@clinebot/core 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,220 +0,0 @@
1
- import{z as V}from"zod";var Zn=V.enum(["connector.started","connector.stopping","message.received","message.completed","message.failed","session.started","session.reused","thread.reset","schedule.delivery.started","schedule.delivery.sent","schedule.delivery.failed"]),oe=V.object({adapter:V.string(),botUserName:V.string().optional(),event:Zn,payload:V.record(V.string(),V.unknown()),ts:V.string()});var Gn=[{modelsDevKey:"openai",generatedProviderId:"openai",runtimeProviderId:"openai-native"},{modelsDevKey:"openai",generatedProviderId:"openai",runtimeProviderId:"openai-codex"},{modelsDevKey:"anthropic",generatedProviderId:"anthropic"},{modelsDevKey:"anthropic",generatedProviderId:"anthropic",runtimeProviderId:"claude-code"},{modelsDevKey:"google",generatedProviderId:"gemini"},{modelsDevKey:"deepseek",generatedProviderId:"deepseek"},{modelsDevKey:"xai",generatedProviderId:"xai"},{modelsDevKey:"togetherai",runtimeProviderId:"together",generatedProviderId:"together"},{modelsDevKey:"sap-ai-core",runtimeProviderId:"sapaicore",generatedProviderId:"sapaicore"},{modelsDevKey:"fireworks-ai",runtimeProviderId:"fireworks",generatedProviderId:"fireworks"},{modelsDevKey:"groq",runtimeProviderId:"groq",generatedProviderId:"groq"},{modelsDevKey:"cerebras",runtimeProviderId:"cerebras",generatedProviderId:"cerebras"},{modelsDevKey:"sambanova",runtimeProviderId:"sambanova",generatedProviderId:"sambanova"},{modelsDevKey:"nebius",runtimeProviderId:"nebius",generatedProviderId:"nebius"},{modelsDevKey:"huggingface",runtimeProviderId:"huggingface",generatedProviderId:"huggingface"},{modelsDevKey:"openrouter",runtimeProviderId:"cline",generatedProviderId:"openrouter"},{modelsDevKey:"ollama",runtimeProviderId:"ollama-cloud"},{modelsDevKey:"ollama-cloud",generatedProviderId:"ollama"},{modelsDevKey:"vercel",runtimeProviderId:"dify",generatedProviderId:"vercel-ai-gateway"},{modelsDevKey:"vercel",generatedProviderId:"vercel-ai-gateway"},{modelsDevKey:"aihubmix",runtimeProviderId:"aihubmix",generatedProviderId:"aihubmix"},{modelsDevKey:"hicap",runtimeProviderId:"hicap"},{modelsDevKey:"nous-research",runtimeProviderId:"nousResearch"},{modelsDevKey:"huawei-cloud-maas",runtimeProviderId:"huawei-cloud-maas"},{modelsDevKey:"baseten",runtimeProviderId:"baseten",generatedProviderId:"baseten"},{modelsDevKey:"google-vertex-anthropic",generatedProviderId:"vertex"},{modelsDevKey:"lmstudio",generatedProviderId:"lmstudio"},{modelsDevKey:"zai",generatedProviderId:"zai"},{modelsDevKey:"requesty",generatedProviderId:"requesty"},{modelsDevKey:"amazon-bedrock",generatedProviderId:"bedrock"},{modelsDevKey:"moonshotai",generatedProviderId:"moonshot"},{modelsDevKey:"minimax",generatedProviderId:"minimax"}];function ae(n){return Object.fromEntries(Gn.flatMap((t)=>{let e=n==="modelsDevKey"?t.modelsDevKey:t.generatedProviderId;return e?[[t.modelsDevKey,e]]:[]}))}var me=ae("generatedProviderId");import{z as M}from"zod";var ue=M.object({agentId:M.string(),conversationId:M.string(),iteration:M.number(),abortSignal:M.custom().optional(),metadata:M.record(M.string(),M.unknown()).optional()}),ce=M.object({id:M.string(),name:M.string(),input:M.unknown(),output:M.unknown(),error:M.string().optional(),durationMs:M.number(),startedAt:M.date(),endedAt:M.date()});import{z as ln}from"zod";function X(n,t){let e=n.safeParse(t);if(!e.success)throw Error(ln.prettifyError(e.error));return e.data}function $(n){return ln.toJSONSchema(n)}function nt(n){if(!n?.trim())return"";return tt(n,"user_input")}function tt(n,t){if(!n?.trim())return"";if(!t)return n;let e=new RegExp(`<${t}.*?>(.*?)</${t}>`,"g");return n.replace(e,"$1")}var et="runtime.team.progress.v1",rt="runtime.team.lifecycle.v1";function ge(n){let t=n?.trim();return t?t:void 0}function st(n){return ge(n?.hookLogPath)}var Mn=["running","completed","failed","cancelled"];import{existsSync as it,mkdirSync as ot}from"node:fs";import{dirname as at,join as W}from"node:path";var mt="cline_mcp_settings.json",Nn=process?.env?.HOME||"~",ut=!1;function ct(n){let t=n.trim();if(!t)return;Nn=t,ut=!0}function gt(n){if(ut)return;let t=n.trim();if(!t)return;Nn=t}function K(){let n=process.env.CLINE_DATA_DIR?.trim();if(n)return n;return W(Nn,".cline","data")}function dt(){let n=process.env.CLINE_SESSION_DATA_DIR?.trim();if(n)return n;return W(K(),"sessions")}function Dn(){let n=process.env.CLINE_TEAM_DATA_DIR?.trim();if(n)return n;return W(K(),"teams")}function Ln(){let n=process.env.CLINE_PROVIDER_SETTINGS_PATH?.trim();if(n)return n;return W(K(),"settings","providers.json")}function Sn(){let n=process.env.CLINE_MCP_SETTINGS_PATH?.trim();if(n)return n;return W(K(),"settings",mt)}function kn(n){let t=at(n);if(!it(t))ot(t,{recursive:!0})}function Tt(n){if(n?.trim())return kn(n),at(n);let t=W(K(),"hooks");if(!it(t))ot(t,{recursive:!0});return t}class Pn{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(n){let t=n.apiBaseUrl.trim();if(!t)throw Error("apiBaseUrl is required");this.apiBaseUrl=t,this.getAuthTokenFn=n.getAuthToken,this.getCurrentUserIdFn=n.getCurrentUserId,this.getOrganizationMemberIdFn=n.getOrganizationMemberId,this.getHeadersFn=n.getHeaders,this.requestTimeoutMs=n.requestTimeoutMs??30000,this.fetchImpl=n.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchBalance(n){let t=await this.resolveUserId(n);return this.request(`/api/v1/users/${encodeURIComponent(t)}/balance`)}async fetchUsageTransactions(n){let t=await this.resolveUserId(n);return(await this.request(`/api/v1/users/${encodeURIComponent(t)}/usages`)).items??[]}async fetchPaymentTransactions(n){let t=await this.resolveUserId(n);return(await this.request(`/api/v1/users/${encodeURIComponent(t)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganizationBalance(n){let t=n.trim();if(!t)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(t)}/balance`)}async fetchOrganizationUsageTransactions(n){let t=n.organizationId.trim();if(!t)throw Error("organizationId is required");let e=await this.resolveOrganizationMemberId(t,n.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(t)}/members/${encodeURIComponent(e)}/usages`)).items??[]}async switchAccount(n){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:n?.trim()||null},expectNoContent:!0})}async resolveUserId(n){let t=n?.trim();if(t)return t;let s=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(s)return s;let r=await this.fetchMe();if(!r.id?.trim())throw Error("Unable to resolve current user id");return r.id}async resolveOrganizationMemberId(n,t){let e=t?.trim();if(e)return e;let r=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(n):void 0)?.trim();if(r)return r;let o=(await this.fetchUserOrganizations()).find((a)=>a.organizationId===n)?.memberId;if(!o?.trim())throw Error(`Unable to resolve memberId for organization ${n}`);return o}async request(n,t){let e=(await this.getAuthTokenFn())?.trim();if(!e)throw Error("No Cline account auth token found");let s=this.getHeadersFn?await this.getHeadersFn():{},r=new AbortController,i=setTimeout(()=>r.abort(),this.requestTimeoutMs);try{let o=await this.fetchImpl(new URL(n,this.apiBaseUrl),{method:t?.method??"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...s??{}},body:t?.body!==void 0?JSON.stringify(t.body):void 0,signal:r.signal});if(o.status===204||t?.expectNoContent){if(!o.ok)throw Error(`Cline account request failed with status ${o.status}`);return}let a=await o.text(),m;if(a.trim())m=JSON.parse(a);if(!o.ok){let u=typeof m==="object"&&m!==null&&"error"in m?String(m.error):`Cline account request failed with status ${o.status}`;throw Error(u)}if(typeof m==="object"&&m!==null){let u=m;if(typeof u.success==="boolean"){if(!u.success)throw Error(u.error||"Cline account request failed");if(u.data!==void 0)return u.data}}if(m===void 0||m===null)throw Error("Cline account response payload was empty");return m}finally{clearTimeout(i)}}}function pt(n){return n.action==="clineAccount"}async function _t(n,t){switch(n.operation){case"fetchMe":return t.fetchMe();case"fetchBalance":return t.fetchBalance(n.userId);case"fetchUsageTransactions":return t.fetchUsageTransactions(n.userId);case"fetchPaymentTransactions":return t.fetchPaymentTransactions(n.userId);case"fetchUserOrganizations":return t.fetchUserOrganizations();case"fetchOrganizationBalance":return t.fetchOrganizationBalance(n.organizationId);case"fetchOrganizationUsageTransactions":return t.fetchOrganizationUsageTransactions({organizationId:n.organizationId,memberId:n.memberId});case"switchAccount":return await t.switchAccount(n.organizationId),{updated:!0};default:throw Error(`Unsupported Cline account operation: ${String(n)}`)}}class Fn{executor;constructor(n){this.executor=n}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(n){return this.request({action:"clineAccount",operation:"fetchBalance",...n?.trim()?{userId:n.trim()}:{}})}async fetchUsageTransactions(n){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...n?.trim()?{userId:n.trim()}:{}})}async fetchPaymentTransactions(n){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...n?.trim()?{userId:n.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(n){let t=n.trim();if(!t)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:t})}async fetchOrganizationUsageTransactions(n){let t=n.organizationId.trim();if(!t)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:t,...n.memberId?.trim()?{memberId:n.memberId.trim()}:{}})}async switchAccount(n){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:n?.trim()||null})}async request(n){return(await this.executor.runProviderAction(n)).result}}import{z as T}from"zod";var ft=T.object({workspaceRoot:T.string().min(1),cwd:T.string().optional(),provider:T.string().min(1),model:T.string().min(1),mode:T.enum(["act","plan"]).default("act"),apiKey:T.string(),systemPrompt:T.string().optional(),rules:T.string().optional(),maxIterations:T.number().int().positive().optional(),enableTools:T.boolean(),enableSpawn:T.boolean(),enableTeams:T.boolean(),autoApproveTools:T.boolean().optional(),teamName:T.string().min(1),missionStepInterval:T.number().int().positive(),missionTimeIntervalMs:T.number().int().positive()}),ht=T.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),At=T.enum(["user","assistant","tool","system","status","error"]),Et=T.object({id:T.string().min(1),sessionId:T.string().nullable(),role:At,content:T.string(),createdAt:T.number().int().nonnegative(),meta:T.object({stream:T.enum(["stdout","stderr"]).optional(),toolName:T.string().optional(),iteration:T.number().int().nonnegative().optional(),agentId:T.string().optional(),conversationId:T.string().optional(),hookEventName:T.string().optional(),inputTokens:T.number().int().nonnegative().optional(),outputTokens:T.number().int().nonnegative().optional()}).optional()}),vt=T.object({toolCalls:T.number().int().nonnegative(),tokensIn:T.number().int().nonnegative(),tokensOut:T.number().int().nonnegative()}),de=T.object({sessionId:T.string().nullable(),status:ht,config:ft,messages:T.array(Et),rawTranscript:T.string(),error:T.string().nullable(),summary:vt});var q={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question"},rn=[q.READ_FILES,q.SEARCH_CODEBASE,q.RUN_COMMANDS,q.FETCH_WEB_CONTENT,q.APPLY_PATCH,q.EDITOR,q.SKILLS,q.ASK];import{createTool as Y}from"@clinebot/agents";import{z as A}from"zod";var Te=A.string().describe("The absolute file path of a text file to read content from"),sn=A.object({file_paths:A.array(Te).describe("Array of absolute file paths to get full content from. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),Ct=A.union([sn,A.array(A.string()),A.string()]),on=A.object({queries:A.array(A.string()).describe("Array of regex search queries to execute")}),wn=A.string(),an=A.object({commands:A.array(wn).describe("Array of shell commands to execute.")}),Ot=A.union([an,A.array(wn),wn]),Rt=A.object({url:A.string().describe("The URL to fetch"),prompt:A.string().min(2).describe("Analysis prompt for the fetched content")}),mn=A.object({requests:A.array(Rt).describe("Array of the URLs for the web fetch requests")}),un=A.object({command:A.enum(["create","str_replace","insert"]).describe("Editor command to execute: create, str_replace, insert"),path:A.string().min(1).describe("Absolute file path"),file_text:A.string().nullish().describe("Full file content required for 'create' command"),old_str:A.string().nullish().describe("Exact text to replace (must match exactly once) for 'str_replace' command"),new_str:A.string().nullish().describe("Replacement text for 'str_replace' or 'insert' commands"),insert_line:A.number().int().nullish().describe("Optional one-based line index for 'insert' command")}).refine((n)=>n.command!=="create"||n.file_text!=null,{path:["file_text"],message:"file_text is required for command=create"}).refine((n)=>n.command!=="str_replace"||n.old_str!=null,{path:["old_str"],message:"old_str is required for command=str_replace"}).refine((n)=>n.command!=="insert"||n.insert_line!=null,{path:["insert_line"],message:"insert_line is required for command=insert"}).refine((n)=>n.command!=="insert"||n.new_str!=null,{path:["new_str"],message:"new_str is required for command=insert"}),cn=A.object({input:A.string().min(1).describe("The apply_patch text payload, including patch instructions")}),It=A.union([cn,A.string()]),gn=A.object({skill:A.string().min(1).describe('The skill name. E.g., "commit", "review-pr", "pdf", or "ms-office-suite:pdf"'),args:A.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),dn=A.object({question:A.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:A.array(A.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")});function Q(n){if(n instanceof Error)return n.message;return String(n)}function j(n,t,e){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(Error(e)),t)})])}var pe=`This is a custom utility that makes it more convenient to add, remove, move, or edit code in a single file. \`apply_patch\` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the \`apply_patch\` command, you should pass a message of the following structure as "input":
2
-
3
- %%bash
4
- apply_patch <<"EOF"
5
- *** Begin Patch
6
- [YOUR_PATCH]
7
- *** End Patch
8
- EOF
9
-
10
- Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
11
-
12
- *** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
13
-
14
- In a Add File section, every line of the new file (including blank/empty lines) MUST start with a \`+\` prefix. Do not include any unprefixed lines inside an Add section
15
- In a Update/Delete section, repeat the following for each snippet of code that needs to be changed:
16
- [context_before] -> See below for further instructions on context.
17
- - [old_code] -> Precede the old code with a minus sign.
18
- + [new_code] -> Precede the new, replacement code with a plus sign.
19
- [context_after] -> See below for further instructions on context.
20
-
21
- For instructions on [context_before] and [context_after]:
22
- - By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
23
- - If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
24
- @@ class BaseClass
25
- [3 lines of pre-context]
26
- - [old_code]
27
- + [new_code]
28
- [3 lines of post-context]
29
-
30
- - If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple \`@@\` statements to jump to the right context. For instance:
31
-
32
- @@ class BaseClass
33
- @@ def method():
34
- [3 lines of pre-context]
35
- - [old_code]
36
- + [new_code]
37
- [3 lines of post-context]
38
-
39
- Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
40
-
41
- %%bash
42
- apply_patch <<"EOF"
43
- *** Begin Patch
44
- *** Update File: pygorithm/searching/binary_search.py
45
- @@ class BaseClass
46
- @@ def search():
47
- - pass
48
- + raise NotImplementedError()
49
-
50
- @@ class Subclass
51
- @@ def search():
52
- - pass
53
- + raise NotImplementedError()
54
-
55
- *** End Patch
56
- EOF`;function Ut(n,t={}){let e=t.fileReadTimeoutMs??1e4;return Y({name:"read_files",description:"Read the FULL content of text file at the provided absolute paths. Returns file contents or error messages for each path. ",inputSchema:$(sn),timeoutMs:e*2,retryable:!0,maxRetries:1,execute:async(s,r)=>{let i=X(Ct,s),o=Array.isArray(i)?i:typeof i==="object"?i.file_paths:[i];return Promise.all(o.map(async(a)=>{try{let m=await j(n(a,r),e,`File read timed out after ${e}ms`);return{query:a,result:m,success:!0}}catch(m){let u=Q(m);return{query:a,result:"",error:`Error reading file: ${u}`,success:!1}}}))}})}function Mt(n,t={}){let e=t.searchTimeoutMs??30000,s=t.cwd??process.cwd();return Y({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:$(on),timeoutMs:e*2,retryable:!0,maxRetries:1,execute:async(r,i)=>{let o=X(on,r);return Promise.all(o.queries.map(async(a)=>{try{let m=await j(n(a,s,i),e,`Search timed out after ${e}ms`),u=m.length>0&&!m.includes("No results found");return{query:a,result:m,success:u}}catch(m){let u=Q(m);return{query:a,result:"",error:`Search failed: ${u}`,success:!1}}}))}})}function Nt(n,t={}){let e=t.bashTimeoutMs??30000,s=t.cwd??process.cwd();return Y({name:"run_commands",description:"Run shell commands at the root of the project. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped.",inputSchema:$(an),timeoutMs:e*2,retryable:!1,maxRetries:0,execute:async(r,i)=>{let o=X(Ot,r),a=Array.isArray(o)?o:typeof o==="object"?o.commands:[o];return Promise.all(a.map(async(m)=>{try{let u=await j(n(m,s,i),e,`Command timed out after ${e}ms`);return{query:m,result:u,success:!0}}catch(u){let d=Q(u);return{query:m,result:"",error:`Command failed: ${d}`,success:!1}}}))}})}function Dt(n,t={}){let e=t.webFetchTimeoutMs??30000;return Y({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:$(mn),timeoutMs:e*2,retryable:!0,maxRetries:2,execute:async(s,r)=>{let i=X(mn,s);return Promise.all(i.requests.map(async(o)=>{try{let a=await j(n(o.url,o.prompt,r),e,`Web fetch timed out after ${e}ms`);return{query:o.url,result:a,success:!0}}catch(a){let m=Q(a);return{query:o.url,result:"",error:`Error fetching web content: ${m}`,success:!1}}}))}})}function Lt(n,t={}){let e=t.applyPatchTimeoutMs??30000,s=t.cwd??process.cwd();return Y({name:"apply_patch",description:pe,inputSchema:$(cn),timeoutMs:e,retryable:!1,maxRetries:0,execute:async(r,i)=>{let o=X(It,r),a=typeof o==="string"?o:o.input;try{return{query:"apply_patch",result:await j(n({input:a},s,i),e,`apply_patch timed out after ${e}ms`),success:!0}}catch(m){return{query:"apply_patch",result:"",error:`apply_patch failed: ${Q(m)}`,success:!1}}}})}function St(n,t={}){let e=t.editorTimeoutMs??30000,s=t.cwd??process.cwd();return Y({name:"editor",description:"Edit file using absolute path with create, string replacement, and line insert operations. Supported commands: create, str_replace, insert.",inputSchema:$(un),timeoutMs:e,retryable:!1,maxRetries:0,execute:async(r,i)=>{let o=X(un,r);try{let a=await j(n(o,s,i),e,`Editor operation timed out after ${e}ms`);return{query:`${o.command}:${o.path}`,result:a,success:!0}}catch(a){let m=Q(a);return{query:`${o.command}:${o.path}`,result:"",error:`Editor operation failed: ${m}`,success:!1}}}})}function kt(n,t={}){let e=t.skillsTimeoutMs??15000;return Y({name:"skills",description:'Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command (for example "/commit" or "/review-pr"), invoke this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. Available skills are listed in system-reminder messages in the conversation. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',inputSchema:$(gn),timeoutMs:e,retryable:!1,maxRetries:0,execute:async(s,r)=>{let i=X(gn,s);return j(n(i.skill,i.args||void 0,r),e,`Skills operation timed out after ${e}ms`)}})}function Pt(n,t={}){let e=t.askQuestionTimeoutMs??15000;return Y({name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:$(dn),timeoutMs:e,retryable:!1,maxRetries:0,execute:async(s,r)=>{let i=X(dn,s);return j(n(i.question,i.options,r),e,`ask_question timed out after ${e}ms`)}})}function Z(n){let{executors:t,enableReadFiles:e=!0,enableSearch:s=!0,enableBash:r=!0,enableWebFetch:i=!0,enableApplyPatch:o=!1,enableEditor:a=!0,enableSkills:m=!0,enableAskQuestion:u=!0,...d}=n,g=[];if(e&&t.readFile)g.push(Ut(t.readFile,d));if(s&&t.search)g.push(Mt(t.search,d));if(r&&t.bash)g.push(Nt(t.bash,d));if(i&&t.webFetch)g.push(Dt(t.webFetch,d));if(a&&t.editor)g.push(St(t.editor,d));else if(o&&t.applyPatch)g.push(Lt(t.applyPatch,d));if(m&&t.skills)g.push(kt(t.skills,d));if(u&&t.askQuestion)g.push(Pt(t.askQuestion,d));return g}import*as k from"node:fs/promises";import*as P from"node:path";var h={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},wt=["%%bash","apply_patch","EOF","```"];class I extends Error{constructor(n){super(n);this.name="DiffError"}}function S(n){let t={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return n.normalize("NFC").replace(/./gu,(e)=>t[e]??e).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class Bn{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(n,t){this.lines=n;this.currentFiles=t}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning(n){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(n)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(h.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(h.END)??!1}parseNextAction(){let n=this.lines[this.index];if(n?.startsWith(h.UPDATE)){this.parseUpdate(n.substring(h.UPDATE.length).trim());return}if(n?.startsWith(h.DELETE)){this.parseDelete(n.substring(h.DELETE.length).trim());return}if(n?.startsWith(h.ADD)){this.parseAdd(n.substring(h.ADD.length).trim());return}throw new I(`Unknown line while parsing: ${n}`)}checkDuplicate(n,t){if(n in this.patch.actions)throw new I(`Duplicate ${t} for file: ${n}`)}parseUpdate(n){this.checkDuplicate(n,"update"),this.currentPath=n,this.index++;let t=this.lines[this.index]?.startsWith(h.MOVE)?(this.lines[this.index++]??"").substring(h.MOVE.length).trim():void 0;if(!(n in this.currentFiles))throw new I(`Update File Error: Missing File: ${n}`);let e=this.currentFiles[n]??"",s=this.parseUpdateFile(e,n);s.movePath=t,this.patch.actions[n]=s,this.currentPath=void 0}parseUpdateFile(n,t){let e={type:"update",chunks:[]},s=n.split(`
57
- `),r=0,i=[h.END,h.UPDATE,h.DELETE,h.ADD,h.END_FILE];while(!i.some((o)=>this.lines[this.index]?.startsWith(o.trim()))){let o=this.lines[this.index],a=o?.startsWith("@@ ")?o.substring(3):void 0;if(a!==void 0||(o==="@@"?o:void 0)!==void 0)this.index++;else if(r!==0)throw new I(`Invalid Line:
58
- ${this.lines[this.index]}`);if(a?.trim()){let c=S(a.trim());for(let C=r;C<s.length;C++){let N=s[C];if(N&&(S(N)===c||S(N.trim())===c)){if(r=C+1,S(N.trim())===c&&S(N)!==c)this.fuzz++;break}}}let[u,d,g,p]=he(this.lines,this.index),[f,v,O]=fe(s,u,r,p);if(f===-1){let c=u.join(`
59
- `);this.addWarning({path:this.currentPath||t,chunkIndex:e.chunks.length,message:`Could not find matching context (similarity: ${O.toFixed(2)}). Chunk skipped.`,context:c.length>200?`${c.substring(0,200)}...`:c}),this.index=g}else{this.fuzz+=v;for(let c of d)c.origIndex+=f,e.chunks.push(c);r=f+u.length,this.index=g}}return e}parseDelete(n){if(this.checkDuplicate(n,"delete"),!(n in this.currentFiles))throw new I(`Delete File Error: Missing File: ${n}`);this.patch.actions[n]={type:"delete",chunks:[]},this.index++}parseAdd(n){if(this.checkDuplicate(n,"add"),n in this.currentFiles)throw new I(`Add File Error: File already exists: ${n}`);this.index++;let t=[],e=[h.END,h.UPDATE,h.DELETE,h.ADD];while(this.hasMoreLines()&&!e.some((s)=>this.lines[this.index]?.startsWith(s.trim()))){let s=this.lines[this.index++];if(s===void 0)break;if(!s.startsWith("+"))throw new I(`Invalid Add File line (missing '+'): ${s}`);t.push(s.substring(1))}this.patch.actions[n]={type:"add",newFile:t.join(`
60
- `),chunks:[]}}}function Ft(n,t){let e=n.length>t.length?n:t,s=n.length>t.length?t:n;if(e.length===0)return 1;let r=_e(s,e);return(e.length-r)/e.length}function _e(n,t){let e=t.length+1,s=n.length+1,r=Array(e*s).fill(0),i=(a,m)=>r[a*s+m]??0,o=(a,m,u)=>{r[a*s+m]=u};for(let a=0;a<=t.length;a++)o(a,0,a);for(let a=0;a<=n.length;a++)o(0,a,a);for(let a=1;a<=t.length;a++)for(let m=1;m<=n.length;m++)if(t[a-1]===n[m-1])o(a,m,i(a-1,m-1));else o(a,m,1+Math.min(i(a-1,m-1),i(a,m-1),i(a-1,m)));return i(t.length,n.length)}function fe(n,t,e,s){if(t.length===0)return[e,0,1];let r=0,i=(o)=>{let a=S(t.join(`
61
- `));for(let u=o;u<n.length;u++){let d=S(n.slice(u,u+t.length).join(`
62
- `));if(d===a)return[u,0,1];let g=Ft(d,a);if(g>r)r=g}for(let u=o;u<n.length;u++){let d=S(n.slice(u,u+t.length).map((p)=>p.trimEnd()).join(`
63
- `)),g=S(t.map((p)=>p.trimEnd()).join(`
64
- `));if(d===g)return[u,1,1]}for(let u=o;u<n.length;u++){let d=S(n.slice(u,u+t.length).map((p)=>p.trim()).join(`
65
- `)),g=S(t.map((p)=>p.trim()).join(`
66
- `));if(d===g)return[u,100,1]}let m=0.66;for(let u=o;u<n.length;u++){let d=S(n.slice(u,u+t.length).join(`
67
- `)),g=Ft(d,a);if(g>=m)return[u,1000,g];if(g>r)r=g}return[-1,0,r]};if(s){let[o,a,m]=i(n.length-t.length);if(o!==-1)return[o,a,m];return[o,a,m]=i(e),[o,a+1e4,m]}return i(e)}function he(n,t){let e=t,s=[],r=[],i=[],o=[],a="keep",m=["@@",h.END,h.UPDATE,h.DELETE,h.ADD,h.END_FILE];while(e<n.length){let u=n[e];if(!u||m.some((p)=>u.startsWith(p.trim())))break;if(u==="***")break;if(u.startsWith("***"))throw new I(`Invalid line: ${u}`);e++;let d=a,g=u;if(g[0]==="+")a="add";else if(g[0]==="-")a="delete";else if(g[0]===" ")a="keep";else a="keep",g=` ${g}`;if(g=g.slice(1),a==="keep"&&d!==a){if(i.length||r.length)o.push({origIndex:s.length-r.length,delLines:r,insLines:i});r=[],i=[]}if(a==="delete")r.push(g),s.push(g);else if(a==="add")i.push(g);else s.push(g)}if(i.length||r.length)o.push({origIndex:s.length-r.length,delLines:r,insLines:i});if(e<n.length&&n[e]===h.END_FILE)return e++,[s,o,e,!0];return[s,o,e,!1]}function Xn(n,t,e){let s=P.isAbsolute(t),r=s?P.normalize(t):P.resolve(n,t);if(!e||s)return r;let i=P.relative(n,r);if(i.startsWith("..")||P.isAbsolute(i))throw new I(`Path must stay within cwd: ${t}`);return r}function Bt(n){let t=[],e=!1,s=!1,r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(!e&&wt.some((m)=>o.startsWith(m)))continue;if(o.startsWith(h.BEGIN)){e=!0,s=!0,t.push(o);continue}if(o===h.END){e=!1,t.push(o);continue}let a=o.startsWith(h.ADD)||o.startsWith(h.UPDATE)||o.startsWith(h.DELETE)||o.startsWith(h.MOVE)||o.startsWith(h.SECTION)||o.startsWith("+")||o.startsWith("-")||o.startsWith(" ")||o==="***";if(a&&i!==n.length-1)r=!0;if(e||!s&&a||o===""&&r)t.push(o)}while(t.length>0&&t[t.length-1]==="")t.pop();return!s&&!r?n:t}function Ae(n){let t=n.split(`
68
- `).map((r)=>r.replace(/\r$/,""));t=Bt(t);let e=t.length>0&&t[0].startsWith(h.BEGIN),s=t.length>0&&t[t.length-1]===h.END;if(!e&&!s)return[h.BEGIN,...t,h.END];if(e&&s)return t;throw new I("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.")}function Ee(n,t){let e=Bt(n.split(`
69
- `)),s=[];for(let r of e)for(let i of t){if(!r.startsWith(i))continue;let o=r.substring(i.length).trim();if(!n.trim().endsWith(o))s.push(o);break}return s}function ve(n,t,e){if(t.length===0)return n;let s=n.split(`
70
- `),r=[],i=0;for(let o of t){if(o.origIndex>s.length)throw new I(`${e}: chunk.origIndex ${o.origIndex} > lines.length ${s.length}`);if(i>o.origIndex)throw new I(`${e}: currentIndex ${i} > chunk.origIndex ${o.origIndex}`);r.push(...s.slice(i,o.origIndex)),r.push(...o.insLines),i=o.origIndex+o.delLines.length}return r.push(...s.slice(i)),r.join(`
71
- `)}async function Ce(n,t,e,s){let r=Ee(n,[h.UPDATE,h.DELETE]),i={};for(let o of r){let a=Xn(t,o,s),m;try{m=await k.readFile(a,e)}catch{throw new I(`File not found: ${o}`)}i[o]=m.replace(/\r\n/g,`
72
- `)}return i}function Oe(n,t){let e={};for(let[s,r]of Object.entries(n.actions))switch(r.type){case"delete":e[s]={type:"delete",oldContent:t[s]};break;case"add":if(r.newFile===void 0)throw new I("ADD action without file content");e[s]={type:"add",newContent:r.newFile};break;case"update":e[s]={type:"update",oldContent:t[s],newContent:ve(t[s]??"",r.chunks,s),movePath:r.movePath};break}return e}async function Re(n,t,e,s){let r=[];for(let[i,o]of Object.entries(n)){let a=Xn(t,i,s);switch(o.type){case"delete":await k.rm(a,{force:!0}),r.push(`${i}: [deleted]`);break;case"add":if(o.newContent===void 0)throw new I(`Cannot create ${i} with no content`);await k.mkdir(P.dirname(a),{recursive:!0}),await k.writeFile(a,o.newContent,{encoding:e}),r.push(i);break;case"update":{if(o.newContent===void 0)throw new I(`UPDATE change for ${i} has no new content`);if(o.movePath){let m=Xn(t,o.movePath,s);await k.mkdir(P.dirname(m),{recursive:!0}),await k.writeFile(m,o.newContent,{encoding:e}),await k.rm(a,{force:!0}),r.push(`${i} -> ${o.movePath}`)}else await k.writeFile(a,o.newContent,{encoding:e}),r.push(i);break}}}return r}function Tn(n={}){let{encoding:t="utf-8",restrictToCwd:e=!0}=n;return async(s,r,i)=>{let o=Ae(s.input),a=await Ce(s.input,r,t,e),m=new Bn(o,a),{patch:u,fuzz:d}=m.parse(),g=Oe(u,a),p=await Re(g,r,t,e),f=["Successfully applied patch to the following files:"];for(let v of p)f.push(v);if(d>0)f.push(`Note: Patch applied with fuzz factor ${d}`);if(u.warnings&&u.warnings.length>0)for(let v of u.warnings)f.push(`Warning (${v.path}): ${v.message}`);return f.join(`
73
- `)}}import{spawn as Xt}from"node:child_process";function pn(n={}){let{shell:t=process.platform==="win32"?"cmd.exe":"/bin/bash",timeoutMs:e=30000,maxOutputBytes:s=1e6,env:r={},combineOutput:i=!0}=n;return async(o,a,m)=>{return new Promise((u,d)=>{let g=process.platform==="win32"?["/c",o]:["-c",o],p=process.platform==="win32",f=Xt(t,g,{cwd:a,env:{...process.env,...r},stdio:["pipe","pipe","pipe"],detached:!p}),v=f.pid,O="",c="",C=0,N=!1,D=!1,U=(R)=>{if(D)return;D=!0,d(R)},w=(R)=>{if(D)return;D=!0,u(R)},B=()=>{if(!v)return;if(p){Xt("taskkill",["/pid",String(v),"/T","/F"],{stdio:"ignore",windowsHide:!0}).unref();return}try{process.kill(-v,"SIGKILL")}catch{f.kill("SIGKILL")}},L=setTimeout(()=>{N=!0,B(),U(Error(`Command timed out after ${e}ms`))},e),x=()=>{N=!0,B(),U(Error("Command was aborted"))};if(m.abortSignal)m.abortSignal.addEventListener("abort",x);f.stdout?.on("data",(R)=>{if(C+=R.length,C<=s)O+=R.toString()}),f.stderr?.on("data",(R)=>{if(C+=R.length,C<=s)c+=R.toString()}),f.on("close",(R)=>{if(clearTimeout(L),m.abortSignal)m.abortSignal.removeEventListener("abort",x);if(N)return;let H=i?O+(c?`
74
- [stderr]
75
- ${c}`:""):O;if(C>s)H+=`
76
-
77
- [Output truncated: ${C} bytes total, showing first ${s} bytes]`;if(R!==0){let Un=c||`Command exited with code ${R}`;U(Error(Un))}else w(H)}),f.on("error",(R)=>{if(clearTimeout(L),m.abortSignal)m.abortSignal.removeEventListener("abort",x);U(Error(`Failed to execute command: ${R.message}`))})})}}import*as b from"node:fs/promises";import*as z from"node:path";function Ie(n,t,e){let s=z.isAbsolute(t),r=s?z.normalize(t):z.resolve(n,t);if(!e)return r;if(s)return r;let i=z.relative(n,r);if(i.startsWith("..")||z.isAbsolute(i))throw Error(`Path must stay within cwd: ${t}`);return r}function Ue(n,t){if(t.length===0)return 0;return n.split(t).length-1}function Me(n,t,e){let s=n.split(`
78
- `),r=t.split(`
79
- `),i=Math.max(s.length,r.length),o=["```diff"],a=0;for(let m=0;m<i;m++){if(a>=e){o.push("... diff truncated ...");break}let u=s[m],d=r[m];if(u===d)continue;let g=m+1;if(u!==void 0)o.push(`-${g}: ${u}`),a++;if(d!==void 0&&a<e)o.push(`+${g}: ${d}`),a++}return o.push("```"),o.join(`
80
- `)}async function Ne(n,t,e){return await b.mkdir(z.dirname(n),{recursive:!0}),await b.writeFile(n,t,{encoding:e}),`File created successfully at: ${n}`}async function De(n,t,e,s,r){let i=await b.readFile(n,s),o=Ue(i,t);if(o===0)throw Error(`No replacement performed: text not found in ${n}.`);if(o>1)throw Error(`No replacement performed: multiple occurrences of text found in ${n}.`);let a=i.replace(t,e??"");await b.writeFile(n,a,{encoding:s});let m=Me(i,a,r);return`Edited ${n}
81
- ${m}`}async function Le(n,t,e,s){let i=(await b.readFile(n,s)).split(`
82
- `),o=t-1;if(o<0||o>i.length)throw Error(`Invalid line number: ${t}. Valid range: 1-${i.length}`);return i.splice(o,0,...e.split(`
83
- `)),await b.writeFile(n,i.join(`
84
- `),{encoding:s}),`Inserted content at line ${t} in ${n}.`}function _n(n={}){let{encoding:t="utf-8",restrictToCwd:e=!0,maxDiffLines:s=200}=n;return async(r,i,o)=>{let a=Ie(i,r.path,e);switch(r.command){case"create":if(r.file_text==null)throw Error("Parameter `file_text` is required for command: create");return Ne(a,r.file_text,t);case"str_replace":if(r.old_str==null)throw Error("Parameter `old_str` is required for command: str_replace");return De(a,r.old_str,r.new_str,t,s);case"insert":if(r.insert_line==null)throw Error("Parameter `insert_line` is required for insert command.");if(r.new_str==null)throw Error("Parameter `new_str` is required for insert command.");return Le(a,r.insert_line,r.new_str,t);default:throw Error(`Unrecognized command ${r.command}. Allowed commands are: create, str_replace, insert`)}}}import*as fn from"node:fs/promises";import*as G from"node:path";var Se={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function hn(n={}){let{maxFileSizeBytes:t,encoding:e,includeLineNumbers:s}={...Se,...n};return async(r,i)=>{let o=G.isAbsolute(r)?G.normalize(r):G.resolve(process.cwd(),r),a=await fn.stat(o);if(!a.isFile())throw Error(`Path is not a file: ${o}`);if(a.size>t)throw Error(`File too large: ${a.size} bytes (max: ${t} bytes). Consider reading specific sections or using a different approach.`);let m=await fn.readFile(o,e);if(s){let u=m.split(`
85
- `),d=String(u.length).length;return u.map((g,p)=>`${String(p+1).padStart(d," ")} | ${g}`).join(`
86
- `)}return m}}import*as Kt from"node:fs/promises";import*as En from"node:path";import{spawn as ke}from"node:child_process";import{readdir as Pe}from"node:fs/promises";import qn from"node:path";import{isMainThread as zt,parentPort as $t,Worker as Fe}from"node:worker_threads";var we=15000,Be=1000,Xe=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]),$n=new Map;function $e(n,t){return qn.relative(n,t).split(qn.sep).join("/")}async function ze(n){let e=(await new Promise((s,r)=>{let i=ke("rg",["--files","--hidden","-g","!.git"],{cwd:n,stdio:["ignore","pipe","pipe"]}),o="",a="";i.stdout.on("data",(m)=>{o+=m.toString()}),i.stderr.on("data",(m)=>{a+=m.toString()}),i.on("error",r),i.on("close",(m)=>{if(m===0){s(o);return}r(Error(a||`rg exited with code ${m}`))})})).split(/\r?\n/).map((s)=>s.trim()).filter((s)=>s.length>0).map((s)=>s.replace(/\\/g,"/"));return new Set(e)}async function qt(n,t,e){let s=await Pe(t,{withFileTypes:!0});for(let r of s){let i=qn.join(t,r.name);if(r.isDirectory()){if(Xe.has(r.name))continue;await qt(n,i,e);continue}if(r.isFile())e.add($e(n,i))}}async function qe(n){let t=new Set;return await qt(n,n,t),t}async function yn(n){try{return await ze(n)}catch{return qe(n)}}function ye(){if(zt||!$t)return;let n=$t;n.on("message",(t)=>{if(t.type!=="index")return;yn(t.cwd).then((e)=>{let s={type:"indexResult",requestId:t.requestId,files:Array.from(e)};n.postMessage(s)}).catch((e)=>{let s={type:"indexResult",requestId:t.requestId,error:e instanceof Error?e.message:"Failed to build file index"};n.postMessage(s)})})}class yt{worker=new Fe(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",(n)=>{if(n.type!=="indexResult")return;let t=this.pending.get(n.requestId);if(!t)return;if(this.pending.delete(n.requestId),n.error){t.reject(Error(n.error));return}t.resolve(n.files??[])}),this.worker.on("error",(n)=>{this.flushPending(n)}),this.worker.on("exit",(n)=>{if(n!==0)this.flushPending(Error(`File index worker exited with code ${n}`))})}requestIndex(n){let t=++this.nextRequestId,e=new Promise((r,i)=>{let o=setTimeout(()=>{this.pending.delete(t),i(Error("Timed out waiting for file index worker response"))},Be);o.unref(),this.pending.set(t,{resolve:(a)=>{clearTimeout(o),r(a)},reject:(a)=>{clearTimeout(o),i(a)}})}),s={type:"index",requestId:t,cwd:n};return this.worker.postMessage(s),e}flushPending(n){for(let[t,e]of this.pending.entries())e.reject(n),this.pending.delete(t)}}ye();var zn;function Ke(){if(!zt)return null;if(zn===void 0)zn=new yt;return zn}async function be(n){let t=Ke();if(!t)return yn(n);try{let e=await t.requestIndex(n);return new Set(e)}catch{return yn(n)}}async function An(n,t={}){let e=t.ttlMs??we,s=Date.now(),r=$n.get(n);if(r&&e>0&&s-r.lastBuiltAt<=e&&r.files.size>0)return r.files;if(r?.pending)return r.pending;let i=be(n).then((o)=>{return $n.set(n,{files:o,lastBuiltAt:Date.now(),pending:null}),o});return $n.set(n,{files:r?.files??new Set,lastBuiltAt:r?.lastBuiltAt??0,pending:i}),i}var xe=["ts","tsx","js","jsx","mjs","cjs","json","md","mdx","txt","yaml","yml","toml","py","rb","go","rs","java","kt","swift","c","cpp","h","hpp","css","scss","less","html","vue","svelte","sql","sh","bash","zsh","fish","ps1","env","gitignore","dockerignore","editorconfig"],He=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"];function Ve(n,t,e,s){let r=n.split("/"),i=r[r.length-1]??"";if(r.length-1>s)return!1;for(let m=0;m<r.length-1;m++)if(t.has(r[m]??""))return!1;let a=En.posix.extname(i).slice(1).toLowerCase();return e.has(a)||!a&&!i.startsWith(".")}function vn(n={}){let{includeExtensions:t=xe,excludeDirs:e=He,maxResults:s=100,contextLines:r=2,maxDepth:i=20}=n,o=new Set(e),a=new Set(t.map((m)=>m.toLowerCase()));return async(m,u,d)=>{let g;try{g=new RegExp(m,"gim")}catch(c){throw Error(`Invalid regex pattern: ${m}. ${c instanceof Error?c.message:""}`)}let p=[],f=0,v=await An(u);for(let c of v){if(!Ve(c,o,a,i))continue;if(p.length>=s)break;f++;let C=En.join(u,c);try{let D=(await Kt.readFile(C,"utf-8")).split(`
87
- `);for(let U=0;U<D.length;U++){let w=D[U];g.lastIndex=0;let B;while((B=g.exec(w))!==null){if(p.length>=s)break;let L=Math.max(0,U-r),x=Math.min(D.length-1,U+r),R=[];for(let H=L;H<=x;H++){let Un=H===U?">":" ";R.push(`${Un} ${H+1}: ${D[H]}`)}if(p.push({file:c,line:U+1,column:B.index+1,match:B[0],context:R}),B.index===g.lastIndex)g.lastIndex++}}}catch{}}if(p.length===0)return`No results found for pattern: ${m}
88
- Searched ${f} files.`;let O=[`Found ${p.length} result${p.length===1?"":"s"} for pattern: ${m}`,`Searched ${f} files.`,""];for(let c of p)O.push(`${c.file}:${c.line}:${c.column}`),O.push(...c.context),O.push("");if(p.length>=s)O.push(`(Showing first ${s} results. Refine your search for more specific results.)`);return O.join(`
89
- `)}}function Ye(n){return n.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
90
- `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(t,e)=>String.fromCharCode(parseInt(e,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
91
- `).replace(/\n{3,}/g,`
92
-
93
- `).trim()}function Cn(n={}){let{timeoutMs:t=30000,maxResponseBytes:e=5000000,userAgent:s="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:r={},followRedirects:i=!0}=n;return async(o,a,m)=>{let u;try{u=new URL(o)}catch{throw Error(`Invalid URL: ${o}`)}if(!["http:","https:"].includes(u.protocol))throw Error(`Invalid protocol: ${u.protocol}. Only http and https are supported.`);let d=new AbortController,g=setTimeout(()=>d.abort(),t),p;if(m.abortSignal)p=()=>d.abort(),m.abortSignal.addEventListener("abort",p);try{let f=await fetch(o,{method:"GET",headers:{"User-Agent":s,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...r},redirect:i?"follow":"manual",signal:d.signal});if(clearTimeout(g),!i&&f.status>=300&&f.status<400)return`Redirect to: ${f.headers.get("location")}`;if(!f.ok)throw Error(`HTTP ${f.status}: ${f.statusText}`);let v=f.headers.get("content-type")||"",O=f.body?.getReader();if(!O)throw Error("Failed to read response body");let c=[],C=0;while(!0){let{done:L,value:x}=await O.read();if(L)break;if(C+=x.length,C>e)throw O.cancel(),Error(`Response too large: exceeded ${e} bytes`);c.push(x)}let N=new Uint8Array(C),D=0;for(let L of c)N.set(L,D),D+=L.length;let U=new TextDecoder("utf-8").decode(N),w;if(v.includes("text/html")||v.includes("application/xhtml"))w=Ye(U);else if(v.includes("application/json"))try{let L=JSON.parse(U);w=JSON.stringify(L,null,2)}catch{w=U}else w=U;let B=[`URL: ${o}`,`Content-Type: ${v}`,`Size: ${C} bytes`,"","--- Content ---",w.slice(0,50000)];if(w.length>50000)B.push(`
94
- [Content truncated: showing first 50000 of ${w.length} characters]`);return B.push("","--- Analysis Request ---",`Prompt: ${a}`),B.join(`
95
- `)}catch(f){if(clearTimeout(g),f instanceof Error){if(f.name==="AbortError")throw Error(`Request timed out after ${t}ms`);throw f}throw Error(`Fetch failed: ${String(f)}`)}finally{if(m.abortSignal&&p)m.abortSignal.removeEventListener("abort",p)}}}function On(n={}){return{readFile:hn(n.fileRead),search:vn(n.search),bash:pn(n.bash),webFetch:Cn(n.webFetch),applyPatch:Tn(n.applyPatch),editor:_n(n.editor)}}var Kn={browser:{enableReadFiles:!1,enableSearch:!1,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1},development:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0},readonly:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!0},yolo:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0}};function bt(n){if(n!=="yolo")return{};let t={enabled:!0,autoApprove:!0},e={"*":t};for(let s of rn)e[s]=t;return e}function xt(n,t){let e=Kn[n];return Z({...e,...t})}function je(n={}){let{executorOptions:t={},executors:e,...s}=n,r={...On(t),...e??{}};return Z({...s,executors:r})}import{existsSync as Je,readFileSync as We}from"node:fs";import{z as E}from"zod";var tn=E.record(E.string(),E.string()),Ht=E.record(E.string(),E.unknown()),Qe=E.object({type:E.literal("stdio"),command:E.string().min(1),args:E.array(E.string()).optional(),cwd:E.string().min(1).optional(),env:tn.optional()}),Ze=E.object({type:E.literal("sse"),url:E.string().url(),headers:tn.optional()}),Ge=E.object({type:E.literal("streamableHttp"),url:E.string().url(),headers:tn.optional()}),le=E.discriminatedUnion("type",[Qe,Ze,Ge]),nr=E.object({transport:le,disabled:E.boolean().optional(),metadata:Ht.optional()}),tr=E.enum(["stdio","sse","http","streamableHttp"]).optional(),Vt=E.object({type:E.enum(["stdio","sse","streamableHttp"]).optional(),transportType:tr,disabled:E.boolean().optional(),metadata:Ht.optional()});function bn(n){if(!n)return;if(n==="http")return"streamableHttp";return n}var er=Vt.extend({command:E.string().min(1),args:E.array(E.string()).optional(),cwd:E.string().min(1).optional(),env:tn.optional()}).superRefine((n,t)=>{let e=n.type??bn(n.transportType);if(e&&e!=="stdio")t.addIssue({code:E.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((n)=>({transport:{type:"stdio",command:n.command,args:n.args,cwd:n.cwd,env:n.env},disabled:n.disabled,metadata:n.metadata})),rr=Vt.extend({url:E.string().url(),headers:tn.optional()}).superRefine((n,t)=>{let e=n.type??bn(n.transportType)??"sse";if(e!=="sse"&&e!=="streamableHttp")t.addIssue({code:E.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((n)=>{if((n.type??bn(n.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:n.url,headers:n.headers},disabled:n.disabled,metadata:n.metadata};return{transport:{type:"sse",url:n.url,headers:n.headers},disabled:n.disabled,metadata:n.metadata}}),sr=E.union([nr,er,rr]),ir=E.object({mcpServers:E.record(E.string(),sr)}).strict();function Rn(){return Sn()}function xn(n={}){let t=n.filePath??Rn(),e=We(t,"utf8"),s;try{s=JSON.parse(e)}catch(i){let o=i instanceof Error?i.message:String(i);throw Error(`Failed to parse MCP settings JSON at "${t}": ${o}`)}let r=ir.safeParse(s);if(!r.success){let i=r.error.issues.map((o)=>{let a=o.path.join(".");return a?`${a}: ${o.message}`:o.message}).join("; ");throw Error(`Invalid MCP settings at "${t}": ${i}`)}return r.data}function Yt(n={}){let t=n.filePath??Rn();return Je(t)}function Hn(n={}){let t=xn(n);return Object.entries(t.mcpServers).map(([e,s])=>({name:e,transport:s.transport,disabled:s.disabled,metadata:s.metadata}))}async function jt(n,t={}){let e=Hn(t);for(let s of e)await n.registerServer(s);return e}function F(){return Date.now()}function or(n){return n.map((t)=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}class Vn{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(n){this.clientFactory=n.clientFactory,this.toolsCacheTtlMs=n.toolsCacheTtlMs??5000}async registerServer(n){await this.runExclusive(n.name,async()=>{let t=this.servers.get(n.name);if(!t){this.servers.set(n.name,{registration:{...n},status:"disconnected",updatedAt:F()});return}let e=JSON.stringify(t.registration.transport)!==JSON.stringify(n.transport);if(t.registration={...n},t.updatedAt=F(),e)await this.disconnectState(t),t.client=void 0,t.toolCache=void 0,t.toolCacheUpdatedAt=void 0})}async unregisterServer(n){await this.runExclusive(n,async()=>{let t=this.requireServer(n);await this.disconnectState(t),this.servers.delete(n)})}async connectServer(n){await this.runExclusive(n,async()=>{let t=this.requireServer(n);await this.connectState(t)})}async disconnectServer(n){await this.runExclusive(n,async()=>{let t=this.requireServer(n);await this.disconnectState(t)})}async setServerDisabled(n,t){await this.runExclusive(n,async()=>{let e=this.requireServer(n);if(e.registration={...e.registration,disabled:t},e.updatedAt=F(),t)await this.disconnectState(e)})}listServers(){return[...this.servers.values()].map((n)=>({name:n.registration.name,status:n.status,disabled:n.registration.disabled===!0,lastError:n.lastError,toolCount:n.toolCache?.length??0,updatedAt:n.updatedAt,metadata:n.registration.metadata})).sort((n,t)=>n.name.localeCompare(t.name))}async listTools(n){let t=this.requireServer(n),e=t.toolCacheUpdatedAt??0;if(t.toolCache&&F()-e<=this.toolsCacheTtlMs)return t.toolCache;return this.refreshTools(n)}async refreshTools(n){return this.runExclusive(n,async()=>{let t=this.requireServer(n),s=await(await this.ensureConnectedClient(t)).listTools(),r=or(s);return t.toolCache=r,t.toolCacheUpdatedAt=F(),t.updatedAt=F(),r})}async callTool(n){return this.runExclusive(n.serverName,async()=>{let t=this.requireServer(n.serverName),e=await this.ensureConnectedClient(t);return t.updatedAt=F(),e.callTool({name:n.toolName,arguments:n.arguments,context:n.context})})}async dispose(){let n=[...this.servers.keys()];for(let t of n)await this.unregisterServer(t)}async ensureConnectedClient(n){if(await this.connectState(n),!n.client)throw Error(`MCP server "${n.registration.name}" does not have an initialized client.`);return n.client}async connectState(n){if(n.registration.disabled)throw Error(`MCP server "${n.registration.name}" is disabled and cannot be connected.`);if(n.status==="connected"&&n.client)return;n.status="connecting",n.updatedAt=F();try{let t=n.client??await this.clientFactory(n.registration);await t.connect(),n.client=t,n.status="connected",n.lastError=void 0,n.updatedAt=F()}catch(t){throw n.status="disconnected",n.lastError=t instanceof Error?t.message:String(t),n.updatedAt=F(),t}}async disconnectState(n){if(!n.client){n.status="disconnected",n.updatedAt=F();return}try{await n.client.disconnect()}finally{n.status="disconnected",n.updatedAt=F()}}requireServer(n){let t=this.servers.get(n);if(!t)throw Error(`Unknown MCP server: ${n}`);return t}async runExclusive(n,t){let e=this.operationLocks.get(n)??Promise.resolve(),s,r=new Promise((o)=>{s=o}),i=e.catch(()=>{return}).then(()=>r);this.operationLocks.set(n,i),await e.catch(()=>{return});try{return await t()}finally{if(s?.(),this.operationLocks.get(n)===i)this.operationLocks.delete(n)}}}import{existsSync as lt,mkdirSync as Ar,readFileSync as Er,writeFileSync as vr}from"node:fs";import{basename as ne,dirname as Jn}from"node:path";import{providers as Yn}from"@clinebot/llms";import{z as J}from"zod";var Jt=Yn.ProviderSettingsSchema,jn=Yn.toProviderConfig,Wt=J.object({settings:Yn.ProviderSettingsSchema,updatedAt:J.string().datetime(),tokenSource:J.enum(["manual","oauth","migration"]).default("manual")}),In=J.object({version:J.literal(1),lastUsedProvider:J.string().min(1).optional(),providers:J.record(J.string(),Wt)});function l(){return{version:1,providers:{}}}import{existsSync as ar,readFileSync as mr}from"node:fs";import{join as Qt}from"node:path";import{models as ur,providers as cr}from"@clinebot/llms";function _(n){let t=n?.trim();return t?t:void 0}function Zt(n){if(!ar(n))return;try{let t=mr(n,"utf8"),e=JSON.parse(t);if(e&&typeof e==="object"&&!Array.isArray(e))return e}catch{}return}function gr(n){let t=n.dataDir??K(),e=n.globalStatePath??Qt(t,"globalState.json"),s=n.secretsPath??Qt(t,"secrets.json"),r=Zt(e),i=Zt(s);if(!r&&!i)return;return{globalState:r??{},secrets:i??{}}}function dr(n,t,e,s){let r=e==="plan"?"planMode":"actMode",i=t===s?_(e==="plan"?n.planModeApiModelId:n.actModeApiModelId):void 0,a={openrouter:`${r}OpenRouterModelId`,cline:`${r}ClineModelId`,openai:`${r}OpenAiModelId`,ollama:`${r}OllamaModelId`,lmstudio:`${r}LmStudioModelId`,litellm:`${r}LiteLlmModelId`,requesty:`${r}RequestyModelId`,together:`${r}TogetherModelId`,fireworks:`${r}FireworksModelId`,sapaicore:`${r}SapAiCoreModelId`,groq:`${r}GroqModelId`,baseten:`${r}BasetenModelId`,huggingface:`${r}HuggingFaceModelId`,"huawei-cloud-maas":`${r}HuaweiCloudMaasModelId`,oca:`${r}OcaModelId`,aihubmix:`${r}AihubmixModelId`,hicap:`${r}HicapModelId`,nousResearch:`${r}NousResearchModelId`,"vercel-ai-gateway":`${r}VercelAiGatewayModelId`}[t];return(a?_(typeof n[a]==="string"?n[a]:void 0):void 0)??i}function Tr(n,t,e){let s=e==="plan"?n.planModeReasoningEffort:n.actModeReasoningEffort,r=e==="plan"?n.geminiPlanModeThinkingLevel:n.geminiActModeThinkingLevel,i=e==="plan"?n.planModeThinkingBudgetTokens:n.actModeThinkingBudgetTokens,o=(t==="gemini"?r:void 0)??s,a=o==="none"||o==="low"||o==="medium"||o==="high"?o:void 0,m=typeof i==="number"&&Number.isInteger(i)&&i>0?i:void 0;if(!a&&m===void 0)return;return{...a?{effort:a}:{},...m!==void 0?{budgetTokens:m}:{}}}function pr(n){let t=n["openai-codex-oauth-credentials"];if(!t)return;try{let e=JSON.parse(t),s=_(e.access_token),r=_(e.refresh_token),i=_(e.accountId);if(!s&&!r&&!i)return;return{...s?{apiKey:s}:{},auth:{...s?{accessToken:s}:{},...r?{refreshToken:r}:{},...i?{accountId:i}:{}}}}catch{return}}function _r(n){let t=ur.getGeneratedModelsForProvider(n);return Object.keys(t)[0]??void 0}function fr(n,t,e,s){let r=_(s==="plan"?t.planModeApiProvider:t.actModeApiProvider),i=dr(t,n,s,r)??_r(n),o=Tr(t,n,s),a=typeof t.requestTimeoutMs==="number"&&Number.isInteger(t.requestTimeoutMs)&&t.requestTimeoutMs>0?t.requestTimeoutMs:void 0,m={anthropic:e.apiKey,cline:e.clineApiKey,openai:e.openAiApiKey,"openai-native":e.openAiNativeApiKey,openrouter:e.openRouterApiKey,bedrock:e.awsBedrockApiKey,gemini:e.geminiApiKey,ollama:e.ollamaApiKey,deepseek:e.deepSeekApiKey,requesty:e.requestyApiKey,together:e.togetherApiKey,fireworks:e.fireworksApiKey,qwen:e.qwenApiKey,doubao:e.doubaoApiKey,mistral:e.mistralApiKey,litellm:e.liteLlmApiKey,asksage:e.asksageApiKey,xai:e.xaiApiKey,moonshot:e.moonshotApiKey,zai:e.zaiApiKey,huggingface:e.huggingFaceApiKey,nebius:e.nebiusApiKey,sambanova:e.sambanovaApiKey,cerebras:e.cerebrasApiKey,groq:e.groqApiKey,"huawei-cloud-maas":e.huaweiCloudMaasApiKey,baseten:e.basetenApiKey,"vercel-ai-gateway":e.vercelAiGatewayApiKey,dify:e.difyApiKey,minimax:e.minimaxApiKey,hicap:e.hicapApiKey,aihubmix:e.aihubmixApiKey,nousResearch:e.nousResearchApiKey,oca:e.ocaApiKey,sapaicore:e.sapAiCoreClientId},u={};if(n==="openai-codex")Object.assign(u,pr(e));if(n==="cline"){let c=_(e["cline:clineAccountId"]??e.clineAccountId);if(c)u.auth={...u.auth??{},accountId:c}}if(n==="openai"&&t.openAiHeaders)u.headers=t.openAiHeaders;if(n==="bedrock")u.aws={accessKey:_(e.awsAccessKey),secretKey:_(e.awsSecretKey),sessionToken:_(e.awsSessionToken),region:_(t.awsRegion),authentication:t.awsAuthentication,profile:t.awsUseProfile?_(t.awsProfile):void 0,usePromptCache:t.awsBedrockUsePromptCache,useCrossRegionInference:t.awsUseCrossRegionInference,useGlobalInference:t.awsUseGlobalInference,endpoint:_(t.awsBedrockEndpoint),customModelBaseId:_(s==="plan"?t.planModeAwsBedrockCustomModelBaseId:t.actModeAwsBedrockCustomModelBaseId)};if(n==="vertex")u.gcp={projectId:_(t.vertexProjectId),region:_(t.vertexRegion)};if(n==="openai"&&(t.azureApiVersion||t.azureIdentity!==void 0))u.azure={apiVersion:_(t.azureApiVersion),useIdentity:t.azureIdentity};if(n==="sapaicore")u.sap={clientId:_(e.sapAiCoreClientId),clientSecret:_(e.sapAiCoreClientSecret),tokenUrl:_(t.sapAiCoreTokenUrl),resourceGroup:_(t.sapAiResourceGroup),deploymentId:_(s==="plan"?t.planModeSapAiCoreDeploymentId:t.actModeSapAiCoreDeploymentId),useOrchestrationMode:t.sapAiCoreUseOrchestrationMode};if(n==="oca"){u.oca={mode:t.ocaMode};let c=_(e.ocaRefreshToken);if(c)u.auth={...u.auth??{},refreshToken:c}}if(n==="qwen")u.apiLine=t.qwenApiLine;if(n==="moonshot")u.apiLine=t.moonshotApiLine;if(n==="zai")u.apiLine=t.zaiApiLine;if(n==="minimax")u.apiLine=t.minimaxApiLine;let d={anthropic:t.anthropicBaseUrl,openai:t.openAiBaseUrl,ollama:t.ollamaBaseUrl,lmstudio:t.lmStudioBaseUrl,litellm:t.liteLlmBaseUrl,gemini:t.geminiBaseUrl,requesty:t.requestyBaseUrl,asksage:t.asksageApiUrl,dify:t.difyBaseUrl,oca:t.ocaBaseUrl,aihubmix:t.aihubmixBaseUrl,sapaicore:t.sapAiCoreBaseUrl},g=_(m[n]),p=_(d[n]),f={provider:n,...g?{apiKey:g}:{},...i?{model:i}:{},...p?{baseUrl:p}:{},...o?{reasoning:o}:{},...a?{timeout:a}:{},...u},v=cr.ProviderSettingsSchema.safeParse(f);if(!v.success)return;return Object.keys(f).filter((c)=>c!=="provider").length>0?v.data:void 0}function hr(n,t){let e=new Set;for(let s of[n.actModeApiProvider,n.planModeApiProvider]){let r=_(s);if(r)e.add(r)}if(_(t.apiKey))e.add("anthropic");if(_(t.openRouterApiKey))e.add("openrouter");if(_(t.openAiApiKey))e.add("openai");if(_(t.openAiNativeApiKey))e.add("openai-native");if(_(t["openai-codex-oauth-credentials"]))e.add("openai-codex");if(_(t.geminiApiKey))e.add("gemini");if(_(t.ollamaApiKey))e.add("ollama");if(_(t.awsAccessKey)||_(t.awsBedrockApiKey))e.add("bedrock");if(_(n.vertexProjectId)||_(n.vertexRegion))e.add("vertex");if(_(t.clineApiKey))e.add("cline");if(_(t.ocaApiKey))e.add("oca");return e}function Gt(n){let t=n.providerSettingsManager.read(),e=gr(n);if(!e)return{migrated:!1,providerCount:Object.keys(t.providers).length,lastUsedProvider:t.lastUsedProvider};let{globalState:s,secrets:r}=e,i=s.mode==="plan"?"plan":"act",o=hr(s,r),a=l();a.providers={...t.providers},a.lastUsedProvider=t.lastUsedProvider;let m=new Date().toISOString(),u=0;for(let g of o){if(a.providers[g])continue;let p=fr(g,s,r,i);if(!p)continue;a.providers[g]={settings:p,updatedAt:m,tokenSource:"migration"},u+=1}if(u===0)return{migrated:!1,providerCount:Object.keys(t.providers).length,lastUsedProvider:t.lastUsedProvider};let d=_(i==="plan"?s.planModeApiProvider:s.actModeApiProvider);return a.lastUsedProvider=t.lastUsedProvider??(d&&a.providers[d]?d:Object.keys(a.providers)[0]),n.providerSettingsManager.write(a),{migrated:!0,providerCount:Object.keys(a.providers).length,lastUsedProvider:a.lastUsedProvider}}function Cr(){return new Date().toISOString()}function Or(n){if(ne(n)!=="providers.json")return;let t=Jn(n);if(ne(t)!=="settings")return;return Jn(t)}class te{filePath;dataDir;constructor(n={}){if(this.filePath=n.filePath??Ln(),this.dataDir=n.dataDir??Or(this.filePath),this.dataDir||!n.filePath)Gt({providerSettingsManager:this,dataDir:this.dataDir})}getFilePath(){return this.filePath}read(){if(!lt(this.filePath))return l();try{let n=Er(this.filePath,"utf8"),t=JSON.parse(n),e=In.safeParse(t);if(e.success)return e.data}catch{}return l()}write(n){let t=In.parse(n),e=Jn(this.filePath);if(!lt(e))Ar(e,{recursive:!0});vr(this.filePath,`${JSON.stringify(t,null,2)}
96
- `,"utf8")}saveProviderSettings(n,t={}){let e=Jt.parse(n),s=this.read(),r=e.provider,i=t.setLastUsed!==!1,o=s.providers[r],a=t.tokenSource??o?.tokenSource??"manual",m={...s,providers:{...s.providers,[r]:{settings:e,updatedAt:Cr(),tokenSource:a}},lastUsedProvider:i?r:s.lastUsedProvider};return this.write(m),m}getProviderSettings(n){return this.read().providers[n]?.settings}getLastUsedProviderSettings(){let n=this.read(),t=n.lastUsedProvider;if(!t)return;return n.providers[t]?.settings}getProviderConfig(n){let t=this.getProviderSettings(n);if(!t)return;return jn(t)}getLastUsedProviderConfig(){let n=this.getLastUsedProviderSettings();if(!n)return;return jn(n)}}import{existsSync as Ir,mkdirSync as Ur}from"node:fs";import{join as Mr}from"node:path";import{createRequire as Rr}from"node:module";function en(){return new Date().toISOString()}function Wn(n){let t=Rr(import.meta.url);if(typeof globalThis.Bun<"u"){let{Database:i}=t("bun:sqlite"),o=new i(n,{create:!0});return{prepare:(a)=>{let m=o.query(a);return{run:(...u)=>m.run(...u),get:(...u)=>m.get(...u),all:(...u)=>m.all(...u)}},exec:(a)=>o.exec(a)}}try{let i=["node",":sqlite"].join(""),{DatabaseSync:o}=t(i),a=new o(n);return{prepare:(m)=>{let u=a.prepare(m);return{run:(...d)=>u.run(...d),get:(...d)=>u.get(...d)??null,all:(...d)=>u.all(...d)}},exec:(m)=>a.exec(m)}}catch{}let s=["better","-sqlite3"].join("");return new(t(s))(n)}function Nr(){return Dn()}function nn(n){return n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Dr(n){return{...n,tasks:n.tasks.map((t)=>({...t,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt)})),mailbox:n.mailbox.map((t)=>({...t,sentAt:new Date(t.sentAt),readAt:t.readAt?new Date(t.readAt):void 0})),missionLog:n.missionLog.map((t)=>({...t,ts:new Date(t.ts)})),runs:(n.runs??[]).map((t)=>({...t,startedAt:new Date(t.startedAt),endedAt:t.endedAt?new Date(t.endedAt):void 0,nextAttemptAt:t.nextAttemptAt?new Date(t.nextAttemptAt):void 0,heartbeatAt:t.heartbeatAt?new Date(t.heartbeatAt):void 0})),outcomes:(n.outcomes??[]).map((t)=>({...t,createdAt:new Date(t.createdAt),finalizedAt:t.finalizedAt?new Date(t.finalizedAt):void 0})),outcomeFragments:(n.outcomeFragments??[]).map((t)=>({...t,createdAt:new Date(t.createdAt),reviewedAt:t.reviewedAt?new Date(t.reviewedAt):void 0}))}}class Qn{teamDirPath;db;constructor(n={}){this.teamDirPath=n.teamDir??Nr()}init(){this.getRawDb()}ensureTeamDir(){if(!Ir(this.teamDirPath))Ur(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Mr(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let n=Wn(this.dbPath());return this.ensureSchema(n),this.db=n,n}ensureSchema(n){n.exec(`
97
- CREATE TABLE IF NOT EXISTS team_events (
98
- id INTEGER PRIMARY KEY AUTOINCREMENT,
99
- team_name TEXT NOT NULL,
100
- ts TEXT NOT NULL,
101
- event_type TEXT NOT NULL,
102
- payload_json TEXT NOT NULL,
103
- causation_id TEXT,
104
- correlation_id TEXT
105
- );
106
- CREATE INDEX IF NOT EXISTS idx_team_events_name_ts
107
- ON team_events(team_name, ts DESC);
108
-
109
- CREATE TABLE IF NOT EXISTS team_runtime_snapshot (
110
- team_name TEXT PRIMARY KEY,
111
- state_json TEXT NOT NULL,
112
- teammates_json TEXT NOT NULL,
113
- updated_at TEXT NOT NULL
114
- );
115
-
116
- CREATE TABLE IF NOT EXISTS team_tasks (
117
- team_name TEXT NOT NULL,
118
- task_id TEXT NOT NULL,
119
- title TEXT NOT NULL,
120
- description TEXT NOT NULL,
121
- status TEXT NOT NULL,
122
- assignee TEXT,
123
- depends_on_json TEXT NOT NULL,
124
- summary TEXT,
125
- version INTEGER NOT NULL DEFAULT 1,
126
- updated_at TEXT NOT NULL,
127
- PRIMARY KEY(team_name, task_id)
128
- );
129
-
130
- CREATE TABLE IF NOT EXISTS team_runs (
131
- team_name TEXT NOT NULL,
132
- run_id TEXT NOT NULL,
133
- agent_id TEXT NOT NULL,
134
- task_id TEXT,
135
- status TEXT NOT NULL,
136
- message TEXT NOT NULL,
137
- started_at TEXT,
138
- ended_at TEXT,
139
- error TEXT,
140
- lease_owner TEXT,
141
- heartbeat_at TEXT,
142
- version INTEGER NOT NULL DEFAULT 1,
143
- PRIMARY KEY(team_name, run_id)
144
- );
145
- CREATE INDEX IF NOT EXISTS idx_team_runs_status
146
- ON team_runs(team_name, status);
147
-
148
- CREATE TABLE IF NOT EXISTS team_outcomes (
149
- team_name TEXT NOT NULL,
150
- outcome_id TEXT NOT NULL,
151
- title TEXT NOT NULL,
152
- status TEXT NOT NULL,
153
- schema_json TEXT NOT NULL,
154
- finalized_at TEXT,
155
- version INTEGER NOT NULL DEFAULT 1,
156
- PRIMARY KEY(team_name, outcome_id)
157
- );
158
-
159
- CREATE TABLE IF NOT EXISTS team_outcome_fragments (
160
- team_name TEXT NOT NULL,
161
- outcome_id TEXT NOT NULL,
162
- fragment_id TEXT NOT NULL,
163
- section TEXT NOT NULL,
164
- source_agent_id TEXT NOT NULL,
165
- source_run_id TEXT,
166
- content TEXT NOT NULL,
167
- status TEXT NOT NULL,
168
- reviewed_by TEXT,
169
- reviewed_at TEXT,
170
- version INTEGER NOT NULL DEFAULT 1,
171
- PRIMARY KEY(team_name, fragment_id)
172
- );
173
- `)}run(n,t=[]){return this.getRawDb().prepare(n).run(...t)}queryOne(n,t=[]){return this.getRawDb().prepare(n).get(...t)??void 0}queryAll(n,t=[]){return this.getRawDb().prepare(n).all(...t)}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((n)=>n.team_name)}readState(n){let t=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[nn(n)]);if(!t)return;return Dr(JSON.parse(t.state_json))}readHistory(n,t=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[nn(n),t]).map((e)=>({eventType:e.event_type,payload:JSON.parse(e.payload_json),ts:e.ts}))}loadRuntime(n){let t=nn(n),e=this.readState(t),s=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[t]),r=s?JSON.parse(s.teammates_json):[],i=this.markInProgressRunsInterrupted(t,"runtime_recovered");return{state:e,teammates:r,interruptedRunIds:i}}appendTeamEvent(n,t,e,s){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
174
- VALUES (?, ?, ?, ?, NULL, ?)`,[nn(n),en(),t,JSON.stringify(e),s??null])}persistRuntime(n,t,e){let s=nn(n),r=en();this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
175
- VALUES (?, ?, ?, ?)
176
- ON CONFLICT(team_name) DO UPDATE SET
177
- state_json = excluded.state_json,
178
- teammates_json = excluded.teammates_json,
179
- updated_at = excluded.updated_at`,[s,JSON.stringify(t),JSON.stringify(e),r]);for(let i of t.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
180
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
181
- ON CONFLICT(team_name, task_id) DO UPDATE SET
182
- title = excluded.title,
183
- description = excluded.description,
184
- status = excluded.status,
185
- assignee = excluded.assignee,
186
- depends_on_json = excluded.depends_on_json,
187
- summary = excluded.summary,
188
- version = team_tasks.version + 1,
189
- updated_at = excluded.updated_at`,[s,i.id,i.title,i.description,i.status,i.assignee??null,JSON.stringify(i.dependsOn??[]),i.summary??null,i.updatedAt.toISOString()]);for(let i of t.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
190
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
191
- ON CONFLICT(team_name, run_id) DO UPDATE SET
192
- agent_id = excluded.agent_id,
193
- task_id = excluded.task_id,
194
- status = excluded.status,
195
- message = excluded.message,
196
- started_at = excluded.started_at,
197
- ended_at = excluded.ended_at,
198
- error = excluded.error,
199
- lease_owner = excluded.lease_owner,
200
- heartbeat_at = excluded.heartbeat_at,
201
- version = team_runs.version + 1`,[s,i.id,i.agentId,i.taskId??null,i.status,i.message,i.startedAt?i.startedAt.toISOString():null,i.endedAt?i.endedAt.toISOString():null,i.error??null,i.leaseOwner??null,i.heartbeatAt?i.heartbeatAt.toISOString():null]);for(let i of t.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
202
- VALUES (?, ?, ?, ?, ?, ?, 1)
203
- ON CONFLICT(team_name, outcome_id) DO UPDATE SET
204
- title = excluded.title,
205
- status = excluded.status,
206
- schema_json = excluded.schema_json,
207
- finalized_at = excluded.finalized_at,
208
- version = team_outcomes.version + 1`,[s,i.id,i.title,i.status,JSON.stringify({requiredSections:i.requiredSections}),i.finalizedAt?i.finalizedAt.toISOString():null]);for(let i of t.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
209
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
210
- ON CONFLICT(team_name, fragment_id) DO UPDATE SET
211
- outcome_id = excluded.outcome_id,
212
- section = excluded.section,
213
- source_agent_id = excluded.source_agent_id,
214
- source_run_id = excluded.source_run_id,
215
- content = excluded.content,
216
- status = excluded.status,
217
- reviewed_by = excluded.reviewed_by,
218
- reviewed_at = excluded.reviewed_at,
219
- version = team_outcome_fragments.version + 1`,[s,i.outcomeId,i.id,i.section,i.sourceAgentId,i.sourceRunId??null,i.content,i.status,i.reviewedBy??null,i.reviewedAt?i.reviewedAt.toISOString():null])}markInProgressRunsInterrupted(n,t){let e=nn(n),s=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[e]);if(s.length===0)return[];let r=en();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
220
- WHERE team_name = ? AND status IN ('queued', 'running')`,[t,r,e]),s.map((i)=>i.run_id)}handleTeamEvent(n,t){this.appendTeamEvent(n,t.type,t)}}function y(){return new Date().toISOString()}function ee(n,t){if(t<=0)return 0;return Math.round(n/t*100)}function Lr(n,t){let e=new Set;for(let r of t)if(r.status==="reviewed")e.add(`${r.outcomeId}:${r.section}`);let s=new Set;for(let r of n){if(r.status==="finalized")continue;for(let i of r.requiredSections)if(!e.has(`${r.id}:${i}`))s.add(`${r.id}:${i}`)}return[...s].sort((r,i)=>r.localeCompare(i))}function re(n,t){let e={idle:0,running:0,stopped:0},s={pending:0,in_progress:0,blocked:0,completed:0},r={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},i={draft:0,in_review:0,finalized:0},o={draft:0,reviewed:0,rejected:0},a=0,m=0;for(let c of t.members)if(e[c.status]+=1,c.role==="lead")a+=1;else m+=1;let u=[],d=[],g=t.tasks.filter((c)=>c.status==="completed").length,p=new Map(t.tasks.map((c)=>[c.id,c]));for(let c of t.tasks){if(s[c.status]+=1,c.status==="blocked"){u.push(c.id);continue}if(c.status!=="pending")continue;if(c.dependsOn.every((N)=>{return p.get(N)?.status==="completed"}))d.push(c.id)}let f=[],v,O=0;for(let c of t.runs){if(r[c.status]+=1,c.status==="queued"||c.status==="running")f.push(c.id);let C=c.startedAt.getTime();if(C>=O)O=C,v=c.id}for(let c of t.outcomes)i[c.status]+=1;for(let c of t.outcomeFragments)o[c.status]+=1;return{teamName:n,updatedAt:y(),members:{total:t.members.length,byStatus:e,leadCount:a,teammateCount:m},tasks:{total:t.tasks.length,byStatus:s,blockedTaskIds:u,readyTaskIds:d,completionPct:ee(g,t.tasks.length)},runs:{total:t.runs.length,byStatus:r,activeRunIds:f,latestRunId:v},outcomes:{total:t.outcomes.length,byStatus:i,finalizedPct:ee(i.finalized,t.outcomes.length),missingRequiredSections:Lr(t.outcomes,t.outcomeFragments)},fragments:{total:t.outcomeFragments.length,byStatus:o}}}function se(n){let{event:t}=n;switch(t.type){case"team_task_updated":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),taskId:t.task.id,agentId:t.task.assignee??t.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),runId:t.run.id,taskId:t.run.taskId,agentId:t.run.agentId,message:t.run.error};case"run_progress":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),runId:t.run.id,taskId:t.run.taskId,agentId:t.run.agentId,message:t.message};case"outcome_created":case"outcome_finalized":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),outcomeId:t.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),outcomeId:t.fragment.outcomeId,fragmentId:t.fragment.id,agentId:t.fragment.sourceAgentId};case"team_message":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),taskId:t.message.taskId,agentId:t.message.fromAgentId,message:t.message.subject};case"team_mission_log":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),taskId:t.entry.taskId,agentId:t.entry.agentId,message:t.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),agentId:t.agentId}}return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y()}}var Sr=Mn,ie;((o)=>{o.CLI="cli";o.CLI_SUBAGENT="cli-subagent";o.CORE="core";o.CORE_SUBAGENT="core-subagent";o.DESKTOP="desktop";o.DESKTOP_CHAT="desktop-chat"})(ie||={});export{se as toTeamProgressLifecycleEvent,gt as setHomeDirIfUnset,ct as setHomeDir,dt as resolveSessionDataDir,Hn as resolveMcpServerRegistrations,st as resolveHookLogPath,Rn as resolveDefaultMcpSettingsPath,K as resolveClineDataDir,jt as registerMcpServersFromSettingsFile,nt as normalizeUserInput,xn as loadMcpSettingsFile,pt as isRpcClineAccountActionRequest,Yt as hasMcpSettingsFile,_t as executeRpcClineAccountAction,kn as ensureParentDir,Tt as ensureHookLogDir,l as emptyStoredProviderSettings,bt as createToolPoliciesWithPreset,xt as createDefaultToolsWithPreset,Z as createDefaultTools,On as createDefaultExecutors,je as createBuiltinTools,re as buildTeamProgressSummary,Kn as ToolPresets,In as StoredProviderSettingsSchema,Wt as StoredProviderSettingsEntrySchema,Qn as SqliteTeamStore,ie as SessionSource,Sr as SESSION_STATUSES,Fn as RpcClineAccountService,et as RPC_TEAM_PROGRESS_EVENT_TYPE,rt as RPC_TEAM_LIFECYCLE_EVENT_TYPE,te as ProviderSettingsManager,Vn as InMemoryMcpManager,q as DefaultToolNames,Pn as ClineAccountService,de as ChatViewStateSchema,vt as ChatSummarySchema,ht as ChatSessionStatusSchema,ft as ChatSessionConfigSchema,Et as ChatMessageSchema,At as ChatMessageRoleSchema,rn as ALL_DEFAULT_TOOL_NAMES};
@@ -1 +0,0 @@
1
- export * from "./index";