@cline/agents 0.0.90 → 0.0.91-nightly.1791426960

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.
@@ -133,7 +133,9 @@ export declare class AgentRuntime {
133
133
  * caller to handle, so this only adds
134
134
  * resilience and never changes behavior for a turn that would otherwise
135
135
  * succeed. Context-window overflow recovery and max-tokens recovery still
136
- * run inside each attempt (the latter at most once per run).
136
+ * run inside each attempt (the latter at most once per run). An unknown
137
+ * finish without tool activity is continued once from the partial history;
138
+ * it is never inferred from whether the response contains visible text.
137
139
  */
138
140
  private generateAssistantMessageWithProviderRetry;
139
141
  /**
@@ -183,7 +185,7 @@ export declare class AgentRuntime {
183
185
  private generateAssistantMessageWithOverflowRecovery;
184
186
  private isRecoverableOverflowTurn;
185
187
  private isRecoverableMaxTokensTurn;
186
- /** Provider-executed tool activity is recorded in metadata, not content. */
188
+ /** Tool activity executed outside AgentRuntime is recorded in metadata. */
187
189
  private hasModelToolActivity;
188
190
  /**
189
191
  * A response cut off at the output-token limit is often a symptom of a
@@ -1 +1 @@
1
- {"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../src/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,uBAAuB,EAE5B,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAIX,YAAY,EAEZ,UAAU,EAKV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAM5C,MAAM,eAAe,CAAC;AAmEvB;;;;GAIG;AACH,eAAO,MAAM,kDAAkD,sPACgL,CAAC;AAEhP;;;GAGG;AACH,eAAO,MAAM,+CAA+C,0JAC4F,CAAC;AAEzJ;;;GAGG;AACH,eAAO,MAAM,2CAA2C,2JACiG,CAAC;AAuB1J,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,YAAY,GAAG,SAAS,YAAY,EAAE,CAAC;AAC5E,MAAM,MAAM,kBAAkB,GAA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follow-up m
71
71
 
72
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
- </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(`
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,t={}){let n=he("user",[{type:"text",text:e}],{...t,userRunSpan:0});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}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");if(!this.hasModelToolActivity(r)&&i!=="max-tokens"&&i!=="unknown")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==="unknown"&&s.length===0)throw this.state.lastFinishReason=i,Error("Model ended without a recognized finish reason");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});if(i==="unknown"&&!a.some((c)=>c.content.some((d)=>d.type==="tool-result"&&!d.isError)))throw this.state.lastFinishReason=i,Error("Model ended without a recognized finish reason or successful tool work");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
 
76
- `);this.pendingHookContexts=[];let t=he("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system"}),n=this.state.messages.at(-1);if(n?.role==="assistant"&&n.content.some((i)=>i.type==="tool-call"))this.state.messages.splice(-1,0,t);else this.state.messages.push(t);await this.emit({type:"message-added",snapshot:this.snapshot(),message:t})}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let t=await e({snapshot:this.snapshot()});if(this.applyStopControl(t),t?.appendContext?.trim())this.pendingHookContexts.push(Xt({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async recoverFromIncompleteMaxTokensTurn(){if(this.maxTokensRecoveryCount>=Kt)return!1;return this.maxTokensRecoveryCount+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`output-token limit reached before a tool call — nudging for a more concise response (attempt ${this.maxTokensRecoveryCount}/${Kt})`,metadata:{kind:"max_tokens_recovery",reason:"max_tokens_recovery",phase:"started",iteration:this.state.iteration,attempt:this.maxTokensRecoveryCount,maxRetries:Kt}}),await this.addUserReminderMessage(Ld),!0}async generateAssistantMessageWithProviderRetry(){return await this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery())}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=Gt||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let r=this.state.lastError;this.resetLastError();let i=Math.min(Dd*2**(t-1),Ud);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${Gt})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:Gt,delayMs:i,providerError:r}}),await this.abortableDelay(i)}}isRetryableProviderErrorTurn(e){if(e.finishReason!=="error")return!1;if(e.message.content.length>0)return!1;let t=e.message.metadata?.modelToolActivities;if(Array.isArray(t)&&t.length>0)return!1;let n=this.state.lastErrorClass;if(n==="auth"||n==="context_window_exceeded")return!1;return this.state.lastErrorRetryable===!0}resetLastError(){this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1}async abortableDelay(e){this.throwIfAborted();let t=this.abortController?.signal;await new Promise((n,r)=>{let i=()=>{clearTimeout(o),r(this.normalizeAbortError())},o=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);if(t)t.addEventListener("abort",i,{once:!0})})}async generateAssistantMessageWithOverflowRecovery(){let e=await this.generateAssistantMessage();if(this.isRecoverableMaxTokensTurn(e))return await this.retryTruncatedTurnWithCompaction(e);if(!this.isRecoverableOverflowTurn(e))return e;this.overflowRecoveryAttempted=!0;let t=this.state.lastError;if(!this.config.prepareTurn)throw new Ee(qd,t);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"context window exceeded — compacting and retrying",metadata:{kind:"context_overflow_recovery",reason:"context_overflow_recovery",phase:"started",iteration:this.state.iteration,providerError:t}});let n=await this.generateAssistantMessage({overflowRecovery:!0});if(n.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Ee(Fd,this.state.lastError);return n}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((t)=>t.type==="tool-call")}isRecoverableMaxTokensTurn(e){if(e.finishReason!=="max-tokens"||this.maxTokensRecoveryAttempted||!this.config.prepareTurn)return!1;if(e.message.content.some((t)=>t.type==="tool-call"))return!1;return!this.hasModelToolActivity(e.message)}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async retryTruncatedTurnWithCompaction(e){this.maxTokensRecoveryAttempted=!0;let t={kind:"max_tokens_compaction",reason:"max_tokens_compaction",iteration:this.state.iteration};this.captureTaskLifecycle($e,{phase:"started"});let n;try{await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"response hit the output token limit — compacting and retrying",metadata:{...t,phase:"started"}});let r=await this.prepareModelRequest({overflowRecovery:!0});n=await this.withProviderErrorRetry(()=>this.issuePreparedRequest(r))}catch(r){if(r instanceof Ee)return this.captureTaskLifecycle($e,{phase:"failed",eventType:"nothing_to_compact"}),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output-token-limit recovery failed: nothing to compact",metadata:{...t,phase:"failed"}}),e;throw this.captureTaskLifecycle($e,{phase:"failed",eventType:"recovery_threw",error:r}),await this.recordAssistantMessage(e.message,e.finishReason),r}if(this.captureTaskLifecycle($e,{phase:"retried",eventType:n.finishReason}),n.finishReason==="aborted")throw await this.recordAssistantMessage(e.message,e.finishReason),this.normalizeAbortError();if(n.finishReason==="error"&&!n.message.content.some((r)=>r.type==="tool-call")){if(await this.recordAssistantMessage(e.message,e.finishReason),n.message.content.length>0||this.hasModelToolActivity(n.message))await this.recordAssistantMessage(n.message,n.finishReason);throw Error(this.state.lastError??"Model stream failed")}if(n.message.content.length===0&&!this.hasModelToolActivity(n.message))return e;return n}async recordAssistantMessage(e,t){this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:e,finishReason:t})}async generateAssistantMessage(e){let t=new AbortController;this.modelSteerController=t;try{return await this.generateAssistantMessageForRequest(t,e)}finally{this.modelSteerController=void 0}}async issuePreparedRequest(e){let t=new AbortController;this.modelSteerController=t;try{return await this.streamPreparedRequest({...e,startedAt:Date.now()},t)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=Ei({distinctId:Z(this.config.distinctId),clientName:Z(this.config.clientName),clientVersion:Z(this.config.clientVersion),clineCoreVersion:Z(this.config.clineCoreVersion),sessionId:Z(this.config.sessionId),agentId:this.state.agentId,conversationId:Z(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n={systemPrompt:this.config.systemPrompt,messages:W(this.state.messages),tools:[...this.tools.values()].map((i)=>({name:i.name,description:i.description,inputSchema:i.inputSchema})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:Wt(this.config.modelOptions,{metadata:t})},r=Date.now();if(this.state.iteration>1){let i=await this.consumePendingUserMessage();if(i)n={...n,messages:[...n.messages,...W([i])]}}n=await this.prepareTurnForModelRequest(n,e),this.throwIfAborted();for(let i of this.hooks.beforeModel){let o=await i({snapshot:this.snapshot(),request:n});if(this.throwIfAborted(),this.applyStopControl(o),o?.messages)n={...n,messages:W(o.messages)};if(o?.tools)n={...n,tools:[...o.tools]};if(o?.options)n={...n,options:Wt(n.options,o.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...Jd(n)}),{request:n,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=ce(this.state.usage),r=()=>Date.now()-e.startedAt,i=e.request;this.throwIfAborted(),this.captureTaskLifecycle(Ii,{durationMs:r(),phase:"provider_request_started"}),i={...i,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])};let o=this.openTaskLifecycleStream(i,r),s=[],a=new Map,u=new Map,c=[],d=[],f=0,h="stop",g,v="",_="";for await(let y of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),y.type){case"text-delta":{v+=y.text;let T=d.at(-1);if(T?.type==="part"&&T.part.type==="text")T.part.text+=y.text;else d.push({type:"part",part:{type:"text",text:y.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:y.text,accumulatedText:v});break}case"media":{d.push({type:"part",part:{type:"media",media:y.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:y.media});break}case"reasoning-delta":{_+=y.text;let T=d.at(-1);if(T?.type==="part"&&T.part.type==="reasoning")T.part.text+=y.text,T.part.redacted=y.redacted??T.part.redacted,T.part.metadata=y.metadata??T.part.metadata;else d.push({type:"part",part:{type:"reasoning",text:y.text,redacted:y.redacted,metadata:y.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:y.text,accumulatedText:_,redacted:y.redacted,metadata:y.metadata});break}case"tool-call-delta":{if(y.execution){let Y={type:"tool-call",toolCallId:y.toolCallId??de("model_tool"),toolName:y.toolName??"tool",input:y.input,metadata:y.metadata,execution:y.execution};u.set(Y.toolCallId,{toolCallId:Y.toolCallId,toolName:Y.toolName,execution:y.execution,input:Y.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Y});break}let T=y.toolCallId??`tool_${y.index??f}`;if(y.index==null&&y.toolCallId==null)f+=1;let x=a.get(T);if(!x)x={toolCallId:y.toolCallId??de("tool"),inputText:""},a.set(T,x),d.push({type:"tool",key:T});if(y.toolCallId)x.toolCallId=y.toolCallId;if(y.toolName)x.toolName=y.toolName;if(y.input!==void 0)x.inputValue=y.input;if(y.metadata!==void 0)x.metadata=Ui(x.metadata,y.metadata);if(y.inputText)x.inputText=rp(x.inputText,y.inputText);break}case"tool-result":{let T=u.get(y.toolCallId),x={...T,toolCallId:y.toolCallId,toolName:y.toolName,execution:y.execution,input:y.input===void 0?T?.input:y.input,output:y.output,isError:y.isError};u.set(y.toolCallId,x);let Y={type:"tool-call",toolCallId:y.toolCallId,toolName:y.toolName,input:x.input,execution:y.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Y,message:he("tool",[{type:"tool-result",toolCallId:y.toolCallId,toolName:y.toolName,output:y.output,isError:y.isError,execution:y.execution}])});break}case"usage":{if(typeof y.usage.inputTokens==="number"&&y.usage.inputTokens>0)this.state.lastRequestInputTokens=y.usage.inputTokens;await this.updateUsage(y.usage);break}case"finish":{if(h=y.reason,g=y.requestId,y.error)this.state.lastError=y.error,this.state.lastErrorClass=y.errorClass??$i(y.error),this.state.lastErrorRetryable=y.errorRetryable??Md(y.error),this.state.lastErrorReported=y.errorReported===!0;break}}}this.throwIfAborted();let S=t.signal.aborted;if(S)h="stop";for(let y of d){if(S&&(y.type==="tool"||y.part.type==="reasoning"))continue;if(y.type==="part"){s.push(y.part);continue}let T=a.get(y.key);if(!T?.toolName){c.push({toolCallId:T?.toolCallId??y.key,input:pt(T?.inputText??""),reason:"missing_name"});continue}let x=tp(T);if(x.reason)c.push({toolCallId:T.toolCallId,toolName:T.toolName,input:x.invalidInput,reason:x.reason});s.push({type:"tool-call",toolCallId:T.toolCallId,toolName:T.toolName,input:x.input,metadata:x.parseError?Ui(T.metadata,{inputParseError:x.parseError,rawInputText:T.inputText}):T.metadata})}let k={};if(c.length>0)k.invalidToolCalls=c;if(u.size>0)k.modelToolActivities=[...u.values()];let U=he("assistant",s,Object.keys(k).length>0?k:void 0),re=Gd(n,this.state.usage);if(re)U.metrics=re,this.captureUnexpectedReasoningTokens(i,re);if(this.config.messageModelInfo)U.modelInfo={...this.config.messageModelInfo};for(let y of this.hooks.afterModel){let T=await y({snapshot:this.snapshot(),assistantMessage:U,finishReason:h,...g?{requestId:g}:{}});this.applyStopControl(T)}return{message:U,finishReason:h,interrupted:S}}async*openTaskLifecycleStream(e,t){let n,r="provider_request_started";try{n=await this.config.model.stream(e),this.throwIfAborted(),r="provider_stream_started",this.captureTaskLifecycle(Si,{durationMs:t(),phase:r})}catch(o){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(o))this.captureTaskLifecycleFailure(o,r,t());throw o}let i=!1;try{for await(let o of n){if(!i)i=!0,r="first_chunk_received",this.captureTaskLifecycle(xi,{durationMs:t(),phase:r,eventType:o.type});yield o}}catch(o){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(o))this.captureTaskLifecycleFailure(o,r,t());throw o}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(Ci,{durationMs:n,error:e,errorClass:$i(e),phase:t})}captureTaskLifecycle(e,t={}){let n=Z(this.config.sessionId);Pi(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:Z(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration>0?this.state.iteration:void 0,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...t})}getTelemetryProviderId(){return Z(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return Z(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof Le||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!Yd(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;Oi(this.config.telemetry,{sessionId:this.config.sessionId,agentId:this.state.agentId,runId:this.state.runId,iteration:this.state.iteration,providerId:this.config.messageModelInfo?.provider,modelId:this.config.messageModelInfo?.id,requestedThinking:!1,reasoningTokenCount:n})}async prepareTurnForModelRequest(e,t){if(!this.config.prepareTurn)return e;let n=t?.overflowRecovery===!0,r=await this.config.prepareTurn({agentId:this.state.agentId,conversationId:this.config.conversationId,parentAgentId:this.state.parentAgentId??null,iteration:this.state.iteration,messages:e.messages,systemPrompt:e.systemPrompt,tools:e.tools,model:{id:this.config.messageModelInfo?.id,provider:this.config.messageModelInfo?.provider},signal:e.signal,overflowRecovery:n||void 0,previousRequestInputTokens:this.state.lastRequestInputTokens>0?this.state.lastRequestInputTokens:void 0,emitStatusNotice:(o,s)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:o,metadata:s})}});if(n){if(!(r?.messages!==void 0&&JSON.stringify(r.messages).length<JSON.stringify(e.messages).length))throw new Ee(Bd,this.state.lastError)}if(!r)return e;let i=e;if(r.messages){let o=W(r.messages);i={...i,messages:W(o)}}if(r.systemPrompt!==void 0)i={...i,systemPrompt:r.systemPrompt};return i}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=he("user",[{type:"text",text:t}],{userRunSpan:0});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e){this.state.usage={inputTokens:this.state.usage.inputTokens+(e.inputTokens??0),outputTokens:this.state.usage.outputTokens+(e.outputTokens??0),cacheReadTokens:this.state.usage.cacheReadTokens+(e.cacheReadTokens??0),cacheWriteTokens:this.state.usage.cacheWriteTokens+(e.cacheWriteTokens??0),reasoningTokenCount:(this.state.usage.reasoningTokenCount??0)+(e.reasoningTokenCount??0),totalCost:(this.state.usage.totalCost??0)+(e.totalCost??0)},await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:ce(this.state.usage)})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let r of e)t.push(await this.prepareToolExecution(r));let n=[];for(let r=0;r<t.length;){let i=t[r];if((i.tool?.executionMode??this.config.toolExecution)==="sequential"){n.push(await this.executePreparedTool(i)),r+=1;continue}let s=r;while(r<t.length&&(t[r].tool?.executionMode??this.config.toolExecution)==="parallel")r+=1;n.push(...await Promise.all(t.slice(s,r).map((a)=>this.executePreparedTool(a))))}return n}findCompletingToolMessage(e,t){for(let n=0;n<e.length;n+=1){let r=e[n];if(this.tools.get(r.toolName)?.lifecycle?.completesRun!==!0)continue;let i=t[n],o=i?.content.find((s)=>s.type==="tool-result"&&s.toolCallId===r.toolCallId);if(o&&!o.isError)return i}return}async prepareToolExecution(e){let t=this.tools.get(e.toolName),n=e.input,r,i=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof i?.inputParseError==="string")r=i.inputParseError;let o=i?.toolSource&&typeof i.toolSource==="object"&&!Array.isArray(i.toolSource)?i.toolSource:void 0;if(o?.executionMode==="provider")r=`Tool execution is disabled for provider ${typeof o.providerId==="string"?o.providerId:"provider"}`;if(t&&!r)n=it(n,t.inputSchema);let s;if(t&&!r)for(let a of this.hooks.beforeTool){let u=await a({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(u?.input!==void 0)n=u.input;if(u?.policy)s={...s,...u.policy};if(u?.appendContext?.trim())this.pendingHookContexts.push(Xt({source:"PreToolUse",toolCall:e},u.appendContext));if(this.applyStopControl(u),u?.skip){r=u.reason??`Tool ${t.name} was blocked by a runtime hook`;break}}if(t&&!r){let a={...Vd(e.toolName,this.config.toolPolicies),...s};if(a.enabled===!1)r=`Tool "${e.toolName}" is disabled by policy`;else if(a.autoApprove===!1){let u=await this.requestToolApproval(e,n,a);if(!u.approved)r=`${u.reason??"Tool was not executed"} -- ${Ti}`}}return{toolCall:{...e,input:n},tool:t,input:n,skipReason:r}}async requestToolApproval(e,t,n){let r=this.config.requestToolApproval;if(!r)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await r({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:e.toolCallId,toolName:e.toolName,input:t,policy:n})}catch(i){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${i instanceof Error?i.message:String(i)}`}}}async executePreparedTool(e){let t=new Date;await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let n;if(e.skipReason)n={output:{error:e.skipReason},isError:!0};else if(!e.tool)n={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{n={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??de("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),emitUpdate:(a)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:a})}})}}catch(s){n={output:{error:s instanceof Error?s.message:String(s)},isError:!0}}let r=new Date,i=Math.max(0,r.getTime()-t.getTime());if(e.tool)for(let s of this.hooks.afterTool){let a=await s({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:n,startedAt:t,endedAt:r,durationMs:i});if(a?.appendContext?.trim())this.pendingHookContexts.push(Xt({source:"PostToolUse",toolCall:e.toolCall},a.appendContext));if(this.applyStopControl(a),a?.result)n=a.result}let o=he("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:n.output,isError:n.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:o}),o}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??de("run"),status:e,iterations:this.state.iteration,outputText:n??Di(t??this.findLastAssistantMessage()),messages:W(this.state.messages),usage:ce(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let e=this.abortController?.signal.reason;if(e instanceof Error)return e;if(typeof e==="string")return Error(e);return Error(this.state.lastError??"Run aborted")}async emit(e){let t=ep(e);switch(e.type){case"run-started":this.config.logger?.info?.("Agent run started",t);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",t);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...t,error:e.error}),!this.state.lastErrorReported)Ni(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:this.config.logger?.debug?.("Agent event",t);break}switch(e.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-updated":break;default:this.config.telemetry?.capture({event:`agent.${e.type}`,properties:t});break}for(let n of this.listeners)n(e);for(let n of this.hooks.onEvent)await n(e)}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new en(e.reason)}}function ep(e){return{agentId:e.snapshot.agentId,agentRole:e.snapshot.agentRole,runId:e.snapshot.runId,status:e.snapshot.status,iteration:e.snapshot.iteration,eventType:e.type}}function Ui(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return t;if(!e||typeof e!=="object"||Array.isArray(e))return t;return{...e,...t}}function tp(e){if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:pt(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let t=np(e.inputText);if(t.ok)return{input:t.value,invalidInput:pt(e.inputText)};return{input:{},invalidInput:pt(e.inputText,t.error),parseError:`Tool call ${e.toolName??e.toolCallId} emitted invalid JSON arguments: ${t.error}`,reason:"invalid_arguments"}}function pt(e,t){if(!e.trim())return{};return t?{rawInputText:e,parseError:t}:{rawInputText:e}}function np(e){let t=e.trim();if(!t)return{ok:!1,error:"Tool call arguments were empty."};try{return{ok:!0,value:JSON.parse(t)}}catch{}if(!(t.startsWith("{")||t.startsWith("[")))return{ok:!1,error:"Tool call arguments must be encoded as a JSON object or array."};return{ok:!1,error:"Tool call arguments could not be parsed as JSON. Ensure the outer tool payload is valid JSON and escape embedded quotes/newlines inside string fields."}}function rp(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}function ip(e){return new De(e)}var op=De;function sp(e){return new De(e)}export{op as Agent,De as AgentRuntime,Le as AgentRuntimeAbortError,sp as createAgent,ip as createAgentRuntime,Pd as createTool};
76
+ `);this.pendingHookContexts=[];let t=he("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system"}),n=this.state.messages.at(-1);if(n?.role==="assistant"&&n.content.some((i)=>i.type==="tool-call"))this.state.messages.splice(-1,0,t);else this.state.messages.push(t);await this.emit({type:"message-added",snapshot:this.snapshot(),message:t})}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let t=await e({snapshot:this.snapshot()});if(this.applyStopControl(t),t?.appendContext?.trim())this.pendingHookContexts.push(Xt({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async recoverFromIncompleteMaxTokensTurn(){if(this.maxTokensRecoveryCount>=Kt)return!1;return this.maxTokensRecoveryCount+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`output-token limit reached before a tool call — nudging for a more concise response (attempt ${this.maxTokensRecoveryCount}/${Kt})`,metadata:{kind:"max_tokens_recovery",reason:"max_tokens_recovery",phase:"started",iteration:this.state.iteration,attempt:this.maxTokensRecoveryCount,maxRetries:Kt}}),await this.addUserReminderMessage(Ld),!0}async generateAssistantMessageWithProviderRetry(){let e=()=>this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery()),t=await e();if(t.finishReason!=="unknown"||t.interrupted)return t;if(t.message.content.some((n)=>n.type==="tool-call")||this.hasModelToolActivity(t.message))return t;return await this.recordAssistantMessage(t.message,t.finishReason),await this.addUserReminderMessage("Previous turn ended unexpectedly. Continue from where you left off.",{displayRole:"system"}),this.resetLastError(),await e()}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=Gt||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let r=this.state.lastError;this.resetLastError();let i=Math.min(Dd*2**(t-1),Ud);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${Gt})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:Gt,delayMs:i,providerError:r}}),await this.abortableDelay(i)}}isRetryableProviderErrorTurn(e){if(e.finishReason!=="error")return!1;if(e.message.content.length>0)return!1;let t=e.message.metadata?.modelToolActivities;if(Array.isArray(t)&&t.length>0)return!1;let n=this.state.lastErrorClass;if(n==="auth"||n==="context_window_exceeded")return!1;return this.state.lastErrorRetryable===!0}resetLastError(){this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1}async abortableDelay(e){this.throwIfAborted();let t=this.abortController?.signal;await new Promise((n,r)=>{let i=()=>{clearTimeout(o),r(this.normalizeAbortError())},o=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);if(t)t.addEventListener("abort",i,{once:!0})})}async generateAssistantMessageWithOverflowRecovery(){let e=await this.generateAssistantMessage();if(this.isRecoverableMaxTokensTurn(e))return await this.retryTruncatedTurnWithCompaction(e);if(!this.isRecoverableOverflowTurn(e))return e;this.overflowRecoveryAttempted=!0;let t=this.state.lastError;if(!this.config.prepareTurn)throw new Ee(qd,t);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"context window exceeded — compacting and retrying",metadata:{kind:"context_overflow_recovery",reason:"context_overflow_recovery",phase:"started",iteration:this.state.iteration,providerError:t}});let n=await this.generateAssistantMessage({overflowRecovery:!0});if(n.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Ee(Fd,this.state.lastError);return n}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((t)=>t.type==="tool-call")}isRecoverableMaxTokensTurn(e){if(e.finishReason!=="max-tokens"||this.maxTokensRecoveryAttempted||!this.config.prepareTurn)return!1;if(e.message.content.some((t)=>t.type==="tool-call"))return!1;return!this.hasModelToolActivity(e.message)}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async retryTruncatedTurnWithCompaction(e){this.maxTokensRecoveryAttempted=!0;let t={kind:"max_tokens_compaction",reason:"max_tokens_compaction",iteration:this.state.iteration};this.captureTaskLifecycle($e,{phase:"started"});let n;try{await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"response hit the output token limit — compacting and retrying",metadata:{...t,phase:"started"}});let r=await this.prepareModelRequest({overflowRecovery:!0});n=await this.withProviderErrorRetry(()=>this.issuePreparedRequest(r))}catch(r){if(r instanceof Ee)return this.captureTaskLifecycle($e,{phase:"failed",eventType:"nothing_to_compact"}),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"output-token-limit recovery failed: nothing to compact",metadata:{...t,phase:"failed"}}),e;throw this.captureTaskLifecycle($e,{phase:"failed",eventType:"recovery_threw",error:r}),await this.recordAssistantMessage(e.message,e.finishReason),r}if(this.captureTaskLifecycle($e,{phase:"retried",eventType:n.finishReason}),n.finishReason==="aborted")throw await this.recordAssistantMessage(e.message,e.finishReason),this.normalizeAbortError();if(n.finishReason==="error"&&!n.message.content.some((r)=>r.type==="tool-call")){if(await this.recordAssistantMessage(e.message,e.finishReason),n.message.content.length>0||this.hasModelToolActivity(n.message))await this.recordAssistantMessage(n.message,n.finishReason);throw Error(this.state.lastError??"Model stream failed")}if(n.message.content.length===0&&!this.hasModelToolActivity(n.message))return e;return n}async recordAssistantMessage(e,t){this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:e,finishReason:t})}async generateAssistantMessage(e){let t=new AbortController;this.modelSteerController=t;try{return await this.generateAssistantMessageForRequest(t,e)}finally{this.modelSteerController=void 0}}async issuePreparedRequest(e){let t=new AbortController;this.modelSteerController=t;try{return await this.streamPreparedRequest({...e,startedAt:Date.now()},t)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=Ei({distinctId:Z(this.config.distinctId),clientName:Z(this.config.clientName),clientVersion:Z(this.config.clientVersion),clineCoreVersion:Z(this.config.clineCoreVersion),sessionId:Z(this.config.sessionId),agentId:this.state.agentId,conversationId:Z(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n={systemPrompt:this.config.systemPrompt,messages:W(this.state.messages),tools:[...this.tools.values()].map((o)=>({name:o.name,description:o.description,inputSchema:o.inputSchema})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:Wt(this.config.modelOptions,{metadata:t})},r=Date.now(),i=await this.consumePendingUserMessage();if(i)n={...n,messages:[...n.messages,...W([i])]};n=await this.prepareTurnForModelRequest(n,e),this.throwIfAborted();for(let o of this.hooks.beforeModel){let s=await o({snapshot:this.snapshot(),request:n});if(this.throwIfAborted(),this.applyStopControl(s),s?.messages)n={...n,messages:W(s.messages)};if(s?.tools)n={...n,tools:[...s.tools]};if(s?.options)n={...n,options:Wt(n.options,s.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...Jd(n)}),{request:n,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=ce(this.state.usage),r=()=>Date.now()-e.startedAt,i=e.request;this.throwIfAborted(),this.captureTaskLifecycle(Ii,{durationMs:r(),phase:"provider_request_started"}),i={...i,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])};let o=this.openTaskLifecycleStream(i,r),s=[],a=new Map,u=new Map,c=[],d=[],f=0,h="unknown",g,v="",_="";for await(let y of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),y.type){case"text-delta":{v+=y.text;let T=d.at(-1);if(T?.type==="part"&&T.part.type==="text")T.part.text+=y.text;else d.push({type:"part",part:{type:"text",text:y.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:y.text,accumulatedText:v});break}case"media":{d.push({type:"part",part:{type:"media",media:y.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:y.media});break}case"reasoning-delta":{_+=y.text;let T=d.at(-1);if(T?.type==="part"&&T.part.type==="reasoning")T.part.text+=y.text,T.part.redacted=y.redacted??T.part.redacted,T.part.metadata=y.metadata??T.part.metadata;else d.push({type:"part",part:{type:"reasoning",text:y.text,redacted:y.redacted,metadata:y.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:y.text,accumulatedText:_,redacted:y.redacted,metadata:y.metadata});break}case"tool-call-delta":{if(y.execution){let Y={type:"tool-call",toolCallId:y.toolCallId??de("model_tool"),toolName:y.toolName??"tool",input:y.input,metadata:y.metadata,execution:y.execution};u.set(Y.toolCallId,{toolCallId:Y.toolCallId,toolName:Y.toolName,execution:y.execution,input:Y.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Y});break}let T=y.toolCallId??`tool_${y.index??f}`;if(y.index==null&&y.toolCallId==null)f+=1;let x=a.get(T);if(!x)x={toolCallId:y.toolCallId??de("tool"),inputText:""},a.set(T,x),d.push({type:"tool",key:T});if(y.toolCallId)x.toolCallId=y.toolCallId;if(y.toolName)x.toolName=y.toolName;if(y.input!==void 0)x.inputValue=y.input;if(y.metadata!==void 0)x.metadata=Ui(x.metadata,y.metadata);if(y.inputText)x.inputText=rp(x.inputText,y.inputText);break}case"tool-result":{let T=u.get(y.toolCallId),x={...T,toolCallId:y.toolCallId,toolName:y.toolName,execution:y.execution,input:y.input===void 0?T?.input:y.input,output:y.output,isError:y.isError};u.set(y.toolCallId,x);let Y={type:"tool-call",toolCallId:y.toolCallId,toolName:y.toolName,input:x.input,execution:y.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:Y,message:he("tool",[{type:"tool-result",toolCallId:y.toolCallId,toolName:y.toolName,output:y.output,isError:y.isError,execution:y.execution}])});break}case"usage":{if(typeof y.usage.inputTokens==="number"&&y.usage.inputTokens>0)this.state.lastRequestInputTokens=y.usage.inputTokens;await this.updateUsage(y.usage);break}case"finish":{if(h=y.reason,g=y.requestId,y.error)this.state.lastError=y.error,this.state.lastErrorClass=y.errorClass??$i(y.error),this.state.lastErrorRetryable=y.errorRetryable??Md(y.error),this.state.lastErrorReported=y.errorReported===!0;break}}}this.throwIfAborted();let S=t.signal.aborted;if(S)h="stop";for(let y of d){if(S&&(y.type==="tool"||y.part.type==="reasoning"))continue;if(y.type==="part"){s.push(y.part);continue}let T=a.get(y.key);if(!T?.toolName){c.push({toolCallId:T?.toolCallId??y.key,input:pt(T?.inputText??""),reason:"missing_name"});continue}let x=tp(T);if(x.reason)c.push({toolCallId:T.toolCallId,toolName:T.toolName,input:x.invalidInput,reason:x.reason});s.push({type:"tool-call",toolCallId:T.toolCallId,toolName:T.toolName,input:x.input,metadata:x.parseError?Ui(T.metadata,{inputParseError:x.parseError,rawInputText:T.inputText}):T.metadata})}let k={};if(c.length>0)k.invalidToolCalls=c;if(u.size>0)k.modelToolActivities=[...u.values()];let U=he("assistant",s,Object.keys(k).length>0?k:void 0),re=Gd(n,this.state.usage);if(re)U.metrics=re,this.captureUnexpectedReasoningTokens(i,re);if(this.config.messageModelInfo)U.modelInfo={...this.config.messageModelInfo};for(let y of this.hooks.afterModel){let T=await y({snapshot:this.snapshot(),assistantMessage:U,finishReason:h,...g?{requestId:g}:{}});this.applyStopControl(T)}return{message:U,finishReason:h,interrupted:S}}async*openTaskLifecycleStream(e,t){let n,r="provider_request_started";try{n=await this.config.model.stream(e),this.throwIfAborted(),r="provider_stream_started",this.captureTaskLifecycle(Si,{durationMs:t(),phase:r})}catch(o){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(o))this.captureTaskLifecycleFailure(o,r,t());throw o}let i=!1;try{for await(let o of n){if(!i)i=!0,r="first_chunk_received",this.captureTaskLifecycle(xi,{durationMs:t(),phase:r,eventType:o.type});yield o}}catch(o){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(o))this.captureTaskLifecycleFailure(o,r,t());throw o}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(Ci,{durationMs:n,error:e,errorClass:$i(e),phase:t})}captureTaskLifecycle(e,t={}){let n=Z(this.config.sessionId);Pi(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:Z(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration>0?this.state.iteration:void 0,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...t})}getTelemetryProviderId(){return Z(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return Z(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof Le||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!Yd(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;Oi(this.config.telemetry,{sessionId:this.config.sessionId,agentId:this.state.agentId,runId:this.state.runId,iteration:this.state.iteration,providerId:this.config.messageModelInfo?.provider,modelId:this.config.messageModelInfo?.id,requestedThinking:!1,reasoningTokenCount:n})}async prepareTurnForModelRequest(e,t){if(!this.config.prepareTurn)return e;let n=t?.overflowRecovery===!0,r=await this.config.prepareTurn({agentId:this.state.agentId,conversationId:this.config.conversationId,parentAgentId:this.state.parentAgentId??null,iteration:this.state.iteration,messages:e.messages,systemPrompt:e.systemPrompt,tools:e.tools,model:{id:this.config.messageModelInfo?.id,provider:this.config.messageModelInfo?.provider},signal:e.signal,overflowRecovery:n||void 0,previousRequestInputTokens:this.state.lastRequestInputTokens>0?this.state.lastRequestInputTokens:void 0,emitStatusNotice:(o,s)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:o,metadata:s})}});if(n){if(!(r?.messages!==void 0&&JSON.stringify(r.messages).length<JSON.stringify(e.messages).length))throw new Ee(Bd,this.state.lastError)}if(!r)return e;let i=e;if(r.messages){let o=W(r.messages);i={...i,messages:W(o)}}if(r.systemPrompt!==void 0)i={...i,systemPrompt:r.systemPrompt};return i}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=he("user",[{type:"text",text:t}],{userRunSpan:0});return this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e){this.state.usage={inputTokens:this.state.usage.inputTokens+(e.inputTokens??0),outputTokens:this.state.usage.outputTokens+(e.outputTokens??0),cacheReadTokens:this.state.usage.cacheReadTokens+(e.cacheReadTokens??0),cacheWriteTokens:this.state.usage.cacheWriteTokens+(e.cacheWriteTokens??0),reasoningTokenCount:(this.state.usage.reasoningTokenCount??0)+(e.reasoningTokenCount??0),totalCost:(this.state.usage.totalCost??0)+(e.totalCost??0)},await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:ce(this.state.usage)})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let r of e)t.push(await this.prepareToolExecution(r));let n=[];for(let r=0;r<t.length;){let i=t[r];if((i.tool?.executionMode??this.config.toolExecution)==="sequential"){n.push(await this.executePreparedTool(i)),r+=1;continue}let s=r;while(r<t.length&&(t[r].tool?.executionMode??this.config.toolExecution)==="parallel")r+=1;n.push(...await Promise.all(t.slice(s,r).map((a)=>this.executePreparedTool(a))))}return n}findCompletingToolMessage(e,t){for(let n=0;n<e.length;n+=1){let r=e[n];if(this.tools.get(r.toolName)?.lifecycle?.completesRun!==!0)continue;let i=t[n],o=i?.content.find((s)=>s.type==="tool-result"&&s.toolCallId===r.toolCallId);if(o&&!o.isError)return i}return}async prepareToolExecution(e){let t=this.tools.get(e.toolName),n=e.input,r,i=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof i?.inputParseError==="string")r=i.inputParseError;let o=i?.toolSource&&typeof i.toolSource==="object"&&!Array.isArray(i.toolSource)?i.toolSource:void 0;if(o?.executionMode==="provider")r=`Tool execution is disabled for provider ${typeof o.providerId==="string"?o.providerId:"provider"}`;if(t&&!r)n=it(n,t.inputSchema);let s;if(t&&!r)for(let a of this.hooks.beforeTool){let u=await a({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(u?.input!==void 0)n=u.input;if(u?.policy)s={...s,...u.policy};if(u?.appendContext?.trim())this.pendingHookContexts.push(Xt({source:"PreToolUse",toolCall:e},u.appendContext));if(this.applyStopControl(u),u?.skip){r=u.reason??`Tool ${t.name} was blocked by a runtime hook`;break}}if(t&&!r){let a={...Vd(e.toolName,this.config.toolPolicies),...s};if(a.enabled===!1)r=`Tool "${e.toolName}" is disabled by policy`;else if(a.autoApprove===!1){let u=await this.requestToolApproval(e,n,a);if(!u.approved)r=`${u.reason??"Tool was not executed"} -- ${Ti}`}}return{toolCall:{...e,input:n},tool:t,input:n,skipReason:r}}async requestToolApproval(e,t,n){let r=this.config.requestToolApproval;if(!r)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await r({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:e.toolCallId,toolName:e.toolName,input:t,policy:n})}catch(i){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${i instanceof Error?i.message:String(i)}`}}}async executePreparedTool(e){let t=new Date;await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let n;if(e.skipReason)n={output:{error:e.skipReason},isError:!0};else if(!e.tool)n={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{n={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??de("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),emitUpdate:(a)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:a})}})}}catch(s){n={output:{error:s instanceof Error?s.message:String(s)},isError:!0}}let r=new Date,i=Math.max(0,r.getTime()-t.getTime());if(e.tool)for(let s of this.hooks.afterTool){let a=await s({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:n,startedAt:t,endedAt:r,durationMs:i});if(a?.appendContext?.trim())this.pendingHookContexts.push(Xt({source:"PostToolUse",toolCall:e.toolCall},a.appendContext));if(this.applyStopControl(a),a?.result)n=a.result}let o=he("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:n.output,isError:n.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:o}),o}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??de("run"),status:e,iterations:this.state.iteration,outputText:n??Di(t??this.findLastAssistantMessage()),messages:W(this.state.messages),usage:ce(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let e=this.abortController?.signal.reason;if(e instanceof Error)return e;if(typeof e==="string")return Error(e);return Error(this.state.lastError??"Run aborted")}async emit(e){let t=ep(e);switch(e.type){case"run-started":this.config.logger?.info?.("Agent run started",t);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",t);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...t,error:e.error}),!this.state.lastErrorReported)Ni(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:this.config.logger?.debug?.("Agent event",t);break}switch(e.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-updated":break;default:this.config.telemetry?.capture({event:`agent.${e.type}`,properties:t});break}for(let n of this.listeners)n(e);for(let n of this.hooks.onEvent)await n(e)}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new en(e.reason)}}function ep(e){return{agentId:e.snapshot.agentId,agentRole:e.snapshot.agentRole,runId:e.snapshot.runId,status:e.snapshot.status,iteration:e.snapshot.iteration,eventType:e.type}}function Ui(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return t;if(!e||typeof e!=="object"||Array.isArray(e))return t;return{...e,...t}}function tp(e){if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:pt(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let t=np(e.inputText);if(t.ok)return{input:t.value,invalidInput:pt(e.inputText)};return{input:{},invalidInput:pt(e.inputText,t.error),parseError:`Tool call ${e.toolName??e.toolCallId} emitted invalid JSON arguments: ${t.error}`,reason:"invalid_arguments"}}function pt(e,t){if(!e.trim())return{};return t?{rawInputText:e,parseError:t}:{rawInputText:e}}function np(e){let t=e.trim();if(!t)return{ok:!1,error:"Tool call arguments were empty."};try{return{ok:!0,value:JSON.parse(t)}}catch{}if(!(t.startsWith("{")||t.startsWith("[")))return{ok:!1,error:"Tool call arguments must be encoded as a JSON object or array."};return{ok:!1,error:"Tool call arguments could not be parsed as JSON. Ensure the outer tool payload is valid JSON and escape embedded quotes/newlines inside string fields."}}function rp(e,t){if(!e)return t;let n=t.trimStart();if(n.startsWith("{")||n.startsWith("["))return t;return e+t}function ip(e){return new De(e)}var op=De;function sp(e){return new De(e)}export{op as Agent,De as AgentRuntime,Le as AgentRuntimeAbortError,sp as createAgent,ip as createAgentRuntime,Pd as createTool};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cline/agents",
3
- "version": "0.0.90",
3
+ "version": "0.0.91-nightly.1791426960",
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.90",
12
- "@cline/shared": "0.0.90",
11
+ "@cline/llms": "0.0.91-nightly.1791426960",
12
+ "@cline/shared": "0.0.91-nightly.1791426960",
13
13
  "nanoid": "^5.1.7"
14
14
  },
15
15
  "exports": {