@cline/agents 0.0.69-nightly.1785899830 → 0.0.70
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/agent-runtime.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../src/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,uBAAuB,EAC5B,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAIX,YAAY,EAEZ,UAAU,EAIV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAM5C,MAAM,eAAe,CAAC;AAqBvB;;;;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,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;AAEpE;;;;GAIG;AACH,MAAM,WAAW,2BAA4B,SAAQ,sBAAsB;IAC1E,KAAK,EAAE,UAAU,CAAC;CAClB;AAED;;;;GAIG;AACH,MAAM,WAAW,8BAChB,SAAQ,IAAI,CAAC,sBAAsB,EAAE,OAAO,CAAC;IAC7C,gDAAgD;IAChD,UAAU,EAAE,MAAM,CAAC;IACnB,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,+BAA+B;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,wCAAwC;IACxC,OAAO,CAAC,EAAE,uBAAuB,CAAC,SAAS,CAAC,CAAC;CAC7C;AAED;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAC3B,2BAA2B,GAC3B,8BAA8B,CAAC;AAuJlC,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;gBAEd,MAAM,CAAC,EAAE,OAAO;CAa5B;AAmID,qBAAa,YAAY;IACxB,OAAO,CAAC,MAAM,CACU;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAiC;IAE3D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA0C;IAChE,OAAO,CAAC,KAAK,CAQX;IACF,OAAO,CAAC,QAAQ,CAAC,KAAK,CAmBpB;IACF,uDAAuD;IACvD,OAAO,CAAC,yBAAyB,CAAS;IAC1C,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,OAAO,CAAC,eAAe,CAAC,CAAkB;IAC1C,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAS;IAC9C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAS;gBAE/B,MAAM,EAAE,kBAAkB;IAkBhC,GAAG,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAIlD,QAAQ,CAAC,KAAK,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAI9D,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI;IAkB7B,SAAS,CAAC,QAAQ,EAAE,kBAAkB,GAAG,MAAM,IAAI;IAOnD;;;;;;;OAOG;IACH,OAAO,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,IAAI;IAoBhD,QAAQ,IAAI,yBAAyB;YAiBvB,iBAAiB;YAKjB,UAAU;IAkBxB,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,8BAA8B;IAUtC,OAAO,CAAC,gCAAgC;IAUxC,OAAO,CAAC,6BAA6B;YAOvB,sBAAsB;YAatB,OAAO;YA6NP,kBAAkB;YASlB,iBAAiB;IAM/B;;;;;OAKG;YACW,4CAA4C;IA2C1D,OAAO,CAAC,yBAAyB;YAiBnB,wBAAwB;
|
|
1
|
+
{"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../src/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,uBAAuB,EAC5B,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAIX,YAAY,EAEZ,UAAU,EAIV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAM5C,MAAM,eAAe,CAAC;AAqBvB;;;;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,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;AAEpE;;;;GAIG;AACH,MAAM,WAAW,2BAA4B,SAAQ,sBAAsB;IAC1E,KAAK,EAAE,UAAU,CAAC;CAClB;AAED;;;;GAIG;AACH,MAAM,WAAW,8BAChB,SAAQ,IAAI,CAAC,sBAAsB,EAAE,OAAO,CAAC;IAC7C,gDAAgD;IAChD,UAAU,EAAE,MAAM,CAAC;IACnB,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,+BAA+B;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,wCAAwC;IACxC,OAAO,CAAC,EAAE,uBAAuB,CAAC,SAAS,CAAC,CAAC;CAC7C;AAED;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAC3B,2BAA2B,GAC3B,8BAA8B,CAAC;AAuJlC,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;gBAEd,MAAM,CAAC,EAAE,OAAO;CAa5B;AAmID,qBAAa,YAAY;IACxB,OAAO,CAAC,MAAM,CACU;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAiC;IAE3D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA0C;IAChE,OAAO,CAAC,KAAK,CAQX;IACF,OAAO,CAAC,QAAQ,CAAC,KAAK,CAmBpB;IACF,uDAAuD;IACvD,OAAO,CAAC,yBAAyB,CAAS;IAC1C,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,OAAO,CAAC,eAAe,CAAC,CAAkB;IAC1C,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAS;IAC9C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAS;gBAE/B,MAAM,EAAE,kBAAkB;IAkBhC,GAAG,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAIlD,QAAQ,CAAC,KAAK,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAI9D,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI;IAkB7B,SAAS,CAAC,QAAQ,EAAE,kBAAkB,GAAG,MAAM,IAAI;IAOnD;;;;;;;OAOG;IACH,OAAO,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,IAAI;IAoBhD,QAAQ,IAAI,yBAAyB;YAiBvB,iBAAiB;YAKjB,UAAU;IAkBxB,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,8BAA8B;IAUtC,OAAO,CAAC,gCAAgC;IAUxC,OAAO,CAAC,6BAA6B;YAOvB,sBAAsB;YAatB,OAAO;YA6NP,kBAAkB;YASlB,iBAAiB;IAM/B;;;;;OAKG;YACW,4CAA4C;IA2C1D,OAAO,CAAC,yBAAyB;YAiBnB,wBAAwB;YA4SvB,uBAAuB;IAmDtC,OAAO,CAAC,2BAA2B;IAanC,OAAO,CAAC,oBAAoB;IAmB5B,OAAO,CAAC,sBAAsB;IAO9B,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,YAAY;IAOpB,OAAO,CAAC,gCAAgC;YA2B1B,0BAA0B;YAuE1B,yBAAyB;YAqBzB,WAAW;YAoBX,gBAAgB;IAqB9B,OAAO,CAAC,yBAAyB;YAsBnB,oBAAoB;YA0FpB,mBAAmB;YAwCnB,mBAAmB;IAkGjC,OAAO,CAAC,SAAS;IAoBjB,OAAO,CAAC,wBAAwB;IAMhC,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,mBAAmB;YAWb,IAAI;IAiElB,OAAO,CAAC,gBAAgB;CAWxB;AAkHD,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAE3E;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,KAAK,qBAAe,CAAC;AAClC,MAAM,MAAM,KAAK,GAAG,YAAY,CAAC;AAEjC,wBAAgB,WAAW,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAEpE"}
|
package/dist/index.js
CHANGED
|
@@ -73,8 +73,8 @@ You are in Plan mode. Your role is to explore, analyze, and plan -- not to execu
|
|
|
73
73
|
- Do NOT edit files, write code, run destructive commands, or make any changes
|
|
74
74
|
- Do NOT implement anything -- focus on understanding and alignment first
|
|
75
75
|
|
|
76
|
-
The run_commands tool remains available in plan mode strictly for read-only inspection -- listing files, searching (grep), reading configs, inspecting git history and diffs, checking tool versions, and the like. Never use it to change anything: no creating, modifying, or deleting files, no writing scripts that make changes, and no state-changing commands (installs, migrations, database or schema changes, container commands that mutate state, etc.). If the task requires a mutation, put it in the plan; it happens only after the user switches to act mode.`,Kv=`${tc}
|
|
76
|
+
The run_commands tool remains available in plan mode strictly for read-only inspection -- listing files, searching (grep), reading configs, inspecting git history and diffs, checking tool versions, and the like. Never use it to change anything: no creating, modifying, or deleting files, no writing scripts that make changes, and no state-changing commands (installs, migrations, database or schema changes, container commands that mutate state, etc.). File-editing commands (rm/mv/cp, in-place edits like sed -i, output redirection to files outside /tmp, git commands that change the working tree, package installs) are hard-blocked in plan mode: they are not executed and return a tool error instead, so do not attempt them. If the task requires a mutation, put it in the plan; it happens only after the user switches to act mode.`,Kv=`${tc}
|
|
77
77
|
|
|
78
78
|
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.`,qv=`${tc}
|
|
79
79
|
|
|
80
|
-
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 Hv=Er.enum(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),Xv=Er.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),Yv=Er.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var nc="task.provider_request_started",ic="task.provider_stream_started",rc="task.first_chunk_received",ac="task.provider_stream_failed",oc="task.cancelled";var $e=new Map;function Hg(e,n){let r=typeof n.error_message==="string"?n.error_message:"";return[e,n.component,n.operation,n.error_type,n.error_code??"",n.error_status??"",r.replace(/\d+/g,"#").replace(/\s+/g," ").trim().toLowerCase().slice(0,256)].join("\x00")}function Xg(e){let n=Date.now(),r=$e.get(e);if(r&&n-r.startMs<3600000){if(r.emitted<5)return r.emitted+=1,{emit:!0,suppressed:0};return r.suppressed+=1,{emit:!1,suppressed:r.suppressed}}let a=r?.suppressed??0;if($e.delete(e),$e.size>=512){let t=$e.keys().next();if(!t.done)$e.delete(t.value)}return $e.set(e,{startMs:n,emitted:1,suppressed:0}),{emit:!0,suppressed:a}}function sc(e,n){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:dc({sessionId:n.sessionId,agentId:n.agentId,runId:n.runId,iteration:n.iteration,providerId:n.providerId,modelId:n.modelId,requestedThinking:n.requestedThinking,reasoningTokenCount:n.reasoningTokenCount})})}function uc(e,n){if(!e)return;e.capture({event:n.event,properties:dc({sessionId:n.sessionId,ulid:n.ulid??n.sessionId,agentId:n.agentId,conversationId:n.conversationId,runId:n.runId,iteration:n.iteration,provider:n.providerId,providerId:n.providerId,model:n.modelId,modelId:n.modelId,phase:n.phase,durationMs:n.durationMs,eventType:n.eventType,...n.error===void 0?{}:cc(n.error,n.messageLimit),error_class:n.errorClass})})}function lc(e,n){if(!e)return!1;let r=n.event??"sdk.error",a=Yg(n),t=0;try{let i=Xg(Hg(r,a));if(!i.emit)return!0;t=i.suppressed}catch{}return e.capture({event:r,properties:t>0?{...a,suppressed_count:t}:a}),!0}function Yg(e){return{...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...cc(e.error,e.messageLimit,e.errorMessage)}}function dc(e){let n={};for(let[r,a]of Object.entries(e))if(a!==void 0)n[r]=a;return n}function cc(e,n=500,r){let a=tv(e)?e:void 0,t=e instanceof Error?e:void 0,i=Ae(r)??Ae(t?.message)??Ae(a?.message)??nv(e)??"Unknown error",o=iv(a?.code),u=bn(a?.status)??bn(a?.statusCode)??bn(a?.responseStatus);return{error_type:t?.name?.trim()||Ae(a?.name)||t?.constructor?.name||"Error",error_message:ev(Qg(i),n),...o!==void 0?{error_code:o}:{},...u!==void 0?{error_status:u}:{}}}function Qg(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 ev(e,n){let r=Math.max(1,Math.floor(n));return e.length>r?e.substring(0,r):e}function tv(e){return typeof e==="object"&&e!==null}function Ae(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function nv(e){if(e instanceof Error)return;let n=typeof e==="string"?e:String(e);return n==="[object Object]"?void 0:Ae(n)}function iv(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function bn(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var rv=["rules","skills","workflows","plugins"];var Qv=new Set(rv);var av=s.object({rootPath:s.string().min(1),hint:s.string().min(1).optional(),associatedRemoteUrls:s.array(s.string().min(1)).optional(),latestGitCommitHash:s.string().min(1).optional(),latestGitBranchName:s.string().min(1).optional()}),eh=s.object({currentWorkspacePath:s.string().min(1).optional(),workspaces:s.record(s.string().min(1),av)});var ov=["current_state","boundary_analysis","interface_proposal"];var K=s.preprocess((e)=>e instanceof Date?e.toISOString():e,s.string().datetime()),be=s.enum(["pending","in_progress","blocked","completed"]),mc=s.enum(["queued","running","completed","failed","cancelled","interrupted"]),hn=s.enum(["draft","in_review","finalized"]),sv=s.object({agentId:s.string(),role:s.enum(["lead","teammate"]),description:s.string().optional(),status:s.enum(["idle","running","stopped"])}),th=s.object({agentId:s.string(),rolePrompt:s.string(),modelId:s.string().optional(),maxIterations:s.number().optional()});function A(e){return s.preprocess((n)=>n===null?void 0:n,e.optional())}var nh=s.object({agentId:s.string().min(1).describe("Teammate identifier"),rolePrompt:s.string().min(1).describe("System prompt describing teammate role")}).strict(),ih=s.object({agentId:s.string().min(1).describe("Teammate identifier"),reason:A(s.string().min(1)).describe("Optional shutdown reason")}),rh=s.object({}),uv={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var ah=s.object({action:s.enum(["create","list","claim","complete","block"]),title:A(s.string().min(1)).describe("Task title"),description:A(s.string().min(1)).describe("Task details"),dependsOn:A(s.array(s.string().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:A(s.string().min(1)).describe("Optional assignee"),status:A(s.enum(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:A(s.string()).describe("Task ID"),summary:A(s.string().min(1)).describe("Completion summary"),reason:A(s.string().min(1)).describe("Blocking reason")}).superRefine((e,n)=>{for(let r of uv[e.action]){if(e[r]!==void 0)continue;n.addIssue({code:"custom",path:[r],message:`Field "${r}" is required when action=${e.action}`})}}),oh=s.object({agentId:s.string().describe("Teammate agent ID"),task:s.string().min(1).describe("Task instructions for the teammate"),taskId:A(s.string()).describe("Optional shared task list ID"),runMode:A(s.enum(["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:A(s.boolean()).describe("If true, continue the teammate conversation; otherwise start fresh")}),sh=s.object({status:A(s.enum(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:A(s.string().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:A(s.boolean()).describe("Include completed/failed runs (default true)")}),uh=s.object({runId:s.string().min(1).describe("Run ID"),reason:A(s.string().min(1)).describe("Optional cancellation reason")}),lh=s.object({runId:A(s.string().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),dh=s.object({toAgentId:s.string().min(1).describe("Recipient agent ID"),subject:s.string().min(1).describe("Message subject"),body:s.string().min(1).describe("Message body"),taskId:A(s.string().min(1)).describe("Optional task ID context")}),ch=s.object({subject:s.string().min(1).describe("Message subject"),body:s.string().min(1).describe("Message body"),taskId:A(s.string().min(1)).describe("Optional task ID context")}),mh=s.object({unreadOnly:A(s.boolean()).describe("Only unread messages for read action (default true)")}),fh=s.object({kind:s.enum(["progress","handoff","blocked","decision","done","error"]),summary:s.string().min(1).describe("Update summary"),taskId:A(s.string().min(1)).describe("Optional task ID context"),evidence:A(s.array(s.string().min(1))).describe("Optional evidence links/snippets"),nextAction:A(s.string().min(1)).describe("Planned next step")}),ph=s.object({}),gh=s.object({title:s.string().describe("Outcome title"),requiredSections:s.array(s.string()).default(ov).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),vh=s.object({outcomeId:s.string().describe("Outcome ID"),section:s.string().describe("Section name"),sourceRunId:A(s.string()).describe("Optional source run ID"),content:s.string().describe("Section fragment content")}),hh=s.object({fragmentId:s.string().describe("Fragment ID"),approved:s.boolean().describe("Review decision")}),$h=s.object({outcomeId:s.string().describe("Outcome ID")}),yh=s.object({}),bh=s.object({teamId:s.string(),teamName:s.string(),members:s.array(sv),taskCounts:s.record(be,s.number()),unreadMessages:s.number(),missionLogEntries:s.number(),activeRuns:s.number(),queuedRuns:s.number(),outcomeCounts:s.record(hn,s.number())}),lv=s.object({id:s.string(),title:s.string(),description:s.string(),status:be,createdAt:K,updatedAt:K,createdBy:s.string(),assignee:s.string().optional(),dependsOn:s.array(s.string()),summary:s.string().optional(),isReady:s.boolean(),blockedBy:s.array(s.string())}),_h=s.discriminatedUnion("action",[s.object({action:s.literal("create"),taskId:s.string(),status:be,ignoredFields:s.array(s.string()).optional(),note:s.string().optional()}),s.object({action:s.literal("list"),tasks:s.array(lv)}),s.object({action:s.literal("claim"),taskId:s.string(),status:be,nextStep:s.string()}),s.object({action:s.literal("complete"),taskId:s.string(),status:be}),s.object({action:s.literal("block"),taskId:s.string(),status:be})]),kh=s.object({agentId:s.string(),mode:s.enum(["sync","async"]),status:s.enum(["dispatched","running","queued","joined"]),dispatched:s.boolean(),message:s.string(),deduped:s.boolean().optional(),runId:s.string().optional(),text:s.string().optional(),iterations:s.number().optional()}),dv=s.object({textPreview:s.string(),iterations:s.number(),finishReason:s.string(),durationMs:s.number(),usage:s.object({inputTokens:s.number(),outputTokens:s.number(),cacheReadTokens:s.number().optional(),cacheWriteTokens:s.number().optional(),totalCost:s.number().optional()})}),Ih=s.object({id:s.string(),agentId:s.string(),taskId:s.string().optional(),status:mc,messagePreview:s.string(),priority:s.number(),retryCount:s.number(),maxRetries:s.number(),nextAttemptAt:K.optional(),continueConversation:s.boolean().optional(),startedAt:K,endedAt:K.optional(),leaseOwner:s.string().optional(),heartbeatAt:K.optional(),lastProgressAt:K.optional(),lastProgressMessage:s.string().optional(),currentActivity:s.string().optional(),error:s.string().optional(),resultSummary:dv.optional()}),wh=s.object({id:s.string(),teamId:s.string(),fromAgentId:s.string(),toAgentId:s.string(),subject:s.string(),body:s.string(),taskId:s.string().optional(),sentAt:K,readAt:K.optional()}),Sh=s.object({id:s.string(),teamId:s.string(),title:s.string(),status:hn,requiredSections:s.array(s.string()),createdBy:s.string(),createdAt:K,finalizedAt:K.optional()}),xh=s.object({outcomeId:s.string(),status:hn,requiredSections:s.array(s.string())}),Eh=s.object({agentId:s.string(),status:s.string()}),Oh=s.object({runId:s.string(),status:mc}),Th=s.object({id:s.string(),toAgentId:s.string()}),Nh=s.object({delivered:s.number()}),zh=s.object({id:s.string()}),Uh=s.object({status:s.string()}),Ah=s.object({fragmentId:s.string(),status:s.string()}),Dh=s.object({outcomeId:s.string(),status:hn}),cv;((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"})(cv||={});function mv(e){let{$schema:n,...r}=e;if(typeof r.type==="string")return r;if("properties"in r||"required"in r||"additionalProperties"in r)return{type:"object",...r};for(let a of["oneOf","anyOf","allOf"]){let t=r[a];if(!Array.isArray(t)||t.length===0)continue;if(a==="allOf"){if(t.some((i)=>i&&typeof i==="object"&&i.type==="object"))return{type:"object",...r};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(t.every((i)=>i&&typeof i==="object"&&i.type==="object"))return{type:"object",...r};throw Error(`Tool inputSchema must describe an object at the top level, but the schema has a top-level "${a}" whose branches include non-object types. Pass the strict object schema as inputSchema and reserve union/coercion schemas for use inside execute().`)}return r}function fv(e){let n=mv(e.inputSchema instanceof s.ZodType?qg(e.inputSchema):e.inputSchema);return{name:e.name,description:e.description,inputSchema:n,lifecycle:e.lifecycle,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}import{classifyProviderError as fc,createGateway as pv}from"@cline/llms";import{nanoid as gv}from"nanoid";var vv="Model reached the maximum output token limit before completing the turn",hv="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.",$v="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.",yv="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 mt extends Error{constructor(e,n){super(n?.trim()?`${e} (provider reported: ${n.trim()})`:e);this.name="ContextWindowOverflowError"}}function ve(e,n=8){return`${e}_${gv(n)}`}function bv(e){return e.model!==void 0}function _v(e){if(bv(e))return e;let{providerId:n,modelId:r,apiKey:a,baseUrl:t,headers:i,options:o,...u}=e,d=pv({providerConfigs:[{providerId:n,apiKey:a,baseUrl:t,headers:i,options:o}],telemetry:u.telemetry}).createAgentModel({providerId:n,modelId:r}),c=u.messageModelInfo??{id:r,provider:n};return{...u,model:d,messageModelInfo:c}}function kv(e,n){return{...n?.["*"]??{},...n?.[e]??{}}}function Nr(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function Iv(e){if(typeof e==="string")return e.length;return Nr(e)}function wv(e){let n=e.systemPrompt?.length??0,r=0,a=0,t=0;for(let i of e.messages)for(let o of i.content)switch(o.type){case"text":n+=o.text.length;break;case"reasoning":n+=o.text.length;break;case"file":n+=o.content.length;break;case"tool-call":n+=Nr(o.input);break;case"tool-result":{let u=Iv(o.output);r+=1,a+=u,t=Math.max(t,u),n+=u;break}}return{messageCount:e.messages.length,toolSchemaCount:e.tools.length,systemPromptChars:e.systemPrompt?.length??0,requestJsonChars:Nr({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:n,estimatedTextTokens:Qd(n),toolResultCount:r,toolResultChars:a,maxToolResultChars:t}}class zr extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class pt extends Error{reason;constructor(e){let n=typeof e==="string"?e:e instanceof Error?e.message:e===void 0?"Run aborted":String(e);super(n);this.name="AgentRuntimeAbortError",this.reason=e}}var Tr={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function ft(e,n,r){return{id:ve("msg"),role:e,content:n,createdAt:Date.now(),metadata:r}}function ue(e){return{...e}}function F(e){return e.map((n)=>({...n,content:n.content.map((r)=>({...r})),metadata:n.metadata?{...n.metadata}:void 0,modelInfo:n.modelInfo?{...n.modelInfo}:void 0,metrics:n.metrics?{...n.metrics}:void 0}))}function Sv(e,n){let r=Math.max(0,(n.inputTokens??0)-(e.inputTokens??0)),a=Math.max(0,(n.outputTokens??0)-(e.outputTokens??0)),t=Math.max(0,(n.cacheReadTokens??0)-(e.cacheReadTokens??0)),i=Math.max(0,(n.cacheWriteTokens??0)-(e.cacheWriteTokens??0)),o=Math.max(0,(n.reasoningTokenCount??0)-(e.reasoningTokenCount??0)),u=e.totalCost??0,l=n.totalCost??0,d=Math.max(0,l-u);if(r===0&&a===0&&t===0&&i===0&&o===0&&d===0)return;return{inputTokens:r>0?r:0,outputTokens:a>0?a:0,cacheReadTokens:t>0?t:0,cacheWriteTokens:i>0?i:0,...o>0?{reasoningTokenCount:o}:{},...d>0?{cost:d}:{}}}function xv(e){return e.options?.thinking===!1}function pc(e){if(!e)return"";return e.content.filter((n)=>n.type==="text").map((n)=>n.text).join("")}function Ev(e){let n=e?.content.find((r)=>r.type==="tool-result");if(!n||n.isError)return"";if(typeof n.output==="string")return n.output;try{return JSON.stringify(n.output)}catch{return String(n.output)}}function Ov(e){if(typeof e==="string")return[ft("user",[{type:"text",text:e}])];if(Array.isArray(e))return F(e);return F([e])}class gt{config;listeners=new Set;tools=new Map;hooks={beforeRun:[],afterRun:[],beforeModel:[],afterModel:[],beforeTool:[],afterTool:[],onEvent:[]};state={agentId:"",agentRole:void 0,parentAgentId:void 0,runId:void 0,status:"idle",iteration:0,messages:[],pendingToolCalls:[],usage:ue(Tr),lastError:void 0,lastErrorClass:void 0,lastErrorReported:!1};overflowRecoveryAttempted=!1;initialization;abortController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=q(e.messageModelInfo?.provider)??("providerId"in e?q(e.providerId):void 0),this.telemetryModelId=q(e.messageModelInfo?.id)??("modelId"in e?q(e.modelId):void 0);let n=_v(e);this.config={...n,toolExecution:n.toolExecution??"sequential"},this.state.agentId=n.agentId??ve("agent"),this.state.agentRole=n.agentRole,this.state.parentAgentId=n.parentAgentId,this.state.messages=F(n.initialMessages??[])}async run(e){return this.execute(e)}async continue(e){return this.execute(e)}abort(e){if(!this.abortController)return;if(this.abortController.signal.aborted)return;let n=e instanceof pt?e:new pt(e);this.state.lastError=n.message,this.captureTaskLifecycle(oc,{error:n}),this.abortController.abort(n)}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=ue(Tr),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorReported=!1,this.state.messages=F(e),this.config={...this.config,initialMessages:F(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:F(this.state.messages),pendingToolCalls:[...this.state.pendingToolCalls],usage:ue(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 n=await e.setup?.({agentId:this.state.agentId,agentRole:this.state.agentRole,systemPrompt:this.config.systemPrompt});for(let r of n?.tools??[])this.tools.set(r.name,r);this.registerHooks(n?.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 n=ft("user",[{type:"text",text:e}],{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=ve("run"),this.state.status="running",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorReported=!1,this.state.usage=ue(Tr),this.overflowRecoveryAttempted=!1;try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let a of e?Ov(e):[])this.state.messages.push(a),await this.emit({type:"message-added",snapshot:this.snapshot(),message:a});let n=this.getCompletionToolReminderMessage();if(n)await this.addUserReminderMessage(n);let r;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});let{message:a,finishReason:t}=await this.generateAssistantMessageWithOverflowRecovery();if(t==="aborted")throw this.normalizeAbortError();if(a.content.length===0)throw Error(t==="error"?this.state.lastError??"Model stream failed":"Model returned empty response");let i=a.content.filter((l)=>l.type==="tool-call");if(r=a,this.state.messages.push(a),await this.emit({type:"message-added",snapshot:this.snapshot(),message:a}),await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:a,finishReason:t}),t==="max-tokens"&&i.length===0)throw Error(vv);if(t==="error"&&i.length===0)throw Error(this.state.lastError??"Model stream failed");if(this.state.pendingToolCalls=i.map((l)=>l.toolCallId),i.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let l=this.getCompletionReminderMessages();if(l.length>0){for(let c of l)await this.addUserReminderMessage(c);continue}let d=this.finishRun("completed",r);return await this.callAfterRunHooks(d),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:d}),d}let o=await this.executeToolCalls(i);this.state.pendingToolCalls=[];for(let l of o)this.state.messages.push(l),await this.emit({type:"message-added",snapshot:this.snapshot(),message:l});await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:i.length});let u=this.findCompletingToolMessage(i,o);if(u){let l=this.finishRun("completed",r,Ev(u)||void 0);return await this.callAfterRunHooks(l),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:l}),l}}throw Error(`Agent runtime exceeded maxIterations (${this.config.maxIterations})`)}catch(n){let r=n instanceof Error?n:Error(String(n)),a=r instanceof zr,i=this.abortController.signal.aborted||a?"aborted":"failed",o=r instanceof mt?"context_window_exceeded":r.message===this.state.lastError?this.state.lastErrorClass:void 0,u=r.message===this.state.lastError&&this.state.lastErrorReported;this.state.status=i,this.state.lastError=r.message,this.state.lastErrorClass=o,this.state.lastErrorReported=u;let l=this.findLastAssistantMessage(),d={agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??ve("run"),status:i,iterations:this.state.iteration,outputText:pc(l),messages:F(this.state.messages),usage:ue(this.state.usage),error:i==="failed"?r:void 0};if(this.config.logger?.log?.("Agent loop caught error",{severity:i==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:d.runId,status:i,iteration:this.state.iteration,errorName:r.name,errorMessage:r.message,assistantContentPartCount:l?.content.length??0}),await this.callAfterRunHooks(d),i==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:r,errorClass:o});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:d});return d}finally{this.abortController=void 0}}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let n=await e({snapshot:this.snapshot()});this.applyStopControl(n)}}async callAfterRunHooks(e){for(let n of this.hooks.afterRun)await n({snapshot:this.snapshot(),result:e})}async generateAssistantMessageWithOverflowRecovery(){let e=await this.generateAssistantMessage();if(!this.isRecoverableOverflowTurn(e))return e;this.overflowRecoveryAttempted=!0;let n=this.state.lastError;if(!this.config.prepareTurn)throw new mt(yv,n);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:n}});let r=await this.generateAssistantMessage({overflowRecovery:!0});if(r.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new mt($v,this.state.lastError);return r}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((n)=>n.type==="tool-call")}async generateAssistantMessage(e){let n=ue(this.state.usage),r=ec({sessionId:q(this.config.sessionId),agentId:this.state.agentId,conversationId:q(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),a={systemPrompt:this.config.systemPrompt,messages:F(this.state.messages),tools:[...this.tools.values()].map((y)=>({name:y.name,description:y.description,inputSchema:y.inputSchema})),signal:this.abortController?.signal,options:Or(this.config.modelOptions,{metadata:r})},t=Date.now(),i=()=>Date.now()-t;if(this.state.iteration>1){let y=await this.consumePendingUserMessage();if(y)a={...a,messages:[...a.messages,...F([y])]}}a=await this.prepareTurnForModelRequest(a,e),this.throwIfAborted();for(let y of this.hooks.beforeModel){let k=await y({snapshot:this.snapshot(),request:a});if(this.throwIfAborted(),this.applyStopControl(k),k?.messages)a={...a,messages:F(k.messages)};if(k?.tools)a={...a,tools:[...k.tools]};if(k?.options)a={...a,options:Or(a.options,k.options)}}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,...wv(a)}),this.throwIfAborted(),this.captureTaskLifecycle(nc,{durationMs:i(),phase:"provider_request_started"});let o=this.openTaskLifecycleStream(a,i),u=[],l=new Map,d=[],c=[],p=0,f="stop",$="",x="";for await(let y of o)switch(this.throwIfAborted(),y.type){case"text-delta":{$+=y.text;let k=c.at(-1);if(k?.type==="part"&&k.part.type==="text")k.part.text+=y.text;else c.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:$});break}case"reasoning-delta":{x+=y.text;let k=c.at(-1);if(k?.type==="part"&&k.part.type==="reasoning")k.part.text+=y.text,k.part.redacted=y.redacted??k.part.redacted,k.part.metadata=y.metadata??k.part.metadata;else c.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:x,redacted:y.redacted,metadata:y.metadata});break}case"tool-call-delta":{let k=y.toolCallId??`tool_${y.index??p}`;if(y.index==null&&y.toolCallId==null)p+=1;let S=l.get(k);if(!S)S={toolCallId:y.toolCallId??ve("tool"),inputText:""},l.set(k,S),c.push({type:"tool",key:k});if(y.toolCallId)S.toolCallId=y.toolCallId;if(y.toolName)S.toolName=y.toolName;if(y.input!==void 0)S.inputValue=y.input;if(y.metadata!==void 0)S.metadata=gc(S.metadata,y.metadata);if(y.inputText)S.inputText=Uv(S.inputText,y.inputText);break}case"usage":{await this.updateUsage(y.usage);break}case"finish":{if(f=y.reason,y.error)this.state.lastError=y.error,this.state.lastErrorClass=y.errorClass??fc(y.error),this.state.lastErrorReported=y.errorReported===!0;break}}for(let y of c){if(y.type==="part"){u.push(y.part);continue}let k=l.get(y.key);if(!k?.toolName){d.push({toolCallId:k?.toolCallId??y.key,input:$n(k?.inputText??""),reason:"missing_name"});continue}let S=Nv(k);if(S.reason)d.push({toolCallId:k.toolCallId,toolName:k.toolName,input:S.invalidInput,reason:S.reason});u.push({type:"tool-call",toolCallId:k.toolCallId,toolName:k.toolName,input:S.input,metadata:S.parseError?gc(k.metadata,{inputParseError:S.parseError,rawInputText:k.inputText}):k.metadata})}let N=ft("assistant",u,d.length>0?{invalidToolCalls:d}:void 0),X=Sv(n,this.state.usage);if(X)N.metrics=X,this.captureUnexpectedReasoningTokens(a,X);if(this.config.messageModelInfo)N.modelInfo={...this.config.messageModelInfo};for(let y of this.hooks.afterModel){let k=await y({snapshot:this.snapshot(),assistantMessage:N,finishReason:f});this.applyStopControl(k)}return{message:N,finishReason:f}}async*openTaskLifecycleStream(e,n){let r,a="provider_request_started";try{r=await this.config.model.stream(e),this.throwIfAborted(),a="provider_stream_started",this.captureTaskLifecycle(ic,{durationMs:n(),phase:a})}catch(i){if(!this.isAbortError(i))this.captureTaskLifecycleFailure(i,a,n());throw i}let t=!1;try{for await(let i of r){if(!t)t=!0,a="first_chunk_received",this.captureTaskLifecycle(rc,{durationMs:n(),phase:a,eventType:i.type});yield i}}catch(i){if(!this.isAbortError(i))this.captureTaskLifecycleFailure(i,a,n());throw i}}captureTaskLifecycleFailure(e,n,r){this.captureTaskLifecycle(ac,{durationMs:r,error:e,errorClass:fc(e),phase:n})}captureTaskLifecycle(e,n={}){let r=q(this.config.sessionId);uc(this.config.telemetry,{event:e,sessionId:r,ulid:r,agentId:this.state.agentId,conversationId:q(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration>0?this.state.iteration:void 0,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...n})}getTelemetryProviderId(){return q(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return q(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof pt||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,n){if(!xv(e)||(n.reasoningTokenCount??0)<=0)return;let r=n.reasoningTokenCount;if(r===void 0)return;sc(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:r})}async prepareTurnForModelRequest(e,n){if(!this.config.prepareTurn)return e;let r=n?.overflowRecovery===!0,a=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:r||void 0,emitStatusNotice:(i,o)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:i,metadata:o})}});if(r){if(!(a?.messages!==void 0&&JSON.stringify(a.messages).length<JSON.stringify(e.messages).length))throw new mt(hv,this.state.lastError)}if(!a)return e;let t=e;if(a.messages){let i=F(a.messages);t={...t,messages:F(i)}}if(a.systemPrompt!==void 0)t={...t,systemPrompt:a.systemPrompt};return t}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let n=(await e())?.trim();if(!n)return;let r=ft("user",[{type:"text",text:n}],{userRunSpan:0});return this.state.messages.push(r),await this.emit({type:"message-added",snapshot:this.snapshot(),message:r}),r}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:ue(this.state.usage)})}async executeToolCalls(e){let n=[];for(let a of e)n.push(await this.prepareToolExecution(a));if(this.config.toolExecution==="parallel")return Promise.all(n.map((a)=>this.executePreparedTool(a)));let r=[];for(let a of n)r.push(await this.executePreparedTool(a));return r}findCompletingToolMessage(e,n){for(let r=0;r<e.length;r+=1){let a=e[r];if(this.tools.get(a.toolName)?.lifecycle?.completesRun!==!0)continue;let t=n[r],i=t?.content.find((o)=>o.type==="tool-result"&&o.toolCallId===a.toolCallId);if(i&&!i.isError)return t}return}async prepareToolExecution(e){let n=this.tools.get(e.toolName),r=e.input,a,t=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof t?.inputParseError==="string")a=t.inputParseError;let i=t?.toolSource&&typeof t.toolSource==="object"&&!Array.isArray(t.toolSource)?t.toolSource:void 0;if(i?.executionMode==="provider")a=`Tool execution is disabled for provider ${typeof i.providerId==="string"?i.providerId:"provider"}`;if(n&&!a)r=Et(r,n.inputSchema);let o;if(n&&!a)for(let u of this.hooks.beforeTool){let l=await u({snapshot:this.snapshot(),tool:n,toolCall:{...e,input:r},input:r});if(l?.input!==void 0)r=l.input;if(l?.policy)o={...o,...l.policy};if(this.applyStopControl(l),l?.skip){a=l.reason??`Tool ${n.name} was blocked by a runtime hook`;break}}if(n&&!a){let u={...kv(e.toolName,this.config.toolPolicies),...o};if(u.enabled===!1)a=`Tool "${e.toolName}" is disabled by policy`;else if(u.autoApprove===!1){let l=await this.requestToolApproval(e,r,u);if(!l.approved)a=l.reason??`Tool "${e.toolName}" was not approved`}}return{toolCall:{...e,input:r},tool:n,input:r,skipReason:a}}async requestToolApproval(e,n,r){let a=this.config.requestToolApproval;if(!a)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await a({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:n,policy:r})}catch(t){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${t instanceof Error?t.message:String(t)}`}}}async executePreparedTool(e){let n=new Date;await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let r;if(e.skipReason)r={output:{error:e.skipReason},isError:!0};else if(!e.tool)r={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{r={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??ve("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),emitUpdate:(u)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:u})}})}}catch(o){r={output:{error:o instanceof Error?o.message:String(o)},isError:!0}}let a=new Date,t=Math.max(0,a.getTime()-n.getTime());if(e.tool)for(let o of this.hooks.afterTool){let u=await o({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:r,startedAt:n,endedAt:a,durationMs:t});if(this.applyStopControl(u),u?.result)r=u.result}let i=ft("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:r.output,isError:r.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:i}),i}finishRun(e,n,r){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??ve("run"),status:e,iterations:this.state.iteration,outputText:r??pc(n??this.findLastAssistantMessage()),messages:F(this.state.messages),usage:ue(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 n=Tv(e);switch(e.type){case"run-started":this.config.logger?.info?.("Agent run started",n);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",n);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...n,error:e.error}),!this.state.lastErrorReported)lc(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:n});break;default:this.config.logger?.debug?.("Agent event",n);break}this.config.telemetry?.capture({event:`agent.${e.type}`,properties:n});for(let r of this.listeners)r(e);for(let r of this.hooks.onEvent)await r(e)}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new zr(e.reason)}}function Tv(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 gc(e,n){if(!n||typeof n!=="object"||Array.isArray(n))return n;if(!e||typeof e!=="object"||Array.isArray(e))return n;return{...e,...n}}function Nv(e){if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:$n(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let n=zv(e.inputText);if(n.ok)return{input:n.value,invalidInput:$n(e.inputText)};return{input:{},invalidInput:$n(e.inputText,n.error),parseError:`Tool call ${e.toolName??e.toolCallId} emitted invalid JSON arguments: ${n.error}`,reason:"invalid_arguments"}}function $n(e,n){if(!e.trim())return{};return n?{rawInputText:e,parseError:n}:{rawInputText:e}}function zv(e){let n=e.trim();if(!n)return{ok:!1,error:"Tool call arguments were empty."};try{return{ok:!0,value:JSON.parse(n)}}catch{}if(!(n.startsWith("{")||n.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 Uv(e,n){if(!e)return n;let r=n.trimStart();if(r.startsWith("{")||r.startsWith("["))return n;return e+n}function Av(e){return new gt(e)}var Dv=gt;function Pv(e){return new gt(e)}export{fv as createTool,Av as createAgentRuntime,Pv as createAgent,pt as AgentRuntimeAbortError,gt as AgentRuntime,Dv as Agent};
|
|
80
|
+
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 Hv=Er.enum(["reasoning","prompt-cache","tools","provider-tools","oauth","temperature","files","streaming","vision","computer-use","local-auth","popular"]),Xv=Er.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),Yv=Er.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]);var nc="task.provider_request_started",ic="task.provider_stream_started",rc="task.first_chunk_received",ac="task.provider_stream_failed",oc="task.cancelled";var $e=new Map;function Hg(e,n){let r=typeof n.error_message==="string"?n.error_message:"";return[e,n.component,n.operation,n.error_type,n.error_code??"",n.error_status??"",r.replace(/\d+/g,"#").replace(/\s+/g," ").trim().toLowerCase().slice(0,256)].join("\x00")}function Xg(e){let n=Date.now(),r=$e.get(e);if(r&&n-r.startMs<3600000){if(r.emitted<5)return r.emitted+=1,{emit:!0,suppressed:0};return r.suppressed+=1,{emit:!1,suppressed:r.suppressed}}let a=r?.suppressed??0;if($e.delete(e),$e.size>=512){let t=$e.keys().next();if(!t.done)$e.delete(t.value)}return $e.set(e,{startMs:n,emitted:1,suppressed:0}),{emit:!0,suppressed:a}}function sc(e,n){e?.capture({event:"agent.reasoning.unexpected_tokens",properties:dc({sessionId:n.sessionId,agentId:n.agentId,runId:n.runId,iteration:n.iteration,providerId:n.providerId,modelId:n.modelId,requestedThinking:n.requestedThinking,reasoningTokenCount:n.reasoningTokenCount})})}function uc(e,n){if(!e)return;e.capture({event:n.event,properties:dc({sessionId:n.sessionId,ulid:n.ulid??n.sessionId,agentId:n.agentId,conversationId:n.conversationId,runId:n.runId,iteration:n.iteration,provider:n.providerId,providerId:n.providerId,model:n.modelId,modelId:n.modelId,phase:n.phase,durationMs:n.durationMs,eventType:n.eventType,...n.error===void 0?{}:cc(n.error,n.messageLimit),error_class:n.errorClass})})}function lc(e,n){if(!e)return!1;let r=n.event??"sdk.error",a=Yg(n),t=0;try{let i=Xg(Hg(r,a));if(!i.emit)return!0;t=i.suppressed}catch{}return e.capture({event:r,properties:t>0?{...a,suppressed_count:t}:a}),!0}function Yg(e){return{...e.context??{},component:e.component,operation:e.operation,severity:e.severity??"error",handled:e.handled??!0,...cc(e.error,e.messageLimit,e.errorMessage)}}function dc(e){let n={};for(let[r,a]of Object.entries(e))if(a!==void 0)n[r]=a;return n}function cc(e,n=500,r){let a=tv(e)?e:void 0,t=e instanceof Error?e:void 0,i=Ae(r)??Ae(t?.message)??Ae(a?.message)??nv(e)??"Unknown error",o=iv(a?.code),u=bn(a?.status)??bn(a?.statusCode)??bn(a?.responseStatus);return{error_type:t?.name?.trim()||Ae(a?.name)||t?.constructor?.name||"Error",error_message:ev(Qg(i),n),...o!==void 0?{error_code:o}:{},...u!==void 0?{error_status:u}:{}}}function Qg(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 ev(e,n){let r=Math.max(1,Math.floor(n));return e.length>r?e.substring(0,r):e}function tv(e){return typeof e==="object"&&e!==null}function Ae(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function nv(e){if(e instanceof Error)return;let n=typeof e==="string"?e:String(e);return n==="[object Object]"?void 0:Ae(n)}function iv(e){if(typeof e==="string"&&e.trim().length>0)return e;if(typeof e==="number"&&Number.isFinite(e))return e;return}function bn(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}var rv=["rules","skills","workflows","plugins"];var Qv=new Set(rv);var av=s.object({rootPath:s.string().min(1),hint:s.string().min(1).optional(),associatedRemoteUrls:s.array(s.string().min(1)).optional(),latestGitCommitHash:s.string().min(1).optional(),latestGitBranchName:s.string().min(1).optional()}),eh=s.object({currentWorkspacePath:s.string().min(1).optional(),workspaces:s.record(s.string().min(1),av)});var ov=["current_state","boundary_analysis","interface_proposal"];var K=s.preprocess((e)=>e instanceof Date?e.toISOString():e,s.string().datetime()),be=s.enum(["pending","in_progress","blocked","completed"]),mc=s.enum(["queued","running","completed","failed","cancelled","interrupted"]),hn=s.enum(["draft","in_review","finalized"]),sv=s.object({agentId:s.string(),role:s.enum(["lead","teammate"]),description:s.string().optional(),status:s.enum(["idle","running","stopped"])}),th=s.object({agentId:s.string(),rolePrompt:s.string(),modelId:s.string().optional(),maxIterations:s.number().optional()});function A(e){return s.preprocess((n)=>n===null?void 0:n,e.optional())}var nh=s.object({agentId:s.string().min(1).describe("Teammate identifier"),rolePrompt:s.string().min(1).describe("System prompt describing teammate role")}).strict(),ih=s.object({agentId:s.string().min(1).describe("Teammate identifier"),reason:A(s.string().min(1)).describe("Optional shutdown reason")}),rh=s.object({}),uv={create:["title","description"],list:[],claim:["taskId"],complete:["taskId","summary"],block:["taskId","reason"]};var ah=s.object({action:s.enum(["create","list","claim","complete","block"]),title:A(s.string().min(1)).describe("Task title"),description:A(s.string().min(1)).describe("Task details"),dependsOn:A(s.array(s.string().describe("Dependency task ID"))).describe("Array of dependency task IDs"),assignee:A(s.string().min(1)).describe("Optional assignee"),status:A(s.enum(["pending","in_progress","blocked","completed"])).describe("Optional task status filter"),taskId:A(s.string()).describe("Task ID"),summary:A(s.string().min(1)).describe("Completion summary"),reason:A(s.string().min(1)).describe("Blocking reason")}).superRefine((e,n)=>{for(let r of uv[e.action]){if(e[r]!==void 0)continue;n.addIssue({code:"custom",path:[r],message:`Field "${r}" is required when action=${e.action}`})}}),oh=s.object({agentId:s.string().describe("Teammate agent ID"),task:s.string().min(1).describe("Task instructions for the teammate"),taskId:A(s.string()).describe("Optional shared task list ID"),runMode:A(s.enum(["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:A(s.boolean()).describe("If true, continue the teammate conversation; otherwise start fresh")}),sh=s.object({status:A(s.enum(["queued","running","completed","failed","cancelled","interrupted"])).describe("Optional run status filter. Omit to include all statuses."),agentId:A(s.string().min(1)).describe("Optional teammate ID filter. Omit to include all teammates."),includeCompleted:A(s.boolean()).describe("Include completed/failed runs (default true)")}),uh=s.object({runId:s.string().min(1).describe("Run ID"),reason:A(s.string().min(1)).describe("Optional cancellation reason")}),lh=s.object({runId:A(s.string().min(1)).describe("Optional async run ID to await. Omit to wait for all active async runs.")}).strict(),dh=s.object({toAgentId:s.string().min(1).describe("Recipient agent ID"),subject:s.string().min(1).describe("Message subject"),body:s.string().min(1).describe("Message body"),taskId:A(s.string().min(1)).describe("Optional task ID context")}),ch=s.object({subject:s.string().min(1).describe("Message subject"),body:s.string().min(1).describe("Message body"),taskId:A(s.string().min(1)).describe("Optional task ID context")}),mh=s.object({unreadOnly:A(s.boolean()).describe("Only unread messages for read action (default true)")}),fh=s.object({kind:s.enum(["progress","handoff","blocked","decision","done","error"]),summary:s.string().min(1).describe("Update summary"),taskId:A(s.string().min(1)).describe("Optional task ID context"),evidence:A(s.array(s.string().min(1))).describe("Optional evidence links/snippets"),nextAction:A(s.string().min(1)).describe("Planned next step")}),ph=s.object({}),gh=s.object({title:s.string().describe("Outcome title"),requiredSections:s.array(s.string()).default(ov).describe("Required sections for finalization gate (defaults to current_state,boundary_analysis,interface_proposal)")}),vh=s.object({outcomeId:s.string().describe("Outcome ID"),section:s.string().describe("Section name"),sourceRunId:A(s.string()).describe("Optional source run ID"),content:s.string().describe("Section fragment content")}),hh=s.object({fragmentId:s.string().describe("Fragment ID"),approved:s.boolean().describe("Review decision")}),$h=s.object({outcomeId:s.string().describe("Outcome ID")}),yh=s.object({}),bh=s.object({teamId:s.string(),teamName:s.string(),members:s.array(sv),taskCounts:s.record(be,s.number()),unreadMessages:s.number(),missionLogEntries:s.number(),activeRuns:s.number(),queuedRuns:s.number(),outcomeCounts:s.record(hn,s.number())}),lv=s.object({id:s.string(),title:s.string(),description:s.string(),status:be,createdAt:K,updatedAt:K,createdBy:s.string(),assignee:s.string().optional(),dependsOn:s.array(s.string()),summary:s.string().optional(),isReady:s.boolean(),blockedBy:s.array(s.string())}),_h=s.discriminatedUnion("action",[s.object({action:s.literal("create"),taskId:s.string(),status:be,ignoredFields:s.array(s.string()).optional(),note:s.string().optional()}),s.object({action:s.literal("list"),tasks:s.array(lv)}),s.object({action:s.literal("claim"),taskId:s.string(),status:be,nextStep:s.string()}),s.object({action:s.literal("complete"),taskId:s.string(),status:be}),s.object({action:s.literal("block"),taskId:s.string(),status:be})]),kh=s.object({agentId:s.string(),mode:s.enum(["sync","async"]),status:s.enum(["dispatched","running","queued","joined"]),dispatched:s.boolean(),message:s.string(),deduped:s.boolean().optional(),runId:s.string().optional(),text:s.string().optional(),iterations:s.number().optional()}),dv=s.object({textPreview:s.string(),iterations:s.number(),finishReason:s.string(),durationMs:s.number(),usage:s.object({inputTokens:s.number(),outputTokens:s.number(),cacheReadTokens:s.number().optional(),cacheWriteTokens:s.number().optional(),totalCost:s.number().optional()})}),Ih=s.object({id:s.string(),agentId:s.string(),taskId:s.string().optional(),status:mc,messagePreview:s.string(),priority:s.number(),retryCount:s.number(),maxRetries:s.number(),nextAttemptAt:K.optional(),continueConversation:s.boolean().optional(),startedAt:K,endedAt:K.optional(),leaseOwner:s.string().optional(),heartbeatAt:K.optional(),lastProgressAt:K.optional(),lastProgressMessage:s.string().optional(),currentActivity:s.string().optional(),error:s.string().optional(),resultSummary:dv.optional()}),wh=s.object({id:s.string(),teamId:s.string(),fromAgentId:s.string(),toAgentId:s.string(),subject:s.string(),body:s.string(),taskId:s.string().optional(),sentAt:K,readAt:K.optional()}),Sh=s.object({id:s.string(),teamId:s.string(),title:s.string(),status:hn,requiredSections:s.array(s.string()),createdBy:s.string(),createdAt:K,finalizedAt:K.optional()}),xh=s.object({outcomeId:s.string(),status:hn,requiredSections:s.array(s.string())}),Eh=s.object({agentId:s.string(),status:s.string()}),Oh=s.object({runId:s.string(),status:mc}),Th=s.object({id:s.string(),toAgentId:s.string()}),Nh=s.object({delivered:s.number()}),zh=s.object({id:s.string()}),Uh=s.object({status:s.string()}),Ah=s.object({fragmentId:s.string(),status:s.string()}),Dh=s.object({outcomeId:s.string(),status:hn}),cv;((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"})(cv||={});function mv(e){let{$schema:n,...r}=e;if(typeof r.type==="string")return r;if("properties"in r||"required"in r||"additionalProperties"in r)return{type:"object",...r};for(let a of["oneOf","anyOf","allOf"]){let t=r[a];if(!Array.isArray(t)||t.length===0)continue;if(a==="allOf"){if(t.some((i)=>i&&typeof i==="object"&&i.type==="object"))return{type:"object",...r};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(t.every((i)=>i&&typeof i==="object"&&i.type==="object"))return{type:"object",...r};throw Error(`Tool inputSchema must describe an object at the top level, but the schema has a top-level "${a}" whose branches include non-object types. Pass the strict object schema as inputSchema and reserve union/coercion schemas for use inside execute().`)}return r}function fv(e){let n=mv(e.inputSchema instanceof s.ZodType?qg(e.inputSchema):e.inputSchema);return{name:e.name,description:e.description,inputSchema:n,lifecycle:e.lifecycle,timeoutMs:e.timeoutMs??30000,retryable:e.retryable??!0,maxRetries:e.maxRetries??3,execute:e.execute}}import{classifyProviderError as fc,createGateway as pv}from"@cline/llms";import{nanoid as gv}from"nanoid";var vv="Model reached the maximum output token limit before completing the turn",hv="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.",$v="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.",yv="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 mt extends Error{constructor(e,n){super(n?.trim()?`${e} (provider reported: ${n.trim()})`:e);this.name="ContextWindowOverflowError"}}function ve(e,n=8){return`${e}_${gv(n)}`}function bv(e){return e.model!==void 0}function _v(e){if(bv(e))return e;let{providerId:n,modelId:r,apiKey:a,baseUrl:t,headers:i,options:o,...u}=e,d=pv({providerConfigs:[{providerId:n,apiKey:a,baseUrl:t,headers:i,options:o}],telemetry:u.telemetry}).createAgentModel({providerId:n,modelId:r}),c=u.messageModelInfo??{id:r,provider:n};return{...u,model:d,messageModelInfo:c}}function kv(e,n){return{...n?.["*"]??{},...n?.[e]??{}}}function Nr(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function Iv(e){if(typeof e==="string")return e.length;return Nr(e)}function wv(e){let n=e.systemPrompt?.length??0,r=0,a=0,t=0;for(let i of e.messages)for(let o of i.content)switch(o.type){case"text":n+=o.text.length;break;case"reasoning":n+=o.text.length;break;case"file":n+=o.content.length;break;case"tool-call":n+=Nr(o.input);break;case"tool-result":{let u=Iv(o.output);r+=1,a+=u,t=Math.max(t,u),n+=u;break}}return{messageCount:e.messages.length,toolSchemaCount:e.tools.length,systemPromptChars:e.systemPrompt?.length??0,requestJsonChars:Nr({systemPrompt:e.systemPrompt,messages:e.messages,tools:e.tools,options:e.options}),visibleTextChars:n,estimatedTextTokens:Qd(n),toolResultCount:r,toolResultChars:a,maxToolResultChars:t}}class zr extends Error{reason;constructor(e){super(e??"Run stopped by runtime control");this.name="ControlledStopError",this.reason=e}}class pt extends Error{reason;constructor(e){let n=typeof e==="string"?e:e instanceof Error?e.message:e===void 0?"Run aborted":String(e);super(n);this.name="AgentRuntimeAbortError",this.reason=e}}var Tr={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};function ft(e,n,r){return{id:ve("msg"),role:e,content:n,createdAt:Date.now(),metadata:r}}function ue(e){return{...e}}function F(e){return e.map((n)=>({...n,content:n.content.map((r)=>({...r})),metadata:n.metadata?{...n.metadata}:void 0,modelInfo:n.modelInfo?{...n.modelInfo}:void 0,metrics:n.metrics?{...n.metrics}:void 0}))}function Sv(e,n){let r=Math.max(0,(n.inputTokens??0)-(e.inputTokens??0)),a=Math.max(0,(n.outputTokens??0)-(e.outputTokens??0)),t=Math.max(0,(n.cacheReadTokens??0)-(e.cacheReadTokens??0)),i=Math.max(0,(n.cacheWriteTokens??0)-(e.cacheWriteTokens??0)),o=Math.max(0,(n.reasoningTokenCount??0)-(e.reasoningTokenCount??0)),u=e.totalCost??0,l=n.totalCost??0,d=Math.max(0,l-u);if(r===0&&a===0&&t===0&&i===0&&o===0&&d===0)return;return{inputTokens:r>0?r:0,outputTokens:a>0?a:0,cacheReadTokens:t>0?t:0,cacheWriteTokens:i>0?i:0,...o>0?{reasoningTokenCount:o}:{},...d>0?{cost:d}:{}}}function xv(e){return e.options?.thinking===!1}function pc(e){if(!e)return"";return e.content.filter((n)=>n.type==="text").map((n)=>n.text).join("")}function Ev(e){let n=e?.content.find((r)=>r.type==="tool-result");if(!n||n.isError)return"";if(typeof n.output==="string")return n.output;try{return JSON.stringify(n.output)}catch{return String(n.output)}}function Ov(e){if(typeof e==="string")return[ft("user",[{type:"text",text:e}])];if(Array.isArray(e))return F(e);return F([e])}class gt{config;listeners=new Set;tools=new Map;hooks={beforeRun:[],afterRun:[],beforeModel:[],afterModel:[],beforeTool:[],afterTool:[],onEvent:[]};state={agentId:"",agentRole:void 0,parentAgentId:void 0,runId:void 0,status:"idle",iteration:0,messages:[],pendingToolCalls:[],usage:ue(Tr),lastError:void 0,lastErrorClass:void 0,lastErrorReported:!1};overflowRecoveryAttempted=!1;initialization;abortController;telemetryProviderId;telemetryModelId;constructor(e){this.telemetryProviderId=q(e.messageModelInfo?.provider)??("providerId"in e?q(e.providerId):void 0),this.telemetryModelId=q(e.messageModelInfo?.id)??("modelId"in e?q(e.modelId):void 0);let n=_v(e);this.config={...n,toolExecution:n.toolExecution??"sequential"},this.state.agentId=n.agentId??ve("agent"),this.state.agentRole=n.agentRole,this.state.parentAgentId=n.parentAgentId,this.state.messages=F(n.initialMessages??[])}async run(e){return this.execute(e)}async continue(e){return this.execute(e)}abort(e){if(!this.abortController)return;if(this.abortController.signal.aborted)return;let n=e instanceof pt?e:new pt(e);this.state.lastError=n.message,this.captureTaskLifecycle(oc,{error:n}),this.abortController.abort(n)}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=ue(Tr),this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorReported=!1,this.state.messages=F(e),this.config={...this.config,initialMessages:F(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:F(this.state.messages),pendingToolCalls:[...this.state.pendingToolCalls],usage:ue(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 n=await e.setup?.({agentId:this.state.agentId,agentRole:this.state.agentRole,systemPrompt:this.config.systemPrompt});for(let r of n?.tools??[])this.tools.set(r.name,r);this.registerHooks(n?.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 n=ft("user",[{type:"text",text:e}],{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=ve("run"),this.state.status="running",this.state.iteration=0,this.state.pendingToolCalls=[],this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorReported=!1,this.state.usage=ue(Tr),this.overflowRecoveryAttempted=!1;try{await this.callBeforeRunHooks(),await this.emit({type:"run-started",snapshot:this.snapshot()});for(let a of e?Ov(e):[])this.state.messages.push(a),await this.emit({type:"message-added",snapshot:this.snapshot(),message:a});let n=this.getCompletionToolReminderMessage();if(n)await this.addUserReminderMessage(n);let r;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});let{message:a,finishReason:t}=await this.generateAssistantMessageWithOverflowRecovery();if(t==="aborted")throw this.normalizeAbortError();if(a.content.length===0)throw Error(t==="error"?this.state.lastError??"Model stream failed":"Model returned empty response");let i=a.content.filter((l)=>l.type==="tool-call");if(r=a,this.state.messages.push(a),await this.emit({type:"message-added",snapshot:this.snapshot(),message:a}),await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:a,finishReason:t}),t==="max-tokens"&&i.length===0)throw Error(vv);if(t==="error"&&i.length===0)throw Error(this.state.lastError??"Model stream failed");if(this.state.pendingToolCalls=i.map((l)=>l.toolCallId),i.length===0){await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:0});let l=this.getCompletionReminderMessages();if(l.length>0){for(let c of l)await this.addUserReminderMessage(c);continue}let d=this.finishRun("completed",r);return await this.callAfterRunHooks(d),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:d}),d}let o=await this.executeToolCalls(i);this.state.pendingToolCalls=[];for(let l of o)this.state.messages.push(l),await this.emit({type:"message-added",snapshot:this.snapshot(),message:l});await this.emit({type:"turn-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCallCount:i.length});let u=this.findCompletingToolMessage(i,o);if(u){let l=this.finishRun("completed",r,Ev(u)||void 0);return await this.callAfterRunHooks(l),await this.emit({type:"run-finished",snapshot:this.snapshot(),result:l}),l}}throw Error(`Agent runtime exceeded maxIterations (${this.config.maxIterations})`)}catch(n){let r=n instanceof Error?n:Error(String(n)),a=r instanceof zr,i=this.abortController.signal.aborted||a?"aborted":"failed",o=r instanceof mt?"context_window_exceeded":r.message===this.state.lastError?this.state.lastErrorClass:void 0,u=r.message===this.state.lastError&&this.state.lastErrorReported;this.state.status=i,this.state.lastError=r.message,this.state.lastErrorClass=o,this.state.lastErrorReported=u;let l=this.findLastAssistantMessage(),d={agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??ve("run"),status:i,iterations:this.state.iteration,outputText:pc(l),messages:F(this.state.messages),usage:ue(this.state.usage),error:i==="failed"?r:void 0};if(this.config.logger?.log?.("Agent loop caught error",{severity:i==="failed"?"error":"warn",agentId:this.state.agentId,agentRole:this.state.agentRole,runId:d.runId,status:i,iteration:this.state.iteration,errorName:r.name,errorMessage:r.message,assistantContentPartCount:l?.content.length??0}),await this.callAfterRunHooks(d),i==="failed")await this.emit({type:"run-failed",snapshot:this.snapshot(),error:r,errorClass:o});else await this.emit({type:"run-finished",snapshot:this.snapshot(),result:d});return d}finally{this.abortController=void 0}}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let n=await e({snapshot:this.snapshot()});this.applyStopControl(n)}}async callAfterRunHooks(e){for(let n of this.hooks.afterRun)await n({snapshot:this.snapshot(),result:e})}async generateAssistantMessageWithOverflowRecovery(){let e=await this.generateAssistantMessage();if(!this.isRecoverableOverflowTurn(e))return e;this.overflowRecoveryAttempted=!0;let n=this.state.lastError;if(!this.config.prepareTurn)throw new mt(yv,n);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:n}});let r=await this.generateAssistantMessage({overflowRecovery:!0});if(r.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new mt($v,this.state.lastError);return r}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((n)=>n.type==="tool-call")}async generateAssistantMessage(e){let n=ue(this.state.usage),r=ec({sessionId:q(this.config.sessionId),agentId:this.state.agentId,conversationId:q(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),a={systemPrompt:this.config.systemPrompt,messages:F(this.state.messages),tools:[...this.tools.values()].map((y)=>({name:y.name,description:y.description,inputSchema:y.inputSchema})),signal:this.abortController?.signal,options:Or(this.config.modelOptions,{metadata:r})},t=Date.now(),i=()=>Date.now()-t;if(this.state.iteration>1){let y=await this.consumePendingUserMessage();if(y)a={...a,messages:[...a.messages,...F([y])]}}a=await this.prepareTurnForModelRequest(a,e),this.throwIfAborted();for(let y of this.hooks.beforeModel){let k=await y({snapshot:this.snapshot(),request:a});if(this.throwIfAborted(),this.applyStopControl(k),k?.messages)a={...a,messages:F(k.messages)};if(k?.tools)a={...a,tools:[...k.tools]};if(k?.options)a={...a,options:Or(a.options,k.options)}}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,...wv(a)}),this.throwIfAborted(),this.captureTaskLifecycle(nc,{durationMs:i(),phase:"provider_request_started"});let o=this.openTaskLifecycleStream(a,i),u=[],l=new Map,d=[],c=[],p=0,f="stop",$="",x="";for await(let y of o)switch(this.throwIfAborted(),y.type){case"text-delta":{$+=y.text;let k=c.at(-1);if(k?.type==="part"&&k.part.type==="text")k.part.text+=y.text;else c.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:$});break}case"reasoning-delta":{x+=y.text;let k=c.at(-1);if(k?.type==="part"&&k.part.type==="reasoning")k.part.text+=y.text,k.part.redacted=y.redacted??k.part.redacted,k.part.metadata=y.metadata??k.part.metadata;else c.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:x,redacted:y.redacted,metadata:y.metadata});break}case"tool-call-delta":{let k=y.toolCallId??`tool_${y.index??p}`;if(y.index==null&&y.toolCallId==null)p+=1;let S=l.get(k);if(!S)S={toolCallId:y.toolCallId??ve("tool"),inputText:""},l.set(k,S),c.push({type:"tool",key:k});if(y.toolCallId)S.toolCallId=y.toolCallId;if(y.toolName)S.toolName=y.toolName;if(y.input!==void 0)S.inputValue=y.input;if(y.metadata!==void 0)S.metadata=gc(S.metadata,y.metadata);if(y.inputText)S.inputText=Uv(S.inputText,y.inputText);break}case"file":{c.push({type:"part",part:y.mediaType.startsWith("image/")?{type:"image",image:y.data,mediaType:y.mediaType}:{type:"file",path:`model-generated-file-${c.length+1}`,content:y.data}});break}case"usage":{await this.updateUsage(y.usage);break}case"finish":{if(f=y.reason,y.error)this.state.lastError=y.error,this.state.lastErrorClass=y.errorClass??fc(y.error),this.state.lastErrorReported=y.errorReported===!0;break}}for(let y of c){if(y.type==="part"){u.push(y.part);continue}let k=l.get(y.key);if(!k?.toolName){d.push({toolCallId:k?.toolCallId??y.key,input:$n(k?.inputText??""),reason:"missing_name"});continue}let S=Nv(k);if(S.reason)d.push({toolCallId:k.toolCallId,toolName:k.toolName,input:S.invalidInput,reason:S.reason});u.push({type:"tool-call",toolCallId:k.toolCallId,toolName:k.toolName,input:S.input,metadata:S.parseError?gc(k.metadata,{inputParseError:S.parseError,rawInputText:k.inputText}):k.metadata})}let N=ft("assistant",u,d.length>0?{invalidToolCalls:d}:void 0),X=Sv(n,this.state.usage);if(X)N.metrics=X,this.captureUnexpectedReasoningTokens(a,X);if(this.config.messageModelInfo)N.modelInfo={...this.config.messageModelInfo};for(let y of this.hooks.afterModel){let k=await y({snapshot:this.snapshot(),assistantMessage:N,finishReason:f});this.applyStopControl(k)}return{message:N,finishReason:f}}async*openTaskLifecycleStream(e,n){let r,a="provider_request_started";try{r=await this.config.model.stream(e),this.throwIfAborted(),a="provider_stream_started",this.captureTaskLifecycle(ic,{durationMs:n(),phase:a})}catch(i){if(!this.isAbortError(i))this.captureTaskLifecycleFailure(i,a,n());throw i}let t=!1;try{for await(let i of r){if(!t)t=!0,a="first_chunk_received",this.captureTaskLifecycle(rc,{durationMs:n(),phase:a,eventType:i.type});yield i}}catch(i){if(!this.isAbortError(i))this.captureTaskLifecycleFailure(i,a,n());throw i}}captureTaskLifecycleFailure(e,n,r){this.captureTaskLifecycle(ac,{durationMs:r,error:e,errorClass:fc(e),phase:n})}captureTaskLifecycle(e,n={}){let r=q(this.config.sessionId);uc(this.config.telemetry,{event:e,sessionId:r,ulid:r,agentId:this.state.agentId,conversationId:q(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration>0?this.state.iteration:void 0,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...n})}getTelemetryProviderId(){return q(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return q(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof pt||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,n){if(!xv(e)||(n.reasoningTokenCount??0)<=0)return;let r=n.reasoningTokenCount;if(r===void 0)return;sc(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:r})}async prepareTurnForModelRequest(e,n){if(!this.config.prepareTurn)return e;let r=n?.overflowRecovery===!0,a=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:r||void 0,emitStatusNotice:(i,o)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:i,metadata:o})}});if(r){if(!(a?.messages!==void 0&&JSON.stringify(a.messages).length<JSON.stringify(e.messages).length))throw new mt(hv,this.state.lastError)}if(!a)return e;let t=e;if(a.messages){let i=F(a.messages);t={...t,messages:F(i)}}if(a.systemPrompt!==void 0)t={...t,systemPrompt:a.systemPrompt};return t}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let n=(await e())?.trim();if(!n)return;let r=ft("user",[{type:"text",text:n}],{userRunSpan:0});return this.state.messages.push(r),await this.emit({type:"message-added",snapshot:this.snapshot(),message:r}),r}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:ue(this.state.usage)})}async executeToolCalls(e){let n=[];for(let a of e)n.push(await this.prepareToolExecution(a));if(this.config.toolExecution==="parallel")return Promise.all(n.map((a)=>this.executePreparedTool(a)));let r=[];for(let a of n)r.push(await this.executePreparedTool(a));return r}findCompletingToolMessage(e,n){for(let r=0;r<e.length;r+=1){let a=e[r];if(this.tools.get(a.toolName)?.lifecycle?.completesRun!==!0)continue;let t=n[r],i=t?.content.find((o)=>o.type==="tool-result"&&o.toolCallId===a.toolCallId);if(i&&!i.isError)return t}return}async prepareToolExecution(e){let n=this.tools.get(e.toolName),r=e.input,a,t=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof t?.inputParseError==="string")a=t.inputParseError;let i=t?.toolSource&&typeof t.toolSource==="object"&&!Array.isArray(t.toolSource)?t.toolSource:void 0;if(i?.executionMode==="provider")a=`Tool execution is disabled for provider ${typeof i.providerId==="string"?i.providerId:"provider"}`;if(n&&!a)r=Et(r,n.inputSchema);let o;if(n&&!a)for(let u of this.hooks.beforeTool){let l=await u({snapshot:this.snapshot(),tool:n,toolCall:{...e,input:r},input:r});if(l?.input!==void 0)r=l.input;if(l?.policy)o={...o,...l.policy};if(this.applyStopControl(l),l?.skip){a=l.reason??`Tool ${n.name} was blocked by a runtime hook`;break}}if(n&&!a){let u={...kv(e.toolName,this.config.toolPolicies),...o};if(u.enabled===!1)a=`Tool "${e.toolName}" is disabled by policy`;else if(u.autoApprove===!1){let l=await this.requestToolApproval(e,r,u);if(!l.approved)a=l.reason??`Tool "${e.toolName}" was not approved`}}return{toolCall:{...e,input:r},tool:n,input:r,skipReason:a}}async requestToolApproval(e,n,r){let a=this.config.requestToolApproval;if(!a)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await a({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:n,policy:r})}catch(t){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${t instanceof Error?t.message:String(t)}`}}}async executePreparedTool(e){let n=new Date;await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let r;if(e.skipReason)r={output:{error:e.skipReason},isError:!0};else if(!e.tool)r={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{r={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??ve("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),emitUpdate:(u)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:u})}})}}catch(o){r={output:{error:o instanceof Error?o.message:String(o)},isError:!0}}let a=new Date,t=Math.max(0,a.getTime()-n.getTime());if(e.tool)for(let o of this.hooks.afterTool){let u=await o({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:r,startedAt:n,endedAt:a,durationMs:t});if(this.applyStopControl(u),u?.result)r=u.result}let i=ft("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:r.output,isError:r.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:i}),i}finishRun(e,n,r){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??ve("run"),status:e,iterations:this.state.iteration,outputText:r??pc(n??this.findLastAssistantMessage()),messages:F(this.state.messages),usage:ue(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 n=Tv(e);switch(e.type){case"run-started":this.config.logger?.info?.("Agent run started",n);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",n);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...n,error:e.error}),!this.state.lastErrorReported)lc(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:n});break;default:this.config.logger?.debug?.("Agent event",n);break}this.config.telemetry?.capture({event:`agent.${e.type}`,properties:n});for(let r of this.listeners)r(e);for(let r of this.hooks.onEvent)await r(e)}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new zr(e.reason)}}function Tv(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 gc(e,n){if(!n||typeof n!=="object"||Array.isArray(n))return n;if(!e||typeof e!=="object"||Array.isArray(e))return n;return{...e,...n}}function Nv(e){if(e.inputValue!==void 0)return{input:e.inputValue,invalidInput:$n(JSON.stringify(e.inputValue))};if(!e.inputText.trim())return{input:{},invalidInput:{}};let n=zv(e.inputText);if(n.ok)return{input:n.value,invalidInput:$n(e.inputText)};return{input:{},invalidInput:$n(e.inputText,n.error),parseError:`Tool call ${e.toolName??e.toolCallId} emitted invalid JSON arguments: ${n.error}`,reason:"invalid_arguments"}}function $n(e,n){if(!e.trim())return{};return n?{rawInputText:e,parseError:n}:{rawInputText:e}}function zv(e){let n=e.trim();if(!n)return{ok:!1,error:"Tool call arguments were empty."};try{return{ok:!0,value:JSON.parse(n)}}catch{}if(!(n.startsWith("{")||n.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 Uv(e,n){if(!e)return n;let r=n.trimStart();if(r.startsWith("{")||r.startsWith("["))return n;return e+n}function Av(e){return new gt(e)}var Dv=gt;function Pv(e){return new gt(e)}export{fv as createTool,Av as createAgentRuntime,Pv as createAgent,pt as AgentRuntimeAbortError,gt as AgentRuntime,Dv as Agent};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cline/agents",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.70",
|
|
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.70",
|
|
12
|
+
"@cline/shared": "0.0.70",
|
|
13
13
|
"nanoid": "^5.1.7"
|
|
14
14
|
},
|
|
15
15
|
"exports": {
|