@cline/agents 0.0.88 → 0.0.89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -69,7 +69,7 @@ The run_commands tool remains available in plan mode strictly for read-only insp
|
|
|
69
69
|
|
|
70
70
|
Once the user has reviewed your plan and explicitly approved it in a follow-up message, use the switch_to_act_mode tool to switch to act mode and begin implementation. Calling switch_to_act_mode immediately starts execution, so never call it in the same turn you present a plan and never treat the original task request as approval -- end your turn after presenting the plan and wait for the user's response.`,bp=`${Ai}
|
|
71
71
|
|
|
72
|
-
Once you have presented your plan, end your turn and wait for the user's response. You do NOT have the ability to switch to act mode yourself -- the user must do it manually with the Plan/Act toggle once they are satisfied with the plan. If the task requires tools that are only available in act mode, ask the user to "toggle to Act mode" (use those words).`;var Yc=m({id:l(),temperature:b().optional(),maxTokens:b().optional(),contextWindow:b().optional(),inputPrice:b().optional(),outputPrice:b().optional(),supportsImages:I().optional()}),Xc=m({models:E(Yc).optional(),openAiBaseUrl:l().optional(),openAiHeaders:D(l(),l()).optional(),azureApiVersion:l().optional(),azureIdentity:I().optional()}),Qc=m({id:l(),thinkingBudgetTokens:b().optional()}),ed=m({name:l(),baseModelId:l(),thinkingBudgetTokens:b().optional()}),td=m({models:E(Qc).optional(),customModels:E(ed).optional(),awsRegion:l().optional(),awsUseCrossRegionInference:I().optional(),awsUseGlobalInference:I().optional(),awsBedrockUsePromptCache:I().optional(),awsBedrockEndpoint:l().optional()}),nd=m({id:l()}),rd=m({models:E(nd).optional()}),id=m({id:l(),thinkingBudgetTokens:b().optional()}),od=m({models:E(id).optional(),vertexProjectId:l().optional(),vertexRegion:l().optional()}),sd=m({id:l(),thinkingBudgetTokens:b().optional(),promptCachingEnabled:I().optional()}),ad=m({models:E(sd).optional(),baseUrl:l().optional()}),ld=m({id:l(),thinkingBudgetTokens:b().optional()}),ud=m({models:E(ld).optional(),baseUrl:l().optional()}),cd=m({OpenAiCompatible:Xc.optional(),AwsBedrock:td.optional(),Cline:rd.optional(),Vertex:od.optional(),LiteLLM:ad.optional(),Anthropic:ud.optional()}),dd=m({id:l()}),pd=m({name:l(),url:l(),alwaysEnabled:I().optional(),headers:D(l(),l()).optional()}),Wn=m({alwaysEnabled:I(),name:l(),contents:l()}),bt=m({bucket:l(),accessKeyId:l(),secretAccessKey:l(),region:l().optional(),endpoint:l().optional(),accountId:l().optional()}),fd=m({enabled:I().optional(),type:ge([L("s3_access_keys"),L("r2_access_keys"),L("azure_access_keys")]).optional(),s3AccessSettings:bt.optional(),r2AccessSettings:bt.optional(),azureAccessSettings:bt.optional()}),hd=m({promptUploading:fd.optional()}),_p=m({version:l(),providerSettings:cd.optional(),telemetryEnabled:I().optional(),kanbanEnabled:I().optional(),mcpMarketplaceEnabled:I().optional(),allowedMCPServers:E(dd).optional(),remoteMCPServers:E(pd).optional(),blockPersonalRemoteMCPServers:I().optional(),yoloModeAllowed:I().optional(),openTelemetryEnabled:I().optional(),openTelemetryMetricsExporter:l().optional(),openTelemetryLogsExporter:l().optional(),openTelemetryOtlpProtocol:l().optional(),openTelemetryOtlpEndpoint:l().optional(),openTelemetryOtlpHeaders:D(l(),l()).optional(),openTelemetryOtlpMetricsProtocol:l().optional(),openTelemetryOtlpMetricsEndpoint:l().optional(),openTelemetryOtlpMetricsHeaders:D(l(),l()).optional(),openTelemetryOtlpLogsProtocol:l().optional(),openTelemetryOtlpLogsEndpoint:l().optional(),openTelemetryOtlpLogsHeaders:D(l(),l()).optional(),openTelemetryMetricExportInterval:b().optional(),openTelemetryOtlpInsecure:I().optional(),openTelemetryLogBatchSize:b().optional(),openTelemetryLogBatchTimeout:b().optional(),openTelemetryLogMaxQueueSize:b().optional(),enterpriseTelemetry:hd.optional(),globalRules:E(Wn).optional(),globalWorkflows:E(Wn).optional()}),wp=D(l(),l());var Tp=A(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),kp=A(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),Ep=A(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var Ii="task.provider_request_started",Si="task.provider_stream_started",xi="task.first_chunk_received",Ci="task.provider_stream_failed",Ri="task.cancelled",$e="task.max_tokens_recovery";var me=new Map;function md(e,t){let n=typeof t.error_message==="string"?t.error_message:"";return[e,t.component,t.operation,t.error_type,t.error_code??"",t.error_status??"",n.replace(/\d+/g,"#").replace(/\s+/g," ").trim().toLowerCase().slice(0,256)].join("\x00")}function gd(e){let t=Date.now(),n=me.get(e);if(n&&t-n.startMs<3600000){if(n.emitted<5)return n.emitted+=1,{emit:!0,suppressed:0};return n.suppressed+=1,{emit:!1,suppressed:n.suppressed}}let r=n?.suppressed??0;if(me.delete(e),me.size>=512){let i=me.keys().next();if(!i.done)me.delete(i.value)}return me.set(e,{startMs:t,emitted:1,suppressed:0}),{emit:!0,suppressed:r}}function Oi(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:Jt({sessionId:t.sessionId,agentId:t.agentId,runId:t.runId,iteration:t.iteration,providerId:t.providerId,modelId:t.modelId,requestedThinking:t.requestedThinking,reasoningTokenCount:t.reasoningTokenCount})})}function Pi(e,t){if(!e)return;e.capture({event:t.event,properties:Jt({sessionId:t.sessionId,ulid:t.ulid??t.sessionId,agentId:t.agentId,conversationId:t.conversationId,runId:t.runId,iteration:t.iteration,provider:t.providerId,providerId:t.providerId,model:t.modelId,modelId:t.modelId,phase:t.phase,durationMs:t.durationMs,eventType:t.eventType,...t.error===void 0?{}:Mi(t.error,t.messageLimit),error_class:t.errorClass})})}function Ni(e,t){if(!e)return!1;let n=t.event??"sdk.error",r=yd(t),i=0;try{let o=gd(md(n,r));if(!o.emit)return!0;i=o.suppressed}catch{}return e.capture({event:n,properties:i>0?{...r,suppressed_count:i}:r}),!0}function yd(e){return Jt({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...Mi(e.error,e.messageLimit,e.errorMessage)})}function Jt(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0)t[n]=r;return t}function Mi(e,t=500,n){let r=_d(e)?e:void 0,i=e instanceof Error?e:void 0,o=Ce(n)??Ce(i?.message)??Ce(r?.message)??wd(e)??"Unknown error",s=Td(r?.code),a=_t(r?.status)??_t(r?.statusCode)??_t(r?.responseStatus);return{error_type:i?.name?.trim()||Ce(r?.name)||i?.constructor?.name||"Error",error_message:bd(vd(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function vd(e){return e.replace(/(authorization=Bearer\s+)[^&\s]+/gi,"$1[redacted]").replace(/(api[_-]?key|access[_-]?token|refresh[_-]?token|authorization|password|secret)=([^&\s]+)/gi,"$1=[redacted]").replace(/(Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi,"$1[redacted]").replace(/\/Users\/[^/\s]+/g,"/Users/[redacted]").replace(/\/home\/[^/\s]+/g,"/home/[redacted]").replace(/([A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s]+/g,"$1[redacted]")}function bd(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function _d(e){return typeof e==="object"&&e!==null}function Ce(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function wd(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Ce(t)}function Td(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function _t(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var kd=["rules","skills","workflows","plugins","hooks"];var Ap=new Set(kd);var Ed=m({rootPath:l().min(1),hint:l().min(1).optional(),associatedRemoteUrls:E(l().min(1)).optional(),latestGitCommitHash:l().min(1).optional(),latestGitBranchName:l().min(1).optional()}),Ip=m({currentWorkspacePath:l().min(1).optional(),workspaces:D(l().min(1),Ed)});var Ad=["current_state","boundary_analysis","interface_proposal"];var X=bi((e)=>e instanceof Date?e.toISOString():e,l().datetime()),ve=A(["pending","in_progress","blocked","completed"]),zi=A(["queued","running","completed","failed","cancelled","interrupted"]),dt=A(["draft","in_review","finalized"]),Id=m({agentId:l(),role:A(["lead","teammate"]),description:l().optional(),status:A(["idle","running","stopped"])}),Sp=m({agentId:l(),rolePrompt:l(),modelId:l().optional(),maxIterations:b().optional()});function N(e){return bi((t)=>t===null?void 0:t,e.optional())}var xp=m({agentId:l().min(1).describe("Teammate identifier"),rolePrompt:l().min(1).describe("System prompt describing teammate role")}).strict(),Cp=m({agentId:l().min(1).describe("Teammate identifier"),reason:N(l().min(1)).describe("Optional shutdown reason")}),Rp=m({}),Sd={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var Op=m({action:A(["create","list","claim","complete","block"]),title:N(l().min(1)).describe("Task title"),description:N(l().min(1)).describe("Task details"),dependsOn:N(E(l().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:N(l().min(1)).describe("Optional assignee"),status:N(A(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:N(l()).describe("Task ID"),summary:N(l().min(1)).describe("Completion summary"),reason:N(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of Sd[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Pp=m({agentId:l().describe("Teammate agent ID"),task:l().min(1).describe("Task instructions for the teammate"),taskId:N(l()).describe("Optional shared task list ID"),runMode:N(A(["sync","async"])).describe("Execution mode: 'sync' blocks until the teammate finishes and returns the result (default if omitted); 'async' queues the run and returns a runId immediately — use team_await_runs to collect results later."),continueConversation:N(I()).describe("If true, continue the teammate conversation; otherwise start fresh")}),Np=m({status:N(A(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:N(l().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:N(I()).describe("Include completed/failed runs (default true)")}),Mp=m({runId:l().min(1).describe("Run ID"),reason:N(l().min(1)).describe("Optional cancellation reason")}),zp=m({runId:N(l().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),$p=m({toAgentId:l().min(1).describe("Recipient agent ID"),subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:N(l().min(1)).describe("Optional task ID context")}),Lp=m({subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:N(l().min(1)).describe("Optional task ID context")}),Dp=m({unreadOnly:N(I()).describe("Only unread messages for read action (default true)")}),Up=m({kind:A(["progress","handoff","blocked","decision","done","error"]),summary:l().min(1).describe("Update summary"),taskId:N(l().min(1)).describe("Optional task ID context"),evidence:N(E(l().min(1))).describe("Optional evidence links/snippets"),nextAction:N(l().min(1)).describe("Planned next step")}),jp=m({}),Bp=m({title:l().describe("Outcome title"),requiredSections:E(l()).default(Ad).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),Fp=m({outcomeId:l().describe("Outcome ID"),section:l().describe("Section name"),sourceRunId:N(l()).describe("Optional source run ID"),content:l().describe("Section fragment content")}),qp=m({fragmentId:l().describe("Fragment ID"),approved:I().describe("Review decision")}),Zp=m({outcomeId:l().describe("Outcome ID")}),Hp=m({}),Vp=m({teamId:l(),teamName:l(),members:E(Id),taskCounts:D(ve,b()),unreadMessages:b(),missionLogEntries:b(),activeRuns:b(),queuedRuns:b(),outcomeCounts:D(dt,b())}),xd=m({id:l(),title:l(),description:l(),status:ve,createdAt:X,updatedAt:X,createdBy:l(),assignee:l().optional(),dependsOn:E(l()),summary:l().optional(),isReady:I(),blockedBy:E(l())}),Wp=Ht("action",[m({action:L("create"),taskId:l(),status:ve,ignoredFields:E(l()).optional(),note:l().optional()}),m({action:L("list"),tasks:E(xd)}),m({action:L("claim"),taskId:l(),status:ve,nextStep:l()}),m({action:L("complete"),taskId:l(),status:ve}),m({action:L("block"),taskId:l(),status:ve})]),Jp=m({agentId:l(),mode:A(["sync","async"]),status:A(["dispatched","running","queued","joined"]),dispatched:I(),message:l(),deduped:I().optional(),runId:l().optional(),text:l().optional(),iterations:b().optional()}),Cd=m({textPreview:l(),iterations:b(),finishReason:l(),durationMs:b(),usage:m({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()})}),Kp=m({id:l(),agentId:l(),taskId:l().optional(),status:zi,messagePreview:l(),priority:b(),retryCount:b(),maxRetries:b(),nextAttemptAt:X.optional(),continueConversation:I().optional(),startedAt:X,endedAt:X.optional(),leaseOwner:l().optional(),heartbeatAt:X.optional(),lastProgressAt:X.optional(),lastProgressMessage:l().optional(),currentActivity:l().optional(),error:l().optional(),resultSummary:Cd.optional()}),Gp=m({id:l(),teamId:l(),fromAgentId:l(),toAgentId:l(),subject:l(),body:l(),taskId:l().optional(),sentAt:X,readAt:X.optional()}),Yp=m({id:l(),teamId:l(),title:l(),status:dt,requiredSections:E(l()),createdBy:l(),createdAt:X,finalizedAt:X.optional()}),Xp=m({outcomeId:l(),status:dt,requiredSections:E(l())}),Qp=m({agentId:l(),status:l()}),ef=m({runId:l(),status:zi}),tf=m({id:l(),toAgentId:l()}),nf=m({delivered:b()}),rf=m({id:l()}),of=m({status:l()}),sf=m({fragmentId:l(),status:l()}),af=m({outcomeId:l(),status:dt}),Rd;((e)=>{e.TaskStart="task_start",e.TaskEnd="task_end",e.AgentEvent="agent_event",e.TeammateSpawned="teammate_spawned",e.TeammateShutdown="teammate_shutdown",e.TeamTaskUpdated="team_task_updated",e.TeamMessage="team_message",e.TeamMissionLog="team_mission_log",e.TeamTaskCompleted="team_task_completed",e.RunStarted="run_started",e.RunQueued="run_queued",e.RunProgress="run_progress",e.RunCompleted="run_completed",e.RunFailed="run_failed",e.RunCancelled="run_cancelled",e.RunInterrupted="run_interrupted",e.OutcomeCreated="outcome_created",e.OutcomeFragmentAttached="outcome_fragment_attached",e.OutcomeFragmentReviewed="outcome_fragment_reviewed",e.OutcomeFinalized="outcome_finalized"})(Rd||={});function Od(e){let{$schema:t,...n}=e;if(typeof n.type==="string")return n;if("properties"in n||"required"in n||"additionalProperties"in n)return{type:"object",...n};for(let r of["oneOf","anyOf","allOf"]){let i=n[r];if(!Array.isArray(i)||i.length===0)continue;if(r==="allOf"){if(i.some((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error('Tool inputSchema must describe an object at the top level, but the schema has a top-level "allOf" with no branch that asserts type: "object". Add type: "object" to at least one allOf branch to make the object constraint explicit.')}if(i.every((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error(`Tool inputSchema must describe an object at the top level, but the schema has a top-level "${r}" whose branches include non-object types. Pass the strict object schema as inputSchema and reserve union/coercion schemas for use inside execute().`)}return n}function Pd(e){let t=Od(e.inputSchema instanceof O?Gc(e.inputSchema):e.inputSchema);return{name:e.name,description:e.description,inputSchema:t,lifecycle:e.lifecycle,executionMode:e.executionMode,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}import{classifyProviderError as $i,createGateway as Nd,isRetryableProviderError as Md}from"@cline/llms";import{nanoid as zd}from"nanoid";var $d="Model reached the maximum output token limit before completing the turn",Kt=3,Ld="Your previous response was cut off because it reached the model's output-token limit before finishing. Keep responses concise: take one small step at a time, avoid long explanations, and write large files or command output in smaller chunks across multiple tool calls.",Gt=3,Dd=1000,Ud=15000,jd="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",Bd="The request exceeds the model's context window and there is no conversation history to compact — the system prompt, tools, and current input alone are too large. Reduce attached content or switch to a model with a larger context window.",Fd="The conversation still exceeds the model's context window after compacting it. Start a new session or switch to a model with a larger context window.",qd="The conversation exceeds the model's context window. Compact the conversation, start a new session, or switch to a model with a larger context window.";class Ee extends Error{constructor(e,t){super(t?.trim()?`${e} (provider reported: ${t.trim()})`:e);this.name="ContextWindowOverflowError"}}function de(e,t=8){return`${e}_${zd(t)}`}function Zd(e){return e.model!==void 0}function Hd(e){if(Zd(e))return e;let{providerId:t,modelId:n,apiKey:r,baseUrl:i,headers:o,options:s,...a}=e,c=Nd({providerConfigs:[{providerId:t,apiKey:r,baseUrl:i,headers:o,options:s}],telemetry:a.telemetry}).createAgentModel({providerId:t,modelId:n}),d=a.messageModelInfo??{id:n,provider:t};return{...a,model:c,messageModelInfo:d}}function Vd(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function Qt(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function Wd(e){if(typeof e==="string")return e.length;return Qt(e)}function Jd(e){let t=e.systemPrompt?.length??0,n=0,r=0,i=0;for(let o of e.messages)for(let s of o.content)switch(s.type){case"text":t+=s.text.length;break;case"reasoning":t+=s.text.length;break;case"file":t+=s.content.length;break;case"tool-call":t+=Qt(s.input);break;case"tool-result":{let a=Wd(s.output);n+=1,r+=a,i=Math.max(i,a),t+=a;break}}return{messageCount:e.messages.length,toolSchemaCount:e.tools.length,systemPromptChars:e.systemPrompt?.length??0,requestJsonChars:Qt({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:ki(t),toolResultCount:n,toolResultChars:r,maxToolResultChars:i}}class en extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class Le extends Error{reason;constructor(e){let t=typeof e==="string"?e:e instanceof Error?e.message:e===void 0?"Run aborted":String(e);super(t);this.name="AgentRuntimeAbortError",this.reason=e}}var Yt={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function he(e,t,n){return{id:de("msg"),role:e,content:t,createdAt:Date.now(),metadata:n}}function ce(e){return{...e}}var Kd={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Li(e){return e.replace(/[_"<>]/g,(t)=>Kd[t])}function Xt(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${Li(e.toolCall.toolName)}"`,`tool_call_id="${Li(e.toolCall.toolCallId)}"`);let r=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
|
|
72
|
+
Once you have presented your plan, end your turn and wait for the user's response. You do NOT have the ability to switch to act mode yourself -- the user must do it manually with the Plan/Act toggle once they are satisfied with the plan. If the task requires tools that are only available in act mode, ask the user to "toggle to Act mode" (use those words).`;var Yc=m({id:l(),temperature:b().optional(),maxTokens:b().optional(),contextWindow:b().optional(),inputPrice:b().optional(),outputPrice:b().optional(),supportsImages:I().optional()}),Xc=m({models:E(Yc).optional(),openAiBaseUrl:l().optional(),openAiHeaders:D(l(),l()).optional(),azureApiVersion:l().optional(),azureIdentity:I().optional()}),Qc=m({id:l(),thinkingBudgetTokens:b().optional()}),ed=m({name:l(),baseModelId:l(),thinkingBudgetTokens:b().optional()}),td=m({models:E(Qc).optional(),customModels:E(ed).optional(),awsRegion:l().optional(),awsUseCrossRegionInference:I().optional(),awsUseGlobalInference:I().optional(),awsBedrockUsePromptCache:I().optional(),awsBedrockEndpoint:l().optional()}),nd=m({id:l()}),rd=m({models:E(nd).optional()}),id=m({id:l(),thinkingBudgetTokens:b().optional()}),od=m({models:E(id).optional(),vertexProjectId:l().optional(),vertexRegion:l().optional()}),sd=m({id:l(),thinkingBudgetTokens:b().optional(),promptCachingEnabled:I().optional()}),ad=m({models:E(sd).optional(),baseUrl:l().optional()}),ld=m({id:l(),thinkingBudgetTokens:b().optional()}),ud=m({models:E(ld).optional(),baseUrl:l().optional()}),cd=m({OpenAiCompatible:Xc.optional(),AwsBedrock:td.optional(),Cline:rd.optional(),Vertex:od.optional(),LiteLLM:ad.optional(),Anthropic:ud.optional()}),dd=m({id:l()}),pd=m({name:l(),url:l(),alwaysEnabled:I().optional(),headers:D(l(),l()).optional()}),Wn=m({alwaysEnabled:I(),name:l(),contents:l()}),bt=m({bucket:l(),accessKeyId:l(),secretAccessKey:l(),region:l().optional(),endpoint:l().optional(),accountId:l().optional()}),fd=m({enabled:I().optional(),type:ge([L("s3_access_keys"),L("r2_access_keys"),L("azure_access_keys")]).optional(),s3AccessSettings:bt.optional(),r2AccessSettings:bt.optional(),azureAccessSettings:bt.optional()}),hd=m({promptUploading:fd.optional()}),_p=m({version:l(),providerSettings:cd.optional(),telemetryEnabled:I().optional(),kanbanEnabled:I().optional(),mcpMarketplaceEnabled:I().optional(),allowedMCPServers:E(dd).optional(),remoteMCPServers:E(pd).optional(),blockPersonalRemoteMCPServers:I().optional(),yoloModeAllowed:I().optional(),openTelemetryEnabled:I().optional(),openTelemetryMetricsExporter:l().optional(),openTelemetryLogsExporter:l().optional(),openTelemetryOtlpProtocol:l().optional(),openTelemetryOtlpEndpoint:l().optional(),openTelemetryOtlpHeaders:D(l(),l()).optional(),openTelemetryOtlpMetricsProtocol:l().optional(),openTelemetryOtlpMetricsEndpoint:l().optional(),openTelemetryOtlpMetricsHeaders:D(l(),l()).optional(),openTelemetryOtlpLogsProtocol:l().optional(),openTelemetryOtlpLogsEndpoint:l().optional(),openTelemetryOtlpLogsHeaders:D(l(),l()).optional(),openTelemetryMetricExportInterval:b().optional(),openTelemetryOtlpInsecure:I().optional(),openTelemetryLogBatchSize:b().optional(),openTelemetryLogBatchTimeout:b().optional(),openTelemetryLogMaxQueueSize:b().optional(),enterpriseTelemetry:hd.optional(),globalRules:E(Wn).optional(),globalWorkflows:E(Wn).optional()}),wp=D(l(),l());var Tp=A(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),kp=A(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),Ep=A(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var Ii="task.provider_request_started",Si="task.provider_stream_started",xi="task.first_chunk_received",Ci="task.provider_stream_failed",Ri="task.cancelled",$e="task.max_tokens_recovery";var me=new Map;function md(e,t){let n=typeof t.error_message==="string"?t.error_message:"";return[e,t.component,t.operation,t.error_type,t.error_code??"",t.error_status??"",n.replace(/\d+/g,"#").replace(/\s+/g," ").trim().toLowerCase().slice(0,256)].join("\x00")}function gd(e){let t=Date.now(),n=me.get(e);if(n&&t-n.startMs<3600000){if(n.emitted<5)return n.emitted+=1,{emit:!0,suppressed:0};return n.suppressed+=1,{emit:!1,suppressed:n.suppressed}}let r=n?.suppressed??0;if(me.delete(e),me.size>=512){let i=me.keys().next();if(!i.done)me.delete(i.value)}return me.set(e,{startMs:t,emitted:1,suppressed:0}),{emit:!0,suppressed:r}}function Oi(e,t){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:Jt({sessionId:t.sessionId,agentId:t.agentId,runId:t.runId,iteration:t.iteration,providerId:t.providerId,modelId:t.modelId,requestedThinking:t.requestedThinking,reasoningTokenCount:t.reasoningTokenCount})})}function Pi(e,t){if(!e)return;e.capture({event:t.event,properties:Jt({sessionId:t.sessionId,ulid:t.ulid??t.sessionId,agentId:t.agentId,conversationId:t.conversationId,runId:t.runId,iteration:t.iteration,provider:t.providerId,providerId:t.providerId,model:t.modelId,modelId:t.modelId,phase:t.phase,durationMs:t.durationMs,eventType:t.eventType,...t.error===void 0?{}:Mi(t.error,t.messageLimit),error_class:t.errorClass})})}function Ni(e,t){if(!e)return!1;let n=t.event??"sdk.error",r=yd(t),i=0;try{let o=gd(md(n,r));if(!o.emit)return!0;i=o.suppressed}catch{}return e.capture({event:n,properties:i>0?{...r,suppressed_count:i}:r}),!0}function yd(e){return Jt({...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...Mi(e.error,e.messageLimit,e.errorMessage)})}function Jt(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0)t[n]=r;return t}function Mi(e,t=500,n){let r=_d(e)?e:void 0,i=e instanceof Error?e:void 0,o=Ce(n)??Ce(i?.message)??Ce(r?.message)??wd(e)??"Unknown error",s=Td(r?.code),a=_t(r?.status)??_t(r?.statusCode)??_t(r?.responseStatus);return{error_type:i?.name?.trim()||Ce(r?.name)||i?.constructor?.name||"Error",error_message:bd(vd(o),t),...s!==void 0?{error_code:s}:{},...a!==void 0?{error_status:a}:{}}}function vd(e){return e.replace(/(authorization=Bearer\s+)[^&\s]+/gi,"$1[redacted]").replace(/(api[_-]?key|access[_-]?token|refresh[_-]?token|authorization|password|secret)=([^&\s]+)/gi,"$1=[redacted]").replace(/(Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi,"$1[redacted]").replace(/\/Users\/[^/\s]+/g,"/Users/[redacted]").replace(/\/home\/[^/\s]+/g,"/home/[redacted]").replace(/([A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s]+/g,"$1[redacted]")}function bd(e,t){let n=Math.max(1,Math.floor(t));return e.length>n?e.substring(0,n):e}function _d(e){return typeof e==="object"&&e!==null}function Ce(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function wd(e){if(e instanceof Error)return;let t=typeof e==="string"?e:String(e);return t==="[object Object]"?void 0:Ce(t)}function Td(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function _t(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var kd=["rules","skills","workflows","plugins","hooks"];var Ap=new Set(kd);var Ed=m({rootPath:l().min(1),hint:l().min(1).optional(),associatedRemoteUrls:E(l().min(1)).optional(),latestGitCommitHash:l().min(1).optional(),latestGitBranchName:l().min(1).optional()}),Ip=m({currentWorkspacePath:l().min(1).optional(),workspaces:D(l().min(1),Ed)});var Ad=["current_state","boundary_analysis","interface_proposal"];var X=bi((e)=>e instanceof Date?e.toISOString():e,l().datetime()),ve=A(["pending","in_progress","blocked","completed"]),zi=A(["queued","running","completed","failed","cancelled","interrupted"]),dt=A(["draft","in_review","finalized"]),Id=m({agentId:l(),role:A(["lead","teammate"]),description:l().optional(),status:A(["idle","running","stopped"])}),Sp=m({agentId:l(),rolePrompt:l(),modelId:l().optional(),maxIterations:b().optional()});function N(e){return bi((t)=>t===null?void 0:t,e.optional())}var xp=m({agentId:l().min(1).describe("Teammate identifier"),rolePrompt:l().min(1).describe("System prompt describing teammate role")}).strict(),Cp=m({agentId:l().min(1).describe("Teammate identifier"),reason:N(l().min(1)).describe("Optional shutdown reason")}),Rp=m({}),Sd={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var Op=m({action:A(["create","list","claim","complete","block"]),title:N(l().min(1)).describe("Task title"),description:N(l().min(1)).describe("Task details"),dependsOn:N(E(l().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:N(l().min(1)).describe("Optional assignee"),status:N(A(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:N(l()).describe("Task ID"),summary:N(l().min(1)).describe("Completion summary"),reason:N(l().min(1)).describe("Blocking reason")}).superRefine((e,t)=>{for(let n of Sd[e.action]){if(e[n]!==void 0)continue;t.addIssue({code:"custom",path:[n],message:`Field "${n}" is required when action=${e.action}`})}}),Pp=m({agentId:l().describe("Teammate agent ID"),task:l().min(1).describe("Task instructions for the teammate"),taskId:N(l()).describe("Optional shared task list ID"),runMode:N(A(["sync","async"])).describe("Execution mode: 'sync' blocks until the teammate finishes and returns the result (default if omitted); 'async' queues the run and returns a runId immediately — use team_await_runs to collect results later."),continueConversation:N(I()).describe("If true, continue the teammate conversation; otherwise start fresh")}),Np=m({status:N(A(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:N(l().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:N(I()).describe("Include completed/failed runs (default true)")}),Mp=m({runId:l().min(1).describe("Run ID"),reason:N(l().min(1)).describe("Optional cancellation reason")}),zp=m({runId:N(l().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),$p=m({toAgentId:l().min(1).describe("Recipient agent ID"),subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:N(l().min(1)).describe("Optional task ID context")}),Lp=m({subject:l().min(1).describe("Message subject"),body:l().min(1).describe("Message body"),taskId:N(l().min(1)).describe("Optional task ID context")}),Dp=m({unreadOnly:N(I()).describe("Only unread messages for read action (default true)")}),Up=m({kind:A(["progress","handoff","blocked","decision","done","error"]),summary:l().min(1).describe("Update summary"),taskId:N(l().min(1)).describe("Optional task ID context"),evidence:N(E(l().min(1))).describe("Optional evidence links/snippets"),nextAction:N(l().min(1)).describe("Planned next step")}),jp=m({}),Bp=m({title:l().describe("Outcome title"),requiredSections:E(l()).default(Ad).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),Fp=m({outcomeId:l().describe("Outcome ID"),section:l().describe("Section name"),sourceRunId:N(l()).describe("Optional source run ID"),content:l().describe("Section fragment content")}),qp=m({fragmentId:l().describe("Fragment ID"),approved:I().describe("Review decision")}),Zp=m({outcomeId:l().describe("Outcome ID")}),Hp=m({}),Vp=m({teamId:l(),teamName:l(),members:E(Id),taskCounts:D(ve,b()),unreadMessages:b(),missionLogEntries:b(),activeRuns:b(),queuedRuns:b(),outcomeCounts:D(dt,b())}),xd=m({id:l(),title:l(),description:l(),status:ve,createdAt:X,updatedAt:X,createdBy:l(),assignee:l().optional(),dependsOn:E(l()),summary:l().optional(),isReady:I(),blockedBy:E(l())}),Wp=Ht("action",[m({action:L("create"),taskId:l(),status:ve,ignoredFields:E(l()).optional(),note:l().optional()}),m({action:L("list"),tasks:E(xd)}),m({action:L("claim"),taskId:l(),status:ve,nextStep:l()}),m({action:L("complete"),taskId:l(),status:ve}),m({action:L("block"),taskId:l(),status:ve})]),Jp=m({agentId:l(),mode:A(["sync","async"]),status:A(["dispatched","running","queued","joined"]),dispatched:I(),message:l(),deduped:I().optional(),runId:l().optional(),text:l().optional(),iterations:b().optional()}),Cd=m({textPreview:l(),iterations:b(),finishReason:l(),durationMs:b(),usage:m({inputTokens:b(),outputTokens:b(),cacheReadTokens:b().optional(),cacheWriteTokens:b().optional(),totalCost:b().optional()})}),Kp=m({id:l(),agentId:l(),taskId:l().optional(),status:zi,messagePreview:l(),priority:b(),retryCount:b(),maxRetries:b(),nextAttemptAt:X.optional(),continueConversation:I().optional(),startedAt:X,endedAt:X.optional(),leaseOwner:l().optional(),heartbeatAt:X.optional(),lastProgressAt:X.optional(),lastProgressMessage:l().optional(),currentActivity:l().optional(),error:l().optional(),resultSummary:Cd.optional()}),Gp=m({id:l(),teamId:l(),fromAgentId:l(),toAgentId:l(),subject:l(),body:l(),taskId:l().optional(),sentAt:X,readAt:X.optional()}),Yp=m({id:l(),teamId:l(),title:l(),status:dt,requiredSections:E(l()),createdBy:l(),createdAt:X,finalizedAt:X.optional()}),Xp=m({outcomeId:l(),status:dt,requiredSections:E(l())}),Qp=m({agentId:l(),status:l()}),ef=m({runId:l(),status:zi}),tf=m({id:l(),toAgentId:l()}),nf=m({delivered:b()}),rf=m({id:l()}),of=m({status:l()}),sf=m({fragmentId:l(),status:l()}),af=m({outcomeId:l(),status:dt}),Rd;((e)=>{e.TaskStart="task_start",e.TaskEnd="task_end",e.AgentEvent="agent_event",e.TeammateSpawned="teammate_spawned",e.TeammateShutdown="teammate_shutdown",e.TeamTaskUpdated="team_task_updated",e.TeamMessage="team_message",e.TeamMissionLog="team_mission_log",e.TeamTaskCompleted="team_task_completed",e.RunStarted="run_started",e.RunQueued="run_queued",e.RunProgress="run_progress",e.RunCompleted="run_completed",e.RunFailed="run_failed",e.RunCancelled="run_cancelled",e.RunInterrupted="run_interrupted",e.OutcomeCreated="outcome_created",e.OutcomeFragmentAttached="outcome_fragment_attached",e.OutcomeFragmentReviewed="outcome_fragment_reviewed",e.OutcomeFinalized="outcome_finalized"})(Rd||={});function Od(e){let{$schema:t,...n}=e;if(typeof n.type==="string")return n;if("properties"in n||"required"in n||"additionalProperties"in n)return{type:"object",...n};for(let r of["oneOf","anyOf","allOf"]){let i=n[r];if(!Array.isArray(i)||i.length===0)continue;if(r==="allOf"){if(i.some((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error('Tool inputSchema must describe an object at the top level, but the schema has a top-level "allOf" with no branch that asserts type: "object". Add type: "object" to at least one allOf branch to make the object constraint explicit.')}if(i.every((o)=>o&&typeof o==="object"&&o.type==="object"))return{type:"object",...n};throw Error(`Tool inputSchema must describe an object at the top level, but the schema has a top-level "${r}" whose branches include non-object types. Pass the strict object schema as inputSchema and reserve union/coercion schemas for use inside execute().`)}return n}function Pd(e){let t=Od(e.inputSchema instanceof O?Gc(e.inputSchema):e.inputSchema);return{name:e.name,resultPolicy:e.resultPolicy,description:e.description,inputSchema:t,lifecycle:e.lifecycle,executionMode:e.executionMode,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}import{classifyProviderError as $i,createGateway as Nd,isRetryableProviderError as Md}from"@cline/llms";import{nanoid as zd}from"nanoid";var $d="Model reached the maximum output token limit before completing the turn",Kt=3,Ld="Your previous response was cut off because it reached the model's output-token limit before finishing. Keep responses concise: take one small step at a time, avoid long explanations, and write large files or command output in smaller chunks across multiple tool calls.",Gt=3,Dd=1000,Ud=15000,jd="Model returned no content because the response was blocked by a content filter. Retrying is unlikely to help — try rephrasing the request.",Bd="The request exceeds the model's context window and there is no conversation history to compact — the system prompt, tools, and current input alone are too large. Reduce attached content or switch to a model with a larger context window.",Fd="The conversation still exceeds the model's context window after compacting it. Start a new session or switch to a model with a larger context window.",qd="The conversation exceeds the model's context window. Compact the conversation, start a new session, or switch to a model with a larger context window.";class Ee extends Error{constructor(e,t){super(t?.trim()?`${e} (provider reported: ${t.trim()})`:e);this.name="ContextWindowOverflowError"}}function de(e,t=8){return`${e}_${zd(t)}`}function Zd(e){return e.model!==void 0}function Hd(e){if(Zd(e))return e;let{providerId:t,modelId:n,apiKey:r,baseUrl:i,headers:o,options:s,...a}=e,c=Nd({providerConfigs:[{providerId:t,apiKey:r,baseUrl:i,headers:o,options:s}],telemetry:a.telemetry}).createAgentModel({providerId:t,modelId:n}),d=a.messageModelInfo??{id:n,provider:t};return{...a,model:c,messageModelInfo:d}}function Vd(e,t){return{...t?.["*"]??{},...t?.[e]??{}}}function Qt(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function Wd(e){if(typeof e==="string")return e.length;return Qt(e)}function Jd(e){let t=e.systemPrompt?.length??0,n=0,r=0,i=0;for(let o of e.messages)for(let s of o.content)switch(s.type){case"text":t+=s.text.length;break;case"reasoning":t+=s.text.length;break;case"file":t+=s.content.length;break;case"tool-call":t+=Qt(s.input);break;case"tool-result":{let a=Wd(s.output);n+=1,r+=a,i=Math.max(i,a),t+=a;break}}return{messageCount:e.messages.length,toolSchemaCount:e.tools.length,systemPromptChars:e.systemPrompt?.length??0,requestJsonChars:Qt({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:t,estimatedTextTokens:ki(t),toolResultCount:n,toolResultChars:r,maxToolResultChars:i}}class en extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class Le extends Error{reason;constructor(e){let t=typeof e==="string"?e:e instanceof Error?e.message:e===void 0?"Run aborted":String(e);super(t);this.name="AgentRuntimeAbortError",this.reason=e}}var Yt={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function he(e,t,n){return{id:de("msg"),role:e,content:t,createdAt:Date.now(),metadata:n}}function ce(e){return{...e}}var Kd={_:"__",'"':"_q_","<":"_lt_",">":"_gt_"};function Li(e){return e.replace(/[_"<>]/g,(t)=>Kd[t])}function Xt(e,t){let n=[`source="${e.source}"`];if("toolCall"in e)n.push(`tool_name="${Li(e.toolCall.toolName)}"`,`tool_call_id="${Li(e.toolCall.toolCallId)}"`);let r=t.trim().replace(/<(\/?)hook_context/gi,"<\\$1hook_context");return`<hook_context ${n.join(" ")}>
|
|
73
73
|
${r}
|
|
74
74
|
</hook_context>`}function W(e){return e.map((t)=>({...t,content:t.content.map((n)=>({...n})),metadata:t.metadata?{...t.metadata}:void 0,modelInfo:t.modelInfo?{...t.modelInfo}:void 0,metrics:t.metrics?{...t.metrics}:void 0}))}function Gd(e,t){let n=Math.max(0,(t.inputTokens??0)-(e.inputTokens??0)),r=Math.max(0,(t.outputTokens??0)-(e.outputTokens??0)),i=Math.max(0,(t.cacheReadTokens??0)-(e.cacheReadTokens??0)),o=Math.max(0,(t.cacheWriteTokens??0)-(e.cacheWriteTokens??0)),s=Math.max(0,(t.reasoningTokenCount??0)-(e.reasoningTokenCount??0)),a=e.totalCost??0,u=t.totalCost??0,c=Math.max(0,u-a);if(n===0&&r===0&&i===0&&o===0&&s===0&&c===0)return;return{inputTokens:n>0?n:0,outputTokens:r>0?r:0,cacheReadTokens:i>0?i:0,cacheWriteTokens:o>0?o:0,...s>0?{reasoningTokenCount:s}:{},...c>0?{cost:c}:{}}}function Yd(e){return e.options?.thinking===!1}function Di(e){if(!e)return"";return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function Xd(e){let t=e?.content.find((n)=>n.type==="tool-result");if(!t||t.isError)return"";if(typeof t.output==="string")return t.output;try{return JSON.stringify(t.output)}catch{return String(t.output)}}function Qd(e){if(typeof e==="string")return[he("user",[{type:"text",text:e}])];if(Array.isArray(e))return W(e);return W([e])}class De{config;listeners=new Set;tools=new Map;hooks={beforeRun:[],afterRun:[],beforeModel:[],afterModel:[],beforeTool:[],afterTool:[],onEvent:[]};pendingHookContexts=[];state={agentId:"",agentRole:void 0,parentAgentId:void 0,runId:void 0,status:"idle",iteration:0,messages:[],pendingToolCalls:[],usage:ce(Yt),lastError:void 0,lastErrorClass:void 0,lastRequestInputTokens:0,lastErrorRetryable:void 0,lastErrorReported:!1,lastFinishReason:void 0};overflowRecoveryAttempted=!1;maxTokensRecoveryCount=0;maxTokensRecoveryAttempted=!1;initialization;abortController;modelSteerController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=Z(e.messageModelInfo?.provider)??("providerId"in e?Z(e.providerId):void 0),this.telemetryModelId=Z(e.messageModelInfo?.id)??("modelId"in e?Z(e.modelId):void 0);let t=Hd(e);this.config={...t,toolExecution:t.toolExecution??"sequential"},this.state.agentId=t.agentId??de("agent"),this.state.agentRole=t.agentRole,this.state.parentAgentId=t.parentAgentId,this.state.messages=W(t.initialMessages??[])}async run(e){return this.execute(e)}async continue(e){return this.execute(e)}notifyPendingUserMessage(){this.modelSteerController?.abort()}abort(e){if(!this.abortController)return;if(this.abortController.signal.aborted)return;let t=e instanceof Le?e:new Le(e);this.state.lastError=t.message,this.captureTaskLifecycle(Ri,{error:t}),this.abortController.abort(t)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}restore(e){this.abort("Agent state restored"),this.state.runId=void 0,this.state.status="idle",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.usage=ce(Yt),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.messages=W(e),this.config={...this.config,initialMessages:W(e)}}snapshot(){return{agentId:this.state.agentId,agentRole:this.state.agentRole,parentAgentId:this.state.parentAgentId,conversationId:this.config.conversationId?.trim()||void 0,runId:this.state.runId,status:this.state.status,iteration:this.state.iteration,messages:W(this.state.messages),pendingToolCalls:[...this.state.pendingToolCalls],usage:ce(this.state.usage),lastError:this.state.lastError,lastErrorClass:this.state.lastErrorClass}}async ensureInitialized(){this.initialization??=this.initialize(),await this.initialization}async initialize(){this.registerHooks(this.config.hooks);for(let e of this.config.tools??[])this.tools.set(e.name,e);for(let e of this.config.plugins??[]){let t=await e.setup?.({agentId:this.state.agentId,agentRole:this.state.agentRole,systemPrompt:this.config.systemPrompt});for(let n of t?.tools??[])this.tools.set(n.name,n);this.registerHooks(t?.hooks)}}registerHooks(e){if(!e)return;if(e.beforeRun)this.hooks.beforeRun.push(e.beforeRun);if(e.afterRun)this.hooks.afterRun.push(e.afterRun);if(e.beforeModel)this.hooks.beforeModel.push(e.beforeModel);if(e.afterModel)this.hooks.afterModel.push(e.afterModel);if(e.beforeTool)this.hooks.beforeTool.push(e.beforeTool);if(e.afterTool)this.hooks.afterTool.push(e.afterTool);if(e.onEvent)this.hooks.onEvent.push(e.onEvent)}getRequiredCompletionToolNames(){if(this.config.completionPolicy?.requireCompletionTool!==!0)return[];return[...this.tools.values()].filter((e)=>e.lifecycle?.completesRun===!0).map((e)=>e.name).sort()}getCompletionToolReminderMessage(){let e=this.getRequiredCompletionToolNames();if(e.length===0)return;return`[SYSTEM] This run is not complete until you call one of these terminal completion tools: ${e.join(", ")}. Continue working if requirements are not met. If the task is complete, call the appropriate terminal completion tool now.`}getCompletionReminderMessages(){return[this.getCompletionToolReminderMessage(),this.config.completionPolicy?.completionGuard?.()].filter((e)=>Boolean(e))}async addUserReminderMessage(e){let t=he("user",[{type:"text",text:e}],{userRunSpan:0});return this.state.messages.push(t),await this.emit({type:"message-added",snapshot:this.snapshot(),message:t}),t}async execute(e){if(await this.ensureInitialized(),this.state.status==="running")throw Error("Agent runtime is already running");this.abortController=new AbortController,this.state.runId=de("run"),this.state.status="running",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1,this.state.lastFinishReason=void 0,this.state.usage=ce(Yt),this.overflowRecoveryAttempted=!1,this.state.lastRequestInputTokens=0,this.pendingHookContexts=[],this.maxTokensRecoveryCount=0,this.maxTokensRecoveryAttempted=!1;try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let r of e?Qd(e):[])this.state.messages.push(r),await this.emit({type:"message-added",snapshot:this.snapshot(),message:r});let t=this.getCompletionToolReminderMessage();if(t)await this.addUserReminderMessage(t);await this.flushPendingHookContexts();let n;while(this.config.maxIterations===void 0||this.state.iteration<this.config.maxIterations){this.throwIfAborted(),this.state.iteration+=1,await this.emit({type:"turn-started",snapshot:this.snapshot(),iteration:this.state.iteration}),this.resetLastError();let{message:r,finishReason:i,interrupted:o}=await this.generateAssistantMessageWithProviderRetry();if(o&&r.content.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(i==="aborted")throw this.normalizeAbortError();if(r.content.length===0){if(i==="error")throw this.state.lastFinishReason=i,Error(this.state.lastError??"Model stream failed");let c=r.metadata?.modelToolActivities;if(!(Array.isArray(c)&&c.length>0)&&i!=="max-tokens")throw this.state.lastFinishReason=i,Error(i==="content-filter"?jd:"Model returned empty response")}let s=r.content.filter((c)=>c.type==="tool-call");if(n=r,await this.recordAssistantMessage(r,i),o){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}if(i==="max-tokens"&&s.length===0){if(await this.recoverFromIncompleteMaxTokensTurn()){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});continue}throw this.state.lastFinishReason=i,Error($d)}if(i==="error"&&s.length===0)throw this.state.lastFinishReason=i,Error(this.state.lastError??"Model stream failed");if(s.length>0)this.maxTokensRecoveryCount=0;if(this.state.pendingToolCalls=s.map((c)=>c.toolCallId),s.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let c=this.getCompletionReminderMessages();if(c.length>0){for(let f of c)await this.addUserReminderMessage(f);continue}let d=this.finishRun("completed",n);return await this.callAfterRunHooks(d),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:d}),d}let a=await this.executeToolCalls(s);this.state.pendingToolCalls=[];for(let c of a)this.state.messages.push(c),await this.emit({type:"message-added",snapshot:this.snapshot(),message:c});await this.flushPendingHookContexts(),await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:s.length});let u=this.findCompletingToolMessage(s,a);if(u){let c=this.finishRun("completed",n,Xd(u)||void 0);return await this.callAfterRunHooks(c),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c}),c}}throw Error(`Agent runtime exceeded maxIterations (${this.config.maxIterations})`)}catch(t){let n=t instanceof Error?t:Error(String(t)),r=n instanceof en,o=this.abortController.signal.aborted||r?"aborted":"failed",s=n instanceof Ee?"context_window_exceeded":n.message===this.state.lastError?this.state.lastErrorClass:void 0,a=n.message===this.state.lastError&&this.state.lastErrorReported;this.state.status=o,this.state.lastError=n.message,this.state.lastErrorClass=s,this.state.lastErrorReported=a;let u=this.findLastAssistantMessage(),c={agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??de("run"),status:o,iterations:this.state.iteration,outputText:Di(u),messages:W(this.state.messages),usage:ce(this.state.usage),error:o==="failed"?n:void 0};if(this.config.logger?.log?.("Agent loop caught error",{severity:o==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:c.runId,status:o,iteration:this.state.iteration,errorName:n.name,errorMessage:n.message,assistantContentPartCount:u?.content.length??0}),await this.callAfterRunHooks(c),o==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:n,errorClass:s});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:c});return c}finally{this.abortController=void 0}}async flushPendingHookContexts(){if(this.pendingHookContexts.length===0)return;let e=this.pendingHookContexts.join(`
|
|
75
75
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cline/agents",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.89",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/cline/cline",
|
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
},
|
|
9
9
|
"main": "dist/index.js",
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@cline/llms": "0.0.
|
|
12
|
-
"@cline/shared": "0.0.
|
|
11
|
+
"@cline/llms": "0.0.89",
|
|
12
|
+
"@cline/shared": "0.0.89",
|
|
13
13
|
"nanoid": "^5.1.7"
|
|
14
14
|
},
|
|
15
15
|
"exports": {
|