@clinebot/core 0.0.0 → 0.0.3
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 +7 -7
- package/dist/default-tools/definitions.d.ts +1 -1
- package/dist/default-tools/executors/index.d.ts +1 -1
- package/dist/default-tools/index.d.ts +2 -1
- package/dist/default-tools/model-tool-routing.d.ts +33 -0
- package/dist/default-tools/schemas.d.ts +13 -7
- package/dist/index.browser.d.ts +1 -0
- package/dist/index.browser.js +220 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +47 -47
- package/dist/index.node.d.ts +36 -0
- package/dist/index.node.js +622 -0
- package/dist/providers/local-provider-service.d.ts +37 -0
- package/dist/session/default-session-manager.d.ts +3 -1
- package/dist/session/session-host.d.ts +2 -2
- package/dist/session/session-manager.d.ts +8 -0
- package/dist/session/unified-session-persistence-service.d.ts +1 -1
- package/dist/session/utils/helpers.d.ts +11 -0
- package/dist/session/utils/types.d.ts +42 -0
- package/dist/session/utils/usage.d.ts +9 -0
- package/dist/storage/provider-settings-manager.d.ts +2 -0
- package/dist/types/config.d.ts +8 -1
- package/dist/types.d.ts +1 -1
- package/package.json +11 -32
- package/src/default-tools/definitions.test.ts +130 -1
- package/src/default-tools/definitions.ts +7 -3
- package/src/default-tools/executors/editor.ts +10 -9
- package/src/default-tools/executors/file-read.test.ts +1 -1
- package/src/default-tools/executors/file-read.ts +11 -6
- package/src/default-tools/executors/index.ts +1 -1
- package/src/default-tools/index.ts +6 -1
- package/src/default-tools/model-tool-routing.test.ts +86 -0
- package/src/default-tools/model-tool-routing.ts +132 -0
- package/src/default-tools/schemas.ts +49 -52
- package/src/index.browser.ts +1 -0
- package/src/{server/index.ts → index.node.ts} +51 -109
- package/src/index.ts +41 -2
- package/src/input/file-indexer.ts +28 -2
- package/src/providers/local-provider-service.ts +591 -0
- package/src/runtime/runtime-builder.test.ts +69 -0
- package/src/runtime/runtime-builder.ts +20 -0
- package/src/runtime/runtime-parity.test.ts +20 -9
- package/src/session/default-session-manager.e2e.test.ts +11 -1
- package/src/session/default-session-manager.test.ts +270 -0
- package/src/session/default-session-manager.ts +109 -191
- package/src/session/index.ts +7 -2
- package/src/session/session-host.ts +30 -18
- package/src/session/session-manager.ts +11 -0
- package/src/session/unified-session-persistence-service.ts +11 -5
- package/src/session/utils/helpers.ts +148 -0
- package/src/session/utils/types.ts +46 -0
- package/src/session/utils/usage.ts +32 -0
- package/src/storage/provider-settings-legacy-migration.test.ts +3 -3
- package/src/storage/provider-settings-manager.test.ts +34 -0
- package/src/storage/provider-settings-manager.ts +22 -1
- package/src/types/config.ts +13 -0
- package/src/types.ts +1 -0
- package/dist/server/index.d.ts +0 -47
- package/dist/server/index.js +0 -641
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
class be{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(e){let t=e.apiBaseUrl.trim();if(!t)throw Error("apiBaseUrl is required");this.apiBaseUrl=t,this.getAuthTokenFn=e.getAuthToken,this.getCurrentUserIdFn=e.getCurrentUserId,this.getOrganizationMemberIdFn=e.getOrganizationMemberId,this.getHeadersFn=e.getHeaders,this.requestTimeoutMs=e.requestTimeoutMs??30000,this.fetchImpl=e.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchBalance(e){let t=await this.resolveUserId(e);return this.request(`/api/v1/users/${encodeURIComponent(t)}/balance`)}async fetchUsageTransactions(e){let t=await this.resolveUserId(e);return(await this.request(`/api/v1/users/${encodeURIComponent(t)}/usages`)).items??[]}async fetchPaymentTransactions(e){let t=await this.resolveUserId(e);return(await this.request(`/api/v1/users/${encodeURIComponent(t)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganizationBalance(e){let t=e.trim();if(!t)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(t)}/balance`)}async fetchOrganizationUsageTransactions(e){let t=e.organizationId.trim();if(!t)throw Error("organizationId is required");let n=await this.resolveOrganizationMemberId(t,e.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/usages`)).items??[]}async switchAccount(e){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:e?.trim()||null},expectNoContent:!0})}async resolveUserId(e){let t=e?.trim();if(t)return t;let s=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(s)return s;let i=await this.fetchMe();if(!i.id?.trim())throw Error("Unable to resolve current user id");return i.id}async resolveOrganizationMemberId(e,t){let n=t?.trim();if(n)return n;let i=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(e):void 0)?.trim();if(i)return i;let o=(await this.fetchUserOrganizations()).find((a)=>a.organizationId===e)?.memberId;if(!o?.trim())throw Error(`Unable to resolve memberId for organization ${e}`);return o}async request(e,t){let n=(await this.getAuthTokenFn())?.trim();if(!n)throw Error("No Cline account auth token found");let s=this.getHeadersFn?await this.getHeadersFn():{},i=new AbortController,r=setTimeout(()=>i.abort(),this.requestTimeoutMs);try{let o=await this.fetchImpl(new URL(e,this.apiBaseUrl),{method:t?.method??"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...s??{}},body:t?.body!==void 0?JSON.stringify(t.body):void 0,signal:i.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(),c;if(a.trim())c=JSON.parse(a);if(!o.ok){let m=typeof c==="object"&&c!==null&&"error"in c?String(c.error):`Cline account request failed with status ${o.status}`;throw Error(m)}if(typeof c==="object"&&c!==null){let m=c;if(typeof m.success==="boolean"){if(!m.success)throw Error(m.error||"Cline account request failed");if(m.data!==void 0)return m.data}}if(c===void 0||c===null)throw Error("Cline account response payload was empty");return c}finally{clearTimeout(r)}}}function Ge(e){return e.action==="clineAccount"}async function Je(e,t){switch(e.operation){case"fetchMe":return t.fetchMe();case"fetchBalance":return t.fetchBalance(e.userId);case"fetchUsageTransactions":return t.fetchUsageTransactions(e.userId);case"fetchPaymentTransactions":return t.fetchPaymentTransactions(e.userId);case"fetchUserOrganizations":return t.fetchUserOrganizations();case"fetchOrganizationBalance":return t.fetchOrganizationBalance(e.organizationId);case"fetchOrganizationUsageTransactions":return t.fetchOrganizationUsageTransactions({organizationId:e.organizationId,memberId:e.memberId});case"switchAccount":return await t.switchAccount(e.organizationId),{updated:!0};default:throw Error(`Unsupported Cline account operation: ${String(e)}`)}}class Ne{executor;constructor(e){this.executor=e}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(e){return this.request({action:"clineAccount",operation:"fetchBalance",...e?.trim()?{userId:e.trim()}:{}})}async fetchUsageTransactions(e){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...e?.trim()?{userId:e.trim()}:{}})}async fetchPaymentTransactions(e){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...e?.trim()?{userId:e.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(e){let t=e.trim();if(!t)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:t})}async fetchOrganizationUsageTransactions(e){let t=e.organizationId.trim();if(!t)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:t,...e.memberId?.trim()?{memberId:e.memberId.trim()}:{}})}async switchAccount(e){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:e?.trim()||null})}async request(e){return(await this.executor.runProviderAction(e)).result}}import{z as p}from"zod";var We=p.object({workspaceRoot:p.string().min(1),cwd:p.string().optional(),provider:p.string().min(1),model:p.string().min(1),mode:p.enum(["act","plan"]).default("act"),apiKey:p.string(),systemPrompt:p.string().optional(),rules:p.string().optional(),maxIterations:p.number().int().positive().optional(),enableTools:p.boolean(),enableSpawn:p.boolean(),enableTeams:p.boolean(),autoApproveTools:p.boolean().optional(),teamName:p.string().min(1),missionStepInterval:p.number().int().positive(),missionTimeIntervalMs:p.number().int().positive()}),Qe=p.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),Ze=p.enum(["user","assistant","tool","system","status","error"]),et=p.object({id:p.string().min(1),sessionId:p.string().nullable(),role:Ze,content:p.string(),createdAt:p.number().int().nonnegative(),meta:p.object({stream:p.enum(["stdout","stderr"]).optional(),toolName:p.string().optional(),iteration:p.number().int().nonnegative().optional(),agentId:p.string().optional(),conversationId:p.string().optional(),hookEventName:p.string().optional(),inputTokens:p.number().int().nonnegative().optional(),outputTokens:p.number().int().nonnegative().optional()}).optional()}),tt=p.object({toolCalls:p.number().int().nonnegative(),tokensIn:p.number().int().nonnegative(),tokensOut:p.number().int().nonnegative()}),zt=p.object({sessionId:p.string().nullable(),status:Qe,config:We,messages:p.array(et),rawTranscript:p.string(),error:p.string().nullable(),summary:tt});import{z as V}from"zod";var nt=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"]),Kt=V.object({adapter:V.string(),botUserName:V.string().optional(),event:nt,payload:V.record(V.string(),V.unknown()),ts:V.string()});var rt=[{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 Ht(e){return Object.fromEntries(rt.flatMap((t)=>{let n=e==="modelsDevKey"?t.modelsDevKey:t.generatedProviderId;return n?[[t.modelsDevKey,n]]:[]}))}var Vt=Ht("generatedProviderId");import{z as I}from"zod";var jt=I.object({agentId:I.string(),conversationId:I.string(),iteration:I.number(),abortSignal:I.custom().optional(),metadata:I.record(I.string(),I.unknown()).optional()}),Yt=I.object({id:I.string(),name:I.string(),input:I.unknown(),output:I.unknown(),error:I.string().optional(),durationMs:I.number(),startedAt:I.date(),endedAt:I.date()});import{z as st}from"zod";function L(e,t){let n=e.safeParse(t);if(!n.success)throw Error(st.prettifyError(n.error));return n.data}function k(e){return st.toJSONSchema(e)}var Ue=["running","completed","failed","cancelled"];var w={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"},se=[w.READ_FILES,w.SEARCH_CODEBASE,w.RUN_COMMANDS,w.FETCH_WEB_CONTENT,w.APPLY_PATCH,w.EDITOR,w.SKILLS,w.ASK];import{createTool as j}from"@clinebot/agents";import{z as f}from"zod";var Gt=f.string().describe("The absolute file path of a text file to read content from"),ie=f.object({file_paths:f.array(Gt).describe("Array of absolute file paths")}),it=f.union([ie,f.array(f.string()),f.string()]),oe=f.object({queries:f.array(f.string()).describe("Array of regex search queries to execute")}),Me=f.string(),ae=f.object({commands:f.array(Me).describe("Array of shell commands to execute")}),ot=f.union([ae,f.array(Me),Me]),at=f.object({url:f.url().describe("The URL to fetch"),prompt:f.string().min(2).describe("Analysis prompt for the fetched content")}),ce=f.object({requests:f.array(at).describe("Array of web fetch requests")}),me=f.object({command:f.enum(["create","str_replace","insert"]).describe("Editor command to execute: create, str_replace, insert, or undo_edit"),path:f.string().min(1).describe("Absolute file path"),file_text:f.string().optional().describe("Full file content used with create"),old_str:f.string().optional().describe("Exact text to replace (must match exactly once)"),new_str:f.string().optional().describe("Replacement or inserted text"),insert_line:f.number().int().optional().describe("Zero-based line index for insert")}).superRefine((e,t)=>{switch(e.command){case"create":if(e.file_text===void 0)t.addIssue({code:f.ZodIssueCode.custom,path:["file_text"],message:"file_text is required for command=create"});break;case"str_replace":if(e.old_str===void 0)t.addIssue({code:f.ZodIssueCode.custom,path:["old_str"],message:"old_str is required for command=str_replace"});break;case"insert":if(e.insert_line===void 0)t.addIssue({code:f.ZodIssueCode.custom,path:["insert_line"],message:"insert_line is required for command=insert"});if(e.new_str===void 0)t.addIssue({code:f.ZodIssueCode.custom,path:["new_str"],message:"new_str is required for command=insert"});break}}),de=f.object({input:f.string().min(1).describe("The apply_patch text payload, including patch instructions")}),ct=f.union([de,f.string()]),ge=f.object({skill:f.string().min(1).describe('The skill name. E.g., "commit", "review-pr", "pdf", or "ms-office-suite:pdf"'),args:f.string().optional().describe("Optional arguments for the skill")}),ue=f.object({question:f.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:f.array(f.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")});function W(e){if(e instanceof Error)return e.message;return String(e)}function Y(e,t,n){return Promise.race([e,new Promise((s,i)=>{setTimeout(()=>i(Error(n)),t)})])}var Jt=`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":
|
|
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
2
|
|
|
3
3
|
%%bash
|
|
4
4
|
apply_patch <<"EOF"
|
|
@@ -53,47 +53,47 @@ apply_patch <<"EOF"
|
|
|
53
53
|
+ raise NotImplementedError()
|
|
54
54
|
|
|
55
55
|
*** End Patch
|
|
56
|
-
EOF`;function mt(e,t={}){let n=t.fileReadTimeoutMs??1e4;return j({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:k(ie),timeoutMs:n*2,retryable:!0,maxRetries:1,execute:async(s,i)=>{let r=L(it,s),o=Array.isArray(r)?r:typeof r==="object"?r.file_paths:[r];return Promise.all(o.map(async(a)=>{try{let c=await Y(e(a,i),n,`File read timed out after ${n}ms`);return{query:a,result:c,success:!0}}catch(c){let m=W(c);return{query:a,result:"",error:`Error reading file: ${m}`,success:!1}}}))}})}function dt(e,t={}){let n=t.searchTimeoutMs??30000,s=t.cwd??process.cwd();return j({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:k(oe),timeoutMs:n*2,retryable:!0,maxRetries:1,execute:async(i,r)=>{let o=L(oe,i);return Promise.all(o.queries.map(async(a)=>{try{let c=await Y(e(a,s,r),n,`Search timed out after ${n}ms`),m=c.length>0&&!c.includes("No results found");return{query:a,result:c,success:m}}catch(c){let m=W(c);return{query:a,result:"",error:`Search failed: ${m}`,success:!1}}}))}})}function gt(e,t={}){let n=t.bashTimeoutMs??30000,s=t.cwd??process.cwd();return j({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:k(ae),timeoutMs:n*2,retryable:!1,maxRetries:0,execute:async(i,r)=>{let o=L(ot,i),a=Array.isArray(o)?o:typeof o==="object"?o.commands:[o];return Promise.all(a.map(async(c)=>{try{let m=await Y(e(c,s,r),n,`Command timed out after ${n}ms`);return{query:c,result:m,success:!0}}catch(m){let d=W(m);return{query:c,result:"",error:`Command failed: ${d}`,success:!1}}}))}})}function ut(e,t={}){let n=t.webFetchTimeoutMs??30000;return j({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:k(ce),timeoutMs:n*2,retryable:!0,maxRetries:2,execute:async(s,i)=>{let r=L(ce,s);return Promise.all(r.requests.map(async(o)=>{try{let a=await Y(e(o.url,o.prompt,i),n,`Web fetch timed out after ${n}ms`);return{query:o.url,result:a,success:!0}}catch(a){let c=W(a);return{query:o.url,result:"",error:`Error fetching web content: ${c}`,success:!1}}}))}})}function lt(e,t={}){let n=t.applyPatchTimeoutMs??30000,s=t.cwd??process.cwd();return j({name:"apply_patch",description:Jt,inputSchema:k(de),timeoutMs:n,retryable:!1,maxRetries:0,execute:async(i,r)=>{let o=L(ct,i),a=typeof o==="string"?o:o.input;try{return{query:"apply_patch",result:await Y(e({input:a},s,r),n,`apply_patch timed out after ${n}ms`),success:!0}}catch(c){return{query:"apply_patch",result:"",error:`apply_patch failed: ${W(c)}`,success:!1}}}})}function pt(e,t={}){let n=t.editorTimeoutMs??30000,s=t.cwd??process.cwd();return j({name:"editor",description:"Edit file using absolute path with create, string replacement, and line insert operations. Supported commands: create, str_replace, insert, undo_edit.",inputSchema:k(me),timeoutMs:n,retryable:!1,maxRetries:0,execute:async(i,r)=>{let o=L(me,i);try{let a=await Y(e(o,s,r),n,`Editor operation timed out after ${n}ms`);return{query:`${o.command}:${o.path}`,result:a,success:!0}}catch(a){let c=W(a);return{query:`${o.command}:${o.path}`,result:"",error:`Editor operation failed: ${c}`,success:!1}}}})}function ft(e,t={}){let n=t.skillsTimeoutMs??15000;return j({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:k(ge),timeoutMs:n,retryable:!1,maxRetries:0,execute:async(s,i)=>{let r=L(ge,s);return Y(e(r.skill,r.args,i),n,`Skills operation timed out after ${n}ms`)}})}function Tt(e,t={}){let n=t.askQuestionTimeoutMs??15000;return j({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:k(ue),timeoutMs:n,retryable:!1,maxRetries:0,execute:async(s,i)=>{let r=L(ue,s);return Y(e(r.question,r.options,i),n,`ask_question timed out after ${n}ms`)}})}function Q(e){let{executors:t,enableReadFiles:n=!0,enableSearch:s=!0,enableBash:i=!0,enableWebFetch:r=!0,enableApplyPatch:o=!1,enableEditor:a=!0,enableSkills:c=!0,enableAskQuestion:m=!0,...d}=e,g=[];if(n&&t.readFile)g.push(mt(t.readFile,d));if(s&&t.search)g.push(dt(t.search,d));if(i&&t.bash)g.push(gt(t.bash,d));if(r&&t.webFetch)g.push(ut(t.webFetch,d));if(a&&t.editor)g.push(pt(t.editor,d));else if(o&&t.applyPatch)g.push(lt(t.applyPatch,d));if(c&&t.skills)g.push(ft(t.skills,d));if(m&&t.askQuestion)g.push(Tt(t.askQuestion,d));return g}var U=(()=>({}));function F(e){if(typeof e!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(e))}function vt(e,t){var n="",s=0,i=-1,r=0,o;for(var a=0;a<=e.length;++a){if(a<e.length)o=e.charCodeAt(a);else if(o===47)break;else o=47;if(o===47){if(i===a-1||r===1);else if(i!==a-1&&r===2){if(n.length<2||s!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var c=n.lastIndexOf("/");if(c!==n.length-1){if(c===-1)n="",s=0;else n=n.slice(0,c),s=n.length-1-n.lastIndexOf("/");i=a,r=0;continue}}else if(n.length===2||n.length===1){n="",s=0,i=a,r=0;continue}}if(t){if(n.length>0)n+="/..";else n="..";s=2}}else{if(n.length>0)n+="/"+e.slice(i+1,a);else n=e.slice(i+1,a);s=a-i-1}i=a,r=0}else if(o===46&&r!==-1)++r;else r=-1}return n}function Wt(e,t){var n=t.dir||t.root,s=t.base||(t.name||"")+(t.ext||"");if(!n)return s;if(n===t.root)return n+s;return n+e+s}function X(){var e="",t=!1,n;for(var s=arguments.length-1;s>=-1&&!t;s--){var i;if(s>=0)i=arguments[s];else{if(n===void 0)n=process.cwd();i=n}if(F(i),i.length===0)continue;e=i+"/"+e,t=i.charCodeAt(0)===47}if(e=vt(e,!t),t)if(e.length>0)return"/"+e;else return"/";else if(e.length>0)return e;else return"."}function G(e){if(F(e),e.length===0)return".";var t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;if(e=vt(e,!t),e.length===0&&!t)e=".";if(e.length>0&&n)e+="/";if(t)return"/"+e;return e}function $(e){return F(e),e.length>0&&e.charCodeAt(0)===47}function B(){if(arguments.length===0)return".";var e;for(var t=0;t<arguments.length;++t){var n=arguments[t];if(F(n),n.length>0)if(e===void 0)e=n;else e+="/"+n}if(e===void 0)return".";return G(e)}function ee(e,t){if(F(e),F(t),e===t)return"";if(e=X(e),t=X(t),e===t)return"";var n=1;for(;n<e.length;++n)if(e.charCodeAt(n)!==47)break;var s=e.length,i=s-n,r=1;for(;r<t.length;++r)if(t.charCodeAt(r)!==47)break;var o=t.length,a=o-r,c=i<a?i:a,m=-1,d=0;for(;d<=c;++d){if(d===c){if(a>c){if(t.charCodeAt(r+d)===47)return t.slice(r+d+1);else if(d===0)return t.slice(r+d)}else if(i>c){if(e.charCodeAt(n+d)===47)m=d;else if(d===0)m=0}break}var g=e.charCodeAt(n+d),v=t.charCodeAt(r+d);if(g!==v)break;else if(g===47)m=d}var l="";for(d=n+m+1;d<=s;++d)if(d===s||e.charCodeAt(d)===47)if(l.length===0)l+="..";else l+="/..";if(l.length>0)return l+t.slice(r+m);else{if(r+=m,t.charCodeAt(r)===47)++r;return t.slice(r)}}function Qt(e){return e}function q(e){if(F(e),e.length===0)return".";var t=e.charCodeAt(0),n=t===47,s=-1,i=!0;for(var r=e.length-1;r>=1;--r)if(t=e.charCodeAt(r),t===47){if(!i){s=r;break}}else i=!1;if(s===-1)return n?"/":".";if(n&&s===1)return"//";return e.slice(0,s)}function Zt(e,t){if(t!==void 0&&typeof t!=="string")throw TypeError('"ext" argument must be a string');F(e);var n=0,s=-1,i=!0,r;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var o=t.length-1,a=-1;for(r=e.length-1;r>=0;--r){var c=e.charCodeAt(r);if(c===47){if(!i){n=r+1;break}}else{if(a===-1)i=!1,a=r+1;if(o>=0)if(c===t.charCodeAt(o)){if(--o===-1)s=r}else o=-1,s=a}}if(n===s)s=a;else if(s===-1)s=e.length;return e.slice(n,s)}else{for(r=e.length-1;r>=0;--r)if(e.charCodeAt(r)===47){if(!i){n=r+1;break}}else if(s===-1)i=!1,s=r+1;if(s===-1)return"";return e.slice(n,s)}}function en(e){F(e);var t=-1,n=0,s=-1,i=!0,r=0;for(var o=e.length-1;o>=0;--o){var a=e.charCodeAt(o);if(a===47){if(!i){n=o+1;break}continue}if(s===-1)i=!1,s=o+1;if(a===46){if(t===-1)t=o;else if(r!==1)r=1}else if(t!==-1)r=-1}if(t===-1||s===-1||r===0||r===1&&t===s-1&&t===n+1)return"";return e.slice(t,s)}function tn(e){if(e===null||typeof e!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return Wt("/",e)}function nn(e){F(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var n=e.charCodeAt(0),s=n===47,i;if(s)t.root="/",i=1;else i=0;var r=-1,o=0,a=-1,c=!0,m=e.length-1,d=0;for(;m>=i;--m){if(n=e.charCodeAt(m),n===47){if(!c){o=m+1;break}continue}if(a===-1)c=!1,a=m+1;if(n===46){if(r===-1)r=m;else if(d!==1)d=1}else if(r!==-1)d=-1}if(r===-1||a===-1||d===0||d===1&&r===a-1&&r===o+1){if(a!==-1)if(o===0&&s)t.base=t.name=e.slice(1,a);else t.base=t.name=e.slice(o,a)}else{if(o===0&&s)t.name=e.slice(1,r),t.base=e.slice(1,a);else t.name=e.slice(o,r),t.base=e.slice(o,a);t.ext=e.slice(r,a)}if(o>0)t.dir=e.slice(0,o-1);else if(s)t.dir="/";return t}var rn="/",sn=":",De=((e)=>(e.posix=e,e))({resolve:X,normalize:G,isAbsolute:$,join:B,relative:ee,_makeLong:Qt,dirname:q,basename:Zt,extname:en,format:tn,parse:nn,sep:rn,delimiter:sn,win32:null,posix:null}),te=De;var T={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},yt=["%%bash","apply_patch","EOF","```"];class _ extends Error{constructor(e){super(e);this.name="DiffError"}}function N(e){let t={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return e.normalize("NFC").replace(/./gu,(n)=>t[n]??n).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class Pe{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(e,t){this.lines=e;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(e){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(e)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(T.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(T.END)??!1}parseNextAction(){let e=this.lines[this.index];if(e?.startsWith(T.UPDATE)){this.parseUpdate(e.substring(T.UPDATE.length).trim());return}if(e?.startsWith(T.DELETE)){this.parseDelete(e.substring(T.DELETE.length).trim());return}if(e?.startsWith(T.ADD)){this.parseAdd(e.substring(T.ADD.length).trim());return}throw new _(`Unknown line while parsing: ${e}`)}checkDuplicate(e,t){if(e in this.patch.actions)throw new _(`Duplicate ${t} for file: ${e}`)}parseUpdate(e){this.checkDuplicate(e,"update"),this.currentPath=e,this.index++;let t=this.lines[this.index]?.startsWith(T.MOVE)?(this.lines[this.index++]??"").substring(T.MOVE.length).trim():void 0;if(!(e in this.currentFiles))throw new _(`Update File Error: Missing File: ${e}`);let n=this.currentFiles[e]??"",s=this.parseUpdateFile(n,e);s.movePath=t,this.patch.actions[e]=s,this.currentPath=void 0}parseUpdateFile(e,t){let n={type:"update",chunks:[]},s=e.split(`
|
|
57
|
-
`),
|
|
58
|
-
${this.lines[this.index]}`);if(a?.trim()){let
|
|
59
|
-
`);this.addWarning({path:this.currentPath||t,chunkIndex:
|
|
60
|
-
`),chunks:[]}}}function
|
|
61
|
-
`));for(let
|
|
62
|
-
`));if(d===a)return[
|
|
63
|
-
`)),g=
|
|
64
|
-
`));if(d===g)return[
|
|
65
|
-
`)),g=
|
|
66
|
-
`));if(d===g)return[
|
|
67
|
-
`)),g=
|
|
68
|
-
`).map((
|
|
69
|
-
`)),s=[];for(let
|
|
70
|
-
`),
|
|
71
|
-
`)}async function
|
|
72
|
-
`)}return
|
|
73
|
-
`)}}
|
|
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
74
|
[stderr]
|
|
75
|
-
${
|
|
76
|
-
|
|
77
|
-
[Output truncated: ${
|
|
78
|
-
`),
|
|
79
|
-
`),
|
|
80
|
-
`)}async function
|
|
81
|
-
${
|
|
82
|
-
`);if(
|
|
83
|
-
`)),await
|
|
84
|
-
`),{encoding:s}),`Inserted content at line ${t} in ${
|
|
85
|
-
`),d=String(
|
|
86
|
-
`)}return
|
|
87
|
-
`);for(let
|
|
88
|
-
Searched ${
|
|
89
|
-
`)}}function
|
|
90
|
-
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,(t,
|
|
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(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,(t,e)=>String.fromCharCode(parseInt(e,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
|
|
91
91
|
`).replace(/\n{3,}/g,`
|
|
92
92
|
|
|
93
|
-
`).trim()}function
|
|
94
|
-
[Content truncated: showing first 50000 of ${
|
|
95
|
-
`)}catch(l){if(clearTimeout(g),l instanceof Error){if(l.name==="AbortError")throw Error(`Request timed out after ${t}ms`);throw l}throw Error(`Fetch failed: ${String(l)}`)}finally{if(c.abortSignal&&v)c.abortSignal.removeEventListener("abort",v)}}}function Ae(e={}){return{readFile:Se(e.fileRead),search:he(e.search),bash:fe(e.bash),webFetch:Ee(e.webFetch),applyPatch:pe(e.applyPatch),editor:Te(e.editor)}}var Fe={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(e){if(e!=="yolo")return{};let t={enabled:!0,autoApprove:!0},n={"*":t};for(let s of se)n[s]=t;return n}function Nt(e,t){let n=Fe[e];return Q({...n,...t})}function kn(e={}){let{executorOptions:t={},executors:n,...s}=e,i={...Ae(t),...n??{}};return Q({...s,executors:i})}var{existsSync:Fn,readFileSync:Bn}=(()=>({}));var{existsSync:Zs,mkdirSync:ei}=(()=>({}));var Ut="cline_mcp_settings.json",wn=process?.env?.HOME||"~";function _e(){let e=process.env.CLINE_DATA_DIR?.trim();if(e)return e;return B(wn,".cline","data")}function Be(){let e=process.env.CLINE_TEAM_DATA_DIR?.trim();if(e)return e;return B(_e(),"teams")}function xe(){let e=process.env.CLINE_PROVIDER_SETTINGS_PATH?.trim();if(e)return e;return B(_e(),"settings","providers.json")}function Xe(){let e=process.env.CLINE_MCP_SETTINGS_PATH?.trim();if(e)return e;return B(_e(),"settings",Ut)}import{z as S}from"zod";var ne=S.record(S.string(),S.string()),Mt=S.record(S.string(),S.unknown()),xn=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:ne.optional()}),Xn=S.object({type:S.literal("sse"),url:S.string().url(),headers:ne.optional()}),$n=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:ne.optional()}),qn=S.discriminatedUnion("type",[xn,Xn,$n]),zn=S.object({transport:qn,disabled:S.boolean().optional(),metadata:Mt.optional()}),Kn=S.enum(["stdio","sse","http","streamableHttp"]).optional(),Dt=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:Kn,disabled:S.boolean().optional(),metadata:Mt.optional()});function $e(e){if(!e)return;if(e==="http")return"streamableHttp";return e}var Hn=Dt.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:ne.optional()}).superRefine((e,t)=>{let n=e.type??$e(e.transportType);if(n&&n!=="stdio")t.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((e)=>({transport:{type:"stdio",command:e.command,args:e.args,cwd:e.cwd,env:e.env},disabled:e.disabled,metadata:e.metadata})),Vn=Dt.extend({url:S.string().url(),headers:ne.optional()}).superRefine((e,t)=>{let n=e.type??$e(e.transportType)??"sse";if(n!=="sse"&&n!=="streamableHttp")t.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((e)=>{if((e.type??$e(e.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:e.url,headers:e.headers},disabled:e.disabled,metadata:e.metadata};return{transport:{type:"sse",url:e.url,headers:e.headers},disabled:e.disabled,metadata:e.metadata}}),jn=S.union([zn,Hn,Vn]),Yn=S.object({mcpServers:S.record(S.string(),jn)}).strict();function Ce(){return Xe()}function qe(e={}){let t=e.filePath??Ce(),n=Bn(t,"utf8"),s;try{s=JSON.parse(n)}catch(r){let o=r instanceof Error?r.message:String(r);throw Error(`Failed to parse MCP settings JSON at "${t}": ${o}`)}let i=Yn.safeParse(s);if(!i.success){let r=i.error.issues.map((o)=>{let a=o.path.join(".");return a?`${a}: ${o.message}`:o.message}).join("; ");throw Error(`Invalid MCP settings at "${t}": ${r}`)}return i.data}function Pt(e={}){let t=e.filePath??Ce();return Fn(t)}function ze(e={}){let t=qe(e);return Object.entries(t.mcpServers).map(([n,s])=>({name:n,transport:s.transport,disabled:s.disabled,metadata:s.metadata}))}async function Lt(e,t={}){let n=ze(t);for(let s of n)await e.registerServer(s);return n}function M(){return Date.now()}function Gn(e){return e.map((t)=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}class Ke{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(e){this.clientFactory=e.clientFactory,this.toolsCacheTtlMs=e.toolsCacheTtlMs??5000}async registerServer(e){await this.runExclusive(e.name,async()=>{let t=this.servers.get(e.name);if(!t){this.servers.set(e.name,{registration:{...e},status:"disconnected",updatedAt:M()});return}let n=JSON.stringify(t.registration.transport)!==JSON.stringify(e.transport);if(t.registration={...e},t.updatedAt=M(),n)await this.disconnectState(t),t.client=void 0,t.toolCache=void 0,t.toolCacheUpdatedAt=void 0})}async unregisterServer(e){await this.runExclusive(e,async()=>{let t=this.requireServer(e);await this.disconnectState(t),this.servers.delete(e)})}async connectServer(e){await this.runExclusive(e,async()=>{let t=this.requireServer(e);await this.connectState(t)})}async disconnectServer(e){await this.runExclusive(e,async()=>{let t=this.requireServer(e);await this.disconnectState(t)})}async setServerDisabled(e,t){await this.runExclusive(e,async()=>{let n=this.requireServer(e);if(n.registration={...n.registration,disabled:t},n.updatedAt=M(),t)await this.disconnectState(n)})}listServers(){return[...this.servers.values()].map((e)=>({name:e.registration.name,status:e.status,disabled:e.registration.disabled===!0,lastError:e.lastError,toolCount:e.toolCache?.length??0,updatedAt:e.updatedAt,metadata:e.registration.metadata})).sort((e,t)=>e.name.localeCompare(t.name))}async listTools(e){let t=this.requireServer(e),n=t.toolCacheUpdatedAt??0;if(t.toolCache&&M()-n<=this.toolsCacheTtlMs)return t.toolCache;return this.refreshTools(e)}async refreshTools(e){return this.runExclusive(e,async()=>{let t=this.requireServer(e),s=await(await this.ensureConnectedClient(t)).listTools(),i=Gn(s);return t.toolCache=i,t.toolCacheUpdatedAt=M(),t.updatedAt=M(),i})}async callTool(e){return this.runExclusive(e.serverName,async()=>{let t=this.requireServer(e.serverName),n=await this.ensureConnectedClient(t);return t.updatedAt=M(),n.callTool({name:e.toolName,arguments:e.arguments,context:e.context})})}async dispose(){let e=[...this.servers.keys()];for(let t of e)await this.unregisterServer(t)}async ensureConnectedClient(e){if(await this.connectState(e),!e.client)throw Error(`MCP server "${e.registration.name}" does not have an initialized client.`);return e.client}async connectState(e){if(e.registration.disabled)throw Error(`MCP server "${e.registration.name}" is disabled and cannot be connected.`);if(e.status==="connected"&&e.client)return;e.status="connecting",e.updatedAt=M();try{let t=e.client??await this.clientFactory(e.registration);await t.connect(),e.client=t,e.status="connected",e.lastError=void 0,e.updatedAt=M()}catch(t){throw e.status="disconnected",e.lastError=t instanceof Error?t.message:String(t),e.updatedAt=M(),t}}async disconnectState(e){if(!e.client){e.status="disconnected",e.updatedAt=M();return}try{await e.client.disconnect()}finally{e.status="disconnected",e.updatedAt=M()}}requireServer(e){let t=this.servers.get(e);if(!t)throw Error(`Unknown MCP server: ${e}`);return t}async runExclusive(e,t){let n=this.operationLocks.get(e)??Promise.resolve(),s,i=new Promise((o)=>{s=o}),r=n.catch(()=>{return}).then(()=>i);this.operationLocks.set(e,r),await n.catch(()=>{return});try{return await t()}finally{if(s?.(),this.operationLocks.get(e)===r)this.operationLocks.delete(e)}}}var{existsSync:Ft,mkdirSync:Jn,readFileSync:Wn,writeFileSync:Qn}=(()=>({}));import{providers as He}from"@clinebot/llms";import{z as J}from"zod";var kt=He.ProviderSettingsSchema,Ve=He.toProviderConfig,wt=J.object({settings:He.ProviderSettingsSchema,updatedAt:J.string().datetime(),tokenSource:J.enum(["manual","oauth","migration"]).default("manual")}),Ie=J.object({version:J.literal(1),lastUsedProvider:J.string().min(1).optional(),providers:J.record(J.string(),wt)});function Oe(){return{version:1,providers:{}}}function Zn(){return new Date().toISOString()}class Bt{filePath;constructor(e={}){this.filePath=e.filePath??xe()}getFilePath(){return this.filePath}read(){if(!Ft(this.filePath))return Oe();try{let e=Wn(this.filePath,"utf8"),t=JSON.parse(e),n=Ie.safeParse(t);if(n.success)return n.data}catch{}return Oe()}write(e){let t=Ie.parse(e),n=q(this.filePath);if(!Ft(n))Jn(n,{recursive:!0});Qn(this.filePath,`${JSON.stringify(t,null,2)}
|
|
96
|
-
`,"utf8")}saveProviderSettings(
|
|
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
97
|
CREATE TABLE IF NOT EXISTS team_events (
|
|
98
98
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
99
99
|
team_name TEXT NOT NULL,
|
|
@@ -170,13 +170,13 @@ Searched ${l} files.`;let E=[`Found ${v.length} result${v.length===1?"":"s"} for
|
|
|
170
170
|
version INTEGER NOT NULL DEFAULT 1,
|
|
171
171
|
PRIMARY KEY(team_name, fragment_id)
|
|
172
172
|
);
|
|
173
|
-
`)}run(
|
|
174
|
-
VALUES (?, ?, ?, ?, NULL, ?)`,[
|
|
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
175
|
VALUES (?, ?, ?, ?)
|
|
176
176
|
ON CONFLICT(team_name) DO UPDATE SET
|
|
177
177
|
state_json = excluded.state_json,
|
|
178
178
|
teammates_json = excluded.teammates_json,
|
|
179
|
-
updated_at = excluded.updated_at`,[s,JSON.stringify(t),JSON.stringify(
|
|
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
180
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
|
|
181
181
|
ON CONFLICT(team_name, task_id) DO UPDATE SET
|
|
182
182
|
title = excluded.title,
|
|
@@ -186,7 +186,7 @@ Searched ${l} files.`;let E=[`Found ${v.length} result${v.length===1?"":"s"} for
|
|
|
186
186
|
depends_on_json = excluded.depends_on_json,
|
|
187
187
|
summary = excluded.summary,
|
|
188
188
|
version = team_tasks.version + 1,
|
|
189
|
-
updated_at = excluded.updated_at`,[s,
|
|
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
190
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
191
191
|
ON CONFLICT(team_name, run_id) DO UPDATE SET
|
|
192
192
|
agent_id = excluded.agent_id,
|
|
@@ -198,14 +198,14 @@ Searched ${l} files.`;let E=[`Found ${v.length} result${v.length===1?"":"s"} for
|
|
|
198
198
|
error = excluded.error,
|
|
199
199
|
lease_owner = excluded.lease_owner,
|
|
200
200
|
heartbeat_at = excluded.heartbeat_at,
|
|
201
|
-
version = team_runs.version + 1`,[s,
|
|
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
202
|
VALUES (?, ?, ?, ?, ?, ?, 1)
|
|
203
203
|
ON CONFLICT(team_name, outcome_id) DO UPDATE SET
|
|
204
204
|
title = excluded.title,
|
|
205
205
|
status = excluded.status,
|
|
206
206
|
schema_json = excluded.schema_json,
|
|
207
207
|
finalized_at = excluded.finalized_at,
|
|
208
|
-
version = team_outcomes.version + 1`,[s,
|
|
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
209
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
210
210
|
ON CONFLICT(team_name, fragment_id) DO UPDATE SET
|
|
211
211
|
outcome_id = excluded.outcome_id,
|
|
@@ -216,5 +216,5 @@ Searched ${l} files.`;let E=[`Found ${v.length} result${v.length===1?"":"s"} for
|
|
|
216
216
|
status = excluded.status,
|
|
217
217
|
reviewed_by = excluded.reviewed_by,
|
|
218
218
|
reviewed_at = excluded.reviewed_at,
|
|
219
|
-
version = team_outcome_fragments.version + 1`,[s,
|
|
220
|
-
WHERE team_name = ? AND status IN ('queued', 'running')`,[t,
|
|
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};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type { AgentConfigWatcher, AgentConfigWatcherEvent, AgentYamlConfig, BuildAgentConfigOverridesOptions, CreateAgentConfigWatcherOptions, CreateInstructionWatcherOptions, CreateRulesConfigDefinitionOptions, CreateSkillsConfigDefinitionOptions, CreateUserInstructionConfigWatcherOptions, CreateWorkflowsConfigDefinitionOptions, HookConfigFileEntry, LoadAgentPluginFromPathOptions, ParseMarkdownFrontmatterResult, ParseYamlFrontmatterResult, ResolveAgentPluginPathsOptions, RuleConfig, SkillConfig, UnifiedConfigDefinition, UnifiedConfigFileCandidate, UnifiedConfigFileContext, UnifiedConfigRecord, UnifiedConfigWatcherEvent, UnifiedConfigWatcherOptions, UserInstructionConfig, UserInstructionConfigType, UserInstructionConfigWatcher, UserInstructionConfigWatcherEvent, WorkflowConfig, } from "./agents";
|
|
2
|
+
export { createAgentConfigDefinition, createAgentConfigWatcher, createRulesConfigDefinition, createSkillsConfigDefinition, createUserInstructionConfigWatcher, createWorkflowsConfigDefinition, discoverPluginModulePaths, HOOK_CONFIG_FILE_EVENT_MAP, HOOKS_CONFIG_DIRECTORY_NAME, HookConfigFileName, listHookConfigFiles, loadAgentPluginFromPath, loadAgentPluginsFromPaths, parseAgentConfigFromYaml, parsePartialAgentConfigFromYaml, parseRuleConfigFromMarkdown, parseSkillConfigFromMarkdown, parseWorkflowConfigFromMarkdown, RULES_CONFIG_DIRECTORY_NAME, resolveAgentPluginPaths, resolveAgentTools, resolveAndLoadAgentPlugins, resolveDocumentsHooksDirectoryPath, resolveDocumentsRulesDirectoryPath, resolveDocumentsWorkflowsDirectoryPath, resolveHooksConfigSearchPaths, resolvePluginConfigSearchPaths, resolveRulesConfigSearchPaths, resolveSkillsConfigSearchPaths, resolveWorkflowsConfigSearchPaths, SKILLS_CONFIG_DIRECTORY_NAME, toHookConfigFileName, toPartialAgentConfig, UnifiedConfigFileWatcher, WORKFLOWS_CONFIG_DIRECTORY_NAME, } from "./agents";
|
|
3
|
+
export { createOAuthClientCallbacks, type OAuthClientCallbacksOptions, } from "./auth/client";
|
|
4
|
+
export { createClineOAuthProvider, getValidClineCredentials, loginClineOAuth, refreshClineToken, } from "./auth/cline";
|
|
5
|
+
export { getValidOpenAICodexCredentials, isOpenAICodexTokenExpired, loginOpenAICodex, normalizeOpenAICodexCredentials, openaiCodexOAuthProvider, refreshOpenAICodexToken, } from "./auth/codex";
|
|
6
|
+
export { createOcaOAuthProvider, createOcaRequestHeaders, DEFAULT_EXTERNAL_IDCS_CLIENT_ID, DEFAULT_EXTERNAL_IDCS_SCOPES, DEFAULT_EXTERNAL_IDCS_URL, DEFAULT_EXTERNAL_OCA_BASE_URL, DEFAULT_INTERNAL_IDCS_CLIENT_ID, DEFAULT_INTERNAL_IDCS_SCOPES, DEFAULT_INTERNAL_IDCS_URL, DEFAULT_INTERNAL_OCA_BASE_URL, generateOcaOpcRequestId, getValidOcaCredentials, loginOcaOAuth, OCI_HEADER_OPC_REQUEST_ID, refreshOcaToken, } from "./auth/oca";
|
|
7
|
+
export { startLocalOAuthServer } from "./auth/server";
|
|
8
|
+
export type { OAuthCredentials, OAuthLoginCallbacks, OAuthPrompt, OAuthProviderInterface, OcaClientMetadata, OcaMode, OcaOAuthConfig, OcaOAuthEnvironmentConfig, OcaOAuthProviderOptions, OcaTokenResolution, } from "./auth/types";
|
|
9
|
+
export * from "./index";
|
|
10
|
+
export type { FastFileIndexOptions, MentionEnricherOptions, MentionEnrichmentResult, } from "./input";
|
|
11
|
+
export { enrichPromptWithMentions, getFileIndex, prewarmFileIndex, } from "./input";
|
|
12
|
+
export { addLocalProvider, ensureCustomProvidersLoaded, getLocalProviderModels, listLocalProviders, loginLocalProvider, normalizeOAuthProvider, resolveLocalClineAuthToken, saveLocalProviderOAuthCredentials, saveLocalProviderSettings, } from "./providers/local-provider-service";
|
|
13
|
+
export { formatRulesForSystemPrompt, isRuleEnabled, listEnabledRulesFromWatcher, loadRulesForSystemPromptFromWatcher, } from "./runtime/rules";
|
|
14
|
+
export { createTeamName, DefaultRuntimeBuilder, } from "./runtime/runtime-builder";
|
|
15
|
+
export { type SandboxCallOptions, SubprocessSandbox, type SubprocessSandboxOptions, } from "./runtime/sandbox/subprocess-sandbox";
|
|
16
|
+
export type { BuiltRuntime, RuntimeBuilder, RuntimeBuilderInput, SessionRuntime, } from "./runtime/session-runtime";
|
|
17
|
+
export { type DesktopToolApprovalOptions, requestDesktopToolApproval, } from "./runtime/tool-approval";
|
|
18
|
+
export type { AvailableWorkflow } from "./runtime/workflows";
|
|
19
|
+
export { listAvailableWorkflowsFromWatcher, resolveWorkflowSlashCommandFromWatcher, } from "./runtime/workflows";
|
|
20
|
+
export { DefaultSessionManager } from "./session/default-session-manager";
|
|
21
|
+
export { RpcCoreSessionService } from "./session/rpc-session-service";
|
|
22
|
+
export { deriveSubsessionStatus, makeSubSessionId, makeTeamTaskSubSessionId, sanitizeSessionToken, } from "./session/session-graph";
|
|
23
|
+
export type { CreateSessionHostOptions, SessionBackend, SessionHost, } from "./session/session-host";
|
|
24
|
+
export { createSessionHost, resolveSessionBackend, } from "./session/session-host";
|
|
25
|
+
export type { SendSessionInput, SessionAccumulatedUsage, SessionManager, StartSessionInput, StartSessionResult, } from "./session/session-manager";
|
|
26
|
+
export type { SessionManifest } from "./session/session-manifest";
|
|
27
|
+
export type { CreateRootSessionWithArtifactsInput, RootSessionArtifacts, } from "./session/session-service";
|
|
28
|
+
export { CoreSessionService } from "./session/session-service";
|
|
29
|
+
export { createSqliteRpcSessionBackend, SqliteRpcSessionBackend, type SqliteRpcSessionBackendOptions, } from "./session/sqlite-rpc-session-backend";
|
|
30
|
+
export type { WorkspaceManager, WorkspaceManagerEvent, } from "./session/workspace-manager";
|
|
31
|
+
export { InMemoryWorkspaceManager } from "./session/workspace-manager";
|
|
32
|
+
export type { WorkspaceManifest } from "./session/workspace-manifest";
|
|
33
|
+
export { buildWorkspaceMetadata, emptyWorkspaceManifest, generateWorkspaceInfo, normalizeWorkspacePath, upsertWorkspaceInfo, WorkspaceInfoSchema, WorkspaceManifestSchema, } from "./session/workspace-manifest";
|
|
34
|
+
export { type MigrateLegacyProviderSettingsOptions, type MigrateLegacyProviderSettingsResult, migrateLegacyProviderSettings, } from "./storage/provider-settings-legacy-migration";
|
|
35
|
+
export { ProviderSettingsManager } from "./storage/provider-settings-manager";
|
|
36
|
+
export { SqliteSessionStore } from "./storage/sqlite-session-store";
|