@cline/core 0.0.38-nightly.1778113663

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.
Files changed (227) hide show
  1. package/README.md +108 -0
  2. package/dist/ClineCore.d.ts +282 -0
  3. package/dist/account/cline-account-service.d.ts +37 -0
  4. package/dist/account/index.d.ts +3 -0
  5. package/dist/account/rpc.d.ts +40 -0
  6. package/dist/account/types.d.ts +98 -0
  7. package/dist/auth/bounded-ttl-cache.d.ts +13 -0
  8. package/dist/auth/client.d.ts +30 -0
  9. package/dist/auth/cline.d.ts +64 -0
  10. package/dist/auth/codex.d.ts +43 -0
  11. package/dist/auth/oca.d.ts +28 -0
  12. package/dist/auth/server.d.ts +54 -0
  13. package/dist/auth/types.d.ts +103 -0
  14. package/dist/auth/utils.d.ts +32 -0
  15. package/dist/cline-core/automation.d.ts +34 -0
  16. package/dist/cline-core/runtime-services.d.ts +5 -0
  17. package/dist/cline-core/start-input.d.ts +10 -0
  18. package/dist/cline-core/telemetry.d.ts +10 -0
  19. package/dist/cline-core/types.d.ts +221 -0
  20. package/dist/cron/events/cron-event-ingress.d.ts +37 -0
  21. package/dist/cron/reports/cron-report-writer.d.ts +40 -0
  22. package/dist/cron/runner/cron-materializer.d.ts +35 -0
  23. package/dist/cron/runner/cron-runner.d.ts +45 -0
  24. package/dist/cron/runner/resource-limiter.d.ts +8 -0
  25. package/dist/cron/schedule/scheduler.d.ts +12 -0
  26. package/dist/cron/service/cron-service.d.ts +56 -0
  27. package/dist/cron/service/schedule-command-service.d.ts +9 -0
  28. package/dist/cron/service/schedule-service.d.ts +98 -0
  29. package/dist/cron/specs/cron-reconciler.d.ts +61 -0
  30. package/dist/cron/specs/cron-spec-parser.d.ts +26 -0
  31. package/dist/cron/specs/cron-watcher.d.ts +22 -0
  32. package/dist/cron/store/cron-schema.d.ts +2 -0
  33. package/dist/cron/store/sqlite-cron-store.d.ts +240 -0
  34. package/dist/extensions/config/index.d.ts +7 -0
  35. package/dist/extensions/config/runtime-commands.d.ts +11 -0
  36. package/dist/extensions/config/skill-frontmatter-toggle.d.ts +11 -0
  37. package/dist/extensions/config/unified-config-file-watcher.d.ts +77 -0
  38. package/dist/extensions/config/user-instruction-config-loader.d.ts +64 -0
  39. package/dist/extensions/config/user-instruction-plugin.d.ts +25 -0
  40. package/dist/extensions/config/user-instruction-service.d.ts +23 -0
  41. package/dist/extensions/context/agentic-compaction.d.ts +12 -0
  42. package/dist/extensions/context/basic-compaction.d.ts +8 -0
  43. package/dist/extensions/context/compaction-shared.d.ts +60 -0
  44. package/dist/extensions/context/compaction.d.ts +24 -0
  45. package/dist/extensions/index.d.ts +5 -0
  46. package/dist/extensions/mcp/client.d.ts +2 -0
  47. package/dist/extensions/mcp/config-loader.d.ts +15 -0
  48. package/dist/extensions/mcp/index.d.ts +8 -0
  49. package/dist/extensions/mcp/manager.d.ts +23 -0
  50. package/dist/extensions/mcp/name-transform.d.ts +2 -0
  51. package/dist/extensions/mcp/policies.d.ts +14 -0
  52. package/dist/extensions/mcp/tools.d.ts +3 -0
  53. package/dist/extensions/mcp/types.d.ts +94 -0
  54. package/dist/extensions/plugin/plugin-config-loader.d.ts +40 -0
  55. package/dist/extensions/plugin/plugin-load-report.d.ts +18 -0
  56. package/dist/extensions/plugin/plugin-loader.d.ts +22 -0
  57. package/dist/extensions/plugin/plugin-module-import.d.ts +4 -0
  58. package/dist/extensions/plugin/plugin-sandbox.d.ts +36 -0
  59. package/dist/extensions/plugin/plugin-targeting.d.ts +6 -0
  60. package/dist/extensions/plugin-sandbox-bootstrap.js +1 -0
  61. package/dist/extensions/tools/constants.d.ts +24 -0
  62. package/dist/extensions/tools/definitions.d.ts +102 -0
  63. package/dist/extensions/tools/executors/apply-patch-parser.d.ts +68 -0
  64. package/dist/extensions/tools/executors/apply-patch.d.ts +28 -0
  65. package/dist/extensions/tools/executors/bash.d.ts +49 -0
  66. package/dist/extensions/tools/executors/editor.d.ts +31 -0
  67. package/dist/extensions/tools/executors/file-read.d.ts +40 -0
  68. package/dist/extensions/tools/executors/index.d.ts +50 -0
  69. package/dist/extensions/tools/executors/search.d.ts +50 -0
  70. package/dist/extensions/tools/executors/web-fetch.d.ts +58 -0
  71. package/dist/extensions/tools/helpers.d.ts +15 -0
  72. package/dist/extensions/tools/index.d.ts +59 -0
  73. package/dist/extensions/tools/model-tool-routing.d.ts +33 -0
  74. package/dist/extensions/tools/presets.d.ts +132 -0
  75. package/dist/extensions/tools/runtime.d.ts +24 -0
  76. package/dist/extensions/tools/schemas.d.ts +241 -0
  77. package/dist/extensions/tools/team/delegated-agent.d.ts +43 -0
  78. package/dist/extensions/tools/team/index.d.ts +2 -0
  79. package/dist/extensions/tools/team/multi-agent.d.ts +230 -0
  80. package/dist/extensions/tools/team/projections.d.ts +8 -0
  81. package/dist/extensions/tools/team/runtime.d.ts +4 -0
  82. package/dist/extensions/tools/team/spawn-agent-tool.d.ts +83 -0
  83. package/dist/extensions/tools/team/subagent-prompts.d.ts +3 -0
  84. package/dist/extensions/tools/team/team-tools.d.ts +35 -0
  85. package/dist/extensions/tools/types.d.ts +254 -0
  86. package/dist/hooks/checkpoint-hooks.d.ts +45 -0
  87. package/dist/hooks/hook-extension.d.ts +2 -0
  88. package/dist/hooks/hook-file-config.d.ts +24 -0
  89. package/dist/hooks/hook-file-hooks.d.ts +21 -0
  90. package/dist/hooks/index.d.ts +5 -0
  91. package/dist/hooks/subprocess-runner.d.ts +21 -0
  92. package/dist/hooks/subprocess.d.ts +68 -0
  93. package/dist/hub/client/connect.d.ts +14 -0
  94. package/dist/hub/client/index.d.ts +88 -0
  95. package/dist/hub/client/session-client.d.ts +118 -0
  96. package/dist/hub/client/ui-client.d.ts +45 -0
  97. package/dist/hub/daemon/entry.d.ts +1 -0
  98. package/dist/hub/daemon/entry.js +720 -0
  99. package/dist/hub/daemon/index.d.ts +8 -0
  100. package/dist/hub/daemon/runtime-handlers.d.ts +12 -0
  101. package/dist/hub/daemon/start-shared-server.d.ts +18 -0
  102. package/dist/hub/discovery/defaults.d.ts +16 -0
  103. package/dist/hub/discovery/index.d.ts +30 -0
  104. package/dist/hub/discovery/workspace.d.ts +3 -0
  105. package/dist/hub/index.d.ts +32 -0
  106. package/dist/hub/index.js +717 -0
  107. package/dist/hub/runtime-host/hub-runtime-host.d.ts +73 -0
  108. package/dist/hub/runtime-host/remote-runtime-host.d.ts +9 -0
  109. package/dist/hub/server/browser-websocket.d.ts +17 -0
  110. package/dist/hub/server/command-transport.d.ts +7 -0
  111. package/dist/hub/server/handlers/approval-handlers.d.ts +17 -0
  112. package/dist/hub/server/handlers/capability-handlers.d.ts +12 -0
  113. package/dist/hub/server/handlers/client-handlers.d.ts +6 -0
  114. package/dist/hub/server/handlers/context.d.ts +56 -0
  115. package/dist/hub/server/handlers/run-handlers.d.ts +5 -0
  116. package/dist/hub/server/handlers/session-event-projector.d.ts +7 -0
  117. package/dist/hub/server/handlers/session-handlers.d.ts +20 -0
  118. package/dist/hub/server/hub-client-contributions.d.ts +19 -0
  119. package/dist/hub/server/hub-notifications.d.ts +7 -0
  120. package/dist/hub/server/hub-schedule-events.d.ts +2 -0
  121. package/dist/hub/server/hub-server-logging.d.ts +2 -0
  122. package/dist/hub/server/hub-server-options.d.ts +55 -0
  123. package/dist/hub/server/hub-server-transport.d.ts +34 -0
  124. package/dist/hub/server/hub-session-records.d.ts +8 -0
  125. package/dist/hub/server/hub-websocket-server.d.ts +6 -0
  126. package/dist/hub/server/index.d.ts +4 -0
  127. package/dist/hub/server/native-transport.d.ts +16 -0
  128. package/dist/index.d.ts +102 -0
  129. package/dist/index.js +715 -0
  130. package/dist/runtime/capabilities/index.d.ts +2 -0
  131. package/dist/runtime/capabilities/normalize-runtime-capabilities.d.ts +2 -0
  132. package/dist/runtime/capabilities/runtime-capabilities.d.ts +6 -0
  133. package/dist/runtime/config/agent-message-codec.d.ts +6 -0
  134. package/dist/runtime/config/agent-runtime-config-builder.d.ts +87 -0
  135. package/dist/runtime/host/history.d.ts +18 -0
  136. package/dist/runtime/host/host.d.ts +7 -0
  137. package/dist/runtime/host/local/agent-event-bridge.d.ts +29 -0
  138. package/dist/runtime/host/local/session-record.d.ts +6 -0
  139. package/dist/runtime/host/local/session-service-invoker.d.ts +4 -0
  140. package/dist/runtime/host/local/spawn-tool.d.ts +15 -0
  141. package/dist/runtime/host/local/user-files.d.ts +1 -0
  142. package/dist/runtime/host/local-runtime-host.d.ts +119 -0
  143. package/dist/runtime/host/runtime-host-support.d.ts +20 -0
  144. package/dist/runtime/host/runtime-host.d.ts +163 -0
  145. package/dist/runtime/orchestration/runtime-builder.d.ts +6 -0
  146. package/dist/runtime/orchestration/runtime-event-adapter.d.ts +101 -0
  147. package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +30 -0
  148. package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +218 -0
  149. package/dist/runtime/orchestration/session-runtime.d.ts +58 -0
  150. package/dist/runtime/orchestration/user-input-builder.d.ts +15 -0
  151. package/dist/runtime/safety/loop-detection.d.ts +58 -0
  152. package/dist/runtime/safety/mistake-tracker.d.ts +68 -0
  153. package/dist/runtime/safety/rules.d.ts +6 -0
  154. package/dist/runtime/tools/subprocess-sandbox.d.ts +43 -0
  155. package/dist/runtime/tools/tool-approval.d.ts +9 -0
  156. package/dist/runtime/turn-queue/pending-prompt-service.d.ts +64 -0
  157. package/dist/services/agent-events.d.ts +33 -0
  158. package/dist/services/config.d.ts +2 -0
  159. package/dist/services/global-settings.d.ts +34 -0
  160. package/dist/services/llms/cline-recommended-models.d.ts +19 -0
  161. package/dist/services/llms/configured-provider-registry.d.ts +27 -0
  162. package/dist/services/llms/handler-factory.d.ts +3 -0
  163. package/dist/services/llms/provider-defaults.d.ts +28 -0
  164. package/dist/services/llms/provider-settings.d.ts +247 -0
  165. package/dist/services/llms/runtime-config.d.ts +3 -0
  166. package/dist/services/llms/runtime-registry.d.ts +19 -0
  167. package/dist/services/llms/runtime-types.d.ts +84 -0
  168. package/dist/services/local-runtime-bootstrap.d.ts +45 -0
  169. package/dist/services/plugin-tools.d.ts +15 -0
  170. package/dist/services/providers/local-provider-registry.d.ts +218 -0
  171. package/dist/services/providers/local-provider-service.d.ts +99 -0
  172. package/dist/services/providers/model-source.d.ts +3 -0
  173. package/dist/services/session-artifacts.d.ts +17 -0
  174. package/dist/services/session-data.d.ts +51 -0
  175. package/dist/services/session-telemetry.d.ts +15 -0
  176. package/dist/services/storage/file-team-store.d.ts +28 -0
  177. package/dist/services/storage/provider-settings-legacy-migration.d.ts +38 -0
  178. package/dist/services/storage/provider-settings-manager.d.ts +23 -0
  179. package/dist/services/storage/sqlite-session-store.d.ts +30 -0
  180. package/dist/services/storage/sqlite-team-store.d.ts +34 -0
  181. package/dist/services/storage/team-store.d.ts +15 -0
  182. package/dist/services/telemetry/ITelemetryAdapter.d.ts +54 -0
  183. package/dist/services/telemetry/OpenTelemetryAdapter.d.ts +43 -0
  184. package/dist/services/telemetry/OpenTelemetryProvider.d.ts +83 -0
  185. package/dist/services/telemetry/TelemetryLoggerSink.d.ts +27 -0
  186. package/dist/services/telemetry/TelemetryService.d.ts +34 -0
  187. package/dist/services/telemetry/core-events.d.ts +198 -0
  188. package/dist/services/telemetry/distinct-id.d.ts +1 -0
  189. package/dist/services/telemetry/index.d.ts +3 -0
  190. package/dist/services/telemetry/index.js +1 -0
  191. package/dist/services/usage.d.ts +18 -0
  192. package/dist/services/workspace/file-indexer.d.ts +5 -0
  193. package/dist/services/workspace/index.d.ts +4 -0
  194. package/dist/services/workspace/mention-enricher.d.ts +13 -0
  195. package/dist/services/workspace/workspace-manager.d.ts +27 -0
  196. package/dist/services/workspace/workspace-manifest.d.ts +31 -0
  197. package/dist/services/workspace/workspace-telemetry.d.ts +18 -0
  198. package/dist/session/checkpoint-restore.d.ts +20 -0
  199. package/dist/session/models/session-graph.d.ts +15 -0
  200. package/dist/session/models/session-manifest.d.ts +29 -0
  201. package/dist/session/models/session-row.d.ts +92 -0
  202. package/dist/session/services/file-session-service.d.ts +8 -0
  203. package/dist/session/services/message-builder.d.ts +66 -0
  204. package/dist/session/services/persistence-service.d.ts +58 -0
  205. package/dist/session/services/session-service.d.ts +13 -0
  206. package/dist/session/session-snapshot.d.ts +57 -0
  207. package/dist/session/session-versioning-service.d.ts +48 -0
  208. package/dist/session/stores/conversation-store.d.ts +29 -0
  209. package/dist/session/stores/session-manifest-store.d.ts +21 -0
  210. package/dist/session/stores/team-persistence-store.d.ts +23 -0
  211. package/dist/session/team/index.d.ts +2 -0
  212. package/dist/session/team/team-child-session-manager.d.ts +35 -0
  213. package/dist/session/team/team-session-coordinator.d.ts +13 -0
  214. package/dist/settings/index.d.ts +2 -0
  215. package/dist/settings/settings-service.d.ts +6 -0
  216. package/dist/settings/types.d.ts +42 -0
  217. package/dist/types/chat-schema.d.ts +161 -0
  218. package/dist/types/common.d.ts +19 -0
  219. package/dist/types/config.d.ts +167 -0
  220. package/dist/types/events.d.ts +89 -0
  221. package/dist/types/provider-settings.d.ts +19 -0
  222. package/dist/types/session.d.ts +116 -0
  223. package/dist/types/sessions.d.ts +28 -0
  224. package/dist/types/storage.d.ts +36 -0
  225. package/dist/types.d.ts +32 -0
  226. package/dist/version.d.ts +1 -0
  227. package/package.json +83 -0
@@ -0,0 +1,720 @@
1
+ import{createRequire as XY}from"node:module";var{defineProperty:jW,getOwnPropertyNames:ZY}=Object;var B3=Object.prototype.hasOwnProperty;function A3(f){return this[f]}var O=(f,$,J)=>{var W=ZY($);for(let H of W)if(!B3.call(f,H)&&H!=="default")jW(f,H,{get:A3.bind($,H),enumerable:!0});if(J){for(let H of W)if(!B3.call(J,H)&&H!=="default")jW(J,H,{get:A3.bind($,H),enumerable:!0});return J}};var jY=(f)=>f;function PY(f,$){this[f]=jY.bind(null,$)}var N=(f,$)=>{for(var J in $)jW(f,J,{get:$[J],enumerable:!0,configurable:!0,set:PY.bind($,J)})};var $1=(f,$)=>()=>(f&&($=f(f=0)),$);var R3=XY(import.meta.url);var G7={};N(G7,{normalizeUserMessage:()=>oB,buildInitialUserContent:()=>sB});async function sB(f,$,J,W){let H=eB($),Q=await $A(J,W);if(H.length===0&&!Q)return f;let Z=[{type:"text",text:f},...H];if(Q)Z.push(...Q);return Z}function oB(f){if(f==null)return"";if(typeof f==="string")return f;let $=f.content;if(typeof $==="string")return $;if(!Array.isArray($))return"";let J=[];for(let W of $)if(W&&typeof W==="object"&&W.type==="text"){let H=W.text;if(typeof H==="string")J.push(H)}return J.join(`
2
+ `)}function eB(f){if(!f||f.length===0)return[];let $=[];for(let J of f){let W=fA(J);if(W)$.push(W)}return $}function fA(f){let $=f.trim();if(!$)return;let J=$.match(/^data:([^;,]+);base64,(.+)$/);if(J){let W=J[1],H=J[2];if(!W||!H)return;return{type:"image",mediaType:W,data:H}}return{type:"image",mediaType:"image/png",data:$}}async function $A(f,$){if(!f||f.length===0)return;let J=$??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all(f.map(async(H)=>{let Q=H.replace(/\\/g,"/");try{let Z=await J(H);return{type:"file",path:Q,content:Z}}catch(Z){let j=Z instanceof Error?Z.message:String(Z);return{type:"file",path:Q,content:`Error fetching content: ${j}`}}}));if(W.length===0)return;return W}function l(f,$,J){f?.capture({event:$,properties:J})}function d4(f){if(!f)return;return f.substring(0,500)}function lA(f){if(typeof f==="string")return"Error";return f.name?.trim()||f.constructor?.name||"Error"}function pA(f){return typeof f==="string"?f:f.message}function JQ(f,$){return f.some((J)=>$.has(J.trim().toLowerCase()))}function WQ(f){l(f,g.CLIENT.EXTENSION_ACTIVATED)}function r4(f,$){let J=[...$.vcs_types],W={root_count:$.root_count,vcs_types:J,is_multi_root:$.root_count>1,has_git:JQ(J,new Set(["git"])),has_mercurial:JQ(J,new Set(["mercurial","hg"]))};if($.init_duration_ms!==void 0)W.init_duration_ms=$.init_duration_ms;if($.feature_flag_enabled!==void 0)W.feature_flag_enabled=$.feature_flag_enabled;if($.is_remote_workspace!==void 0)W.is_remote_workspace=$.is_remote_workspace;l(f,g.WORKSPACE.INITIALIZED,W)}function l4(f,$,J){l(f,g.WORKSPACE.INIT_ERROR,{error_type:lA($),error_message:d4(pA($)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function HQ(f,$){l(f,g.WORKSPACE.PATH_RESOLVED,{...$})}function R0(f,$){l(f,g.USER.AUTH_STARTED,{provider:$})}function F0(f,$){l(f,g.USER.AUTH_SUCCEEDED,{provider:$})}function y0(f,$,J){l(f,g.USER.AUTH_FAILED,{provider:$,errorMessage:d4(J)})}function g0(f,$,J){l(f,g.USER.AUTH_LOGGED_OUT,{provider:$,reason:J})}function QQ(f,$){f?.captureRequired(g.USER.TELEMETRY_OPT_OUT,$)}function K0(f,$){let J=$.id?.trim();if(J)f?.setDistinctId(J);f?.updateCommonProperties({account_id:$.id,account_email:$.email,provider:$.provider,organization_id:$.organizationId,organization_name:$.organizationName,member_id:$.memberId})}function p4(f,$){l(f,g.TASK.CREATED,$)}function i4(f,$){l(f,g.TASK.RESTARTED,$)}function p2(f,$){l(f,g.TASK.COMPLETED,$)}function F1(f,$){l(f,g.TASK.CONVERSATION_TURN,{...$,timestamp:new Date().toISOString()})}function n4(f,$){l(f,g.TASK.TOKEN_USAGE,$)}function a4(f,$,J){l(f,g.TASK.MODE_SWITCH,{ulid:$,mode:J})}function t4(f,$){l(f,g.TASK.TOOL_USED,$)}function s4(f,$){l(f,g.TASK.SKILL_USED,$)}function o4(f,$){l(f,g.TASK.DIFF_EDIT_FAILED,$)}function i2(f,$){l(f,g.TASK.PROVIDER_API_ERROR,{...$,errorMessage:d4($.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function e4(f,$,J){l(f,g.TASK.MENTION_USED,{mentionType:$,contentLength:J,timestamp:new Date().toISOString()})}function f6(f,$,J,W){l(f,g.TASK.MENTION_FAILED,{mentionType:$,errorType:J,errorMessage:d4(W),timestamp:new Date().toISOString()})}function $6(f,$,J,W,H){l(f,g.TASK.MENTION_SEARCH_RESULTS,{queryLength:$.length,resultCount:J,searchType:W,isEmpty:H,timestamp:new Date().toISOString()})}function v0(f,$){l(f,g.TASK.AGENT_CREATED,{...$,timestamp:new Date().toISOString()})}function J6(f,$){l(f,g.TASK.AGENT_TEAM_CREATED,{...$,timestamp:new Date().toISOString()})}function n2(f,$){l(f,$.event==="ended"?g.TASK.SUBAGENT_COMPLETED:g.TASK.SUBAGENT_STARTED,{...$,timestamp:new Date().toISOString()})}function W6(f,$,J,W){l(f,g.HOOKS.DISCOVERY_COMPLETED,{hookName:$,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}var g;var Gf=$1(()=>{g={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"}}});import{mkdirSync as sA,readFileSync as oA,writeFileSync as eA}from"node:fs";import{dirname as fR}from"node:path";import{resolveGlobalSettingsPath as VQ}from"@cline/shared/storage";import{z as t2}from"zod";function XQ(){return s2.parse({})}function of(){let f=VQ(),$;try{$=JSON.parse(oA(f,"utf8"))}catch{return XQ()}let J=s2.safeParse($);return J.success?J.data:XQ()}function L$(f,$={}){let J=VQ(),W=of();sA(fR(J),{recursive:!0});let H=s2.parse(f);if(!W.telemetryOptOut&&H.telemetryOptOut)QQ($.telemetry);eA(J,`${JSON.stringify(H,null,2)}
3
+ `,"utf8")}function Z6(){return of().telemetryOptOut}function YQ(f,$={}){L$({...of(),telemetryOptOut:f},$)}function rf(f){return new Set(f??of().disabledTools??[])}function o2(f){return new Set(f??of().disabledPlugins??[])}function BQ(f){return rf().has(f)}function j6(f){let $=rf(),J=of();if($.has(f))return $.delete(f),L$({...J,disabledTools:[...$]}),!1;return $.add(f),L$({...J,disabledTools:[...$]}),!0}function tW(f,$){let J=[...new Set(f.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=of(),H=rf(W.disabledTools);for(let Q of J)if($)H.add(Q);else H.delete(Q);L$({...W,disabledTools:[...H]})}function AQ(f,$){return tW([f],$),$}function RQ(f){return o2().has(f)}function FQ(f,$){let J=f.trim();if(!J)return;let W=of(),H=o2(W.disabledPlugins);if($)H.add(J);else H.delete(J);L$({...W,disabledPlugins:[...H]})}function P6(f,$){let J=o2($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W))}function z$(f,$){let J=rf($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W.name))}function X6(f,$){if(!f||f.length===0)return f;let J=rf($);if(J.size===0)return f;return f.map((W)=>{if(!W.setup)return W;return{...W,setup:(H,Q)=>W.setup?.({...H,registerTool:(Z)=>{if(!J.has(Z.name))H.registerTool(Z)}},Q)}})}var PQ,s2;var G0=$1(()=>{Gf();PQ=t2.preprocess((f)=>Array.isArray(f)?f.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,t2.array(t2.string()).optional()).transform((f)=>{if(!f)return;let $=[...new Set(f)].sort((J,W)=>J.localeCompare(W));return $.length>0?$:void 0}),s2=t2.object({telemetryOptOut:t2.boolean().default(!1).catch(!1),disabledTools:PQ.optional(),disabledPlugins:PQ.optional()}).strip().transform((f)=>{let $={telemetryOptOut:f.telemetryOptOut};if(f.disabledTools?.length)$.disabledTools=f.disabledTools;if(f.disabledPlugins?.length)$.disabledPlugins=f.disabledPlugins;return $})});import{existsSync as GT,mkdirSync as TT,readFileSync as hT,writeFileSync as DT}from"node:fs";import{resolve as MT}from"node:path";import{resolveSessionDataDir as _T}from"@cline/shared/storage";import{nanoid as LT}from"nanoid";import*as zT from"node-machine-id";function c$(f){let $=f?.trim();if($)return $;let J=qT();if(J)return J;return bT()}function NT(){let f=zT;return f.machineIdSync??f.default?.machineIdSync}function qT(){try{let f=NT();if(!f)return;return f().trim()||void 0}catch{return}}function bT(){let f=_T(),$=MT(f,OT);try{if(GT($)){let W=hT($,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${LT()}`;try{TT(f,{recursive:!0}),DT($,J,"utf8")}catch{}return J}var OT="machine-id";var _J=()=>{};class A4{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(f){this.name=f.name??"OpenTelemetryAdapter",this.metadata={...f.metadata},this.meterProvider=f.meterProvider,this.loggerProvider=f.loggerProvider,this.meter=f.meterProvider?.getMeter("cline")??null,this.logger=f.loggerProvider?.getLogger("cline")??null,this.enabled=f.enabled??!0,this.distinctId=f.distinctId,this.commonProperties=f.commonProperties?{...f.commonProperties}:{}}emit(f,$){if(!this.isEnabled())return;this.emitLog(f,$,!1)}emitRequired(f,$){this.emitLog(f,$,!0)}recordCounter(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.counters.get(f);if(!Q)Q=this.meter.createCounter(f,W?{description:W}:void 0),this.counters.set(f,Q);Q.add($,this.flattenProperties(this.buildAttributes(J)))}recordHistogram(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.histograms.get(f);if(!Q)Q=this.meter.createHistogram(f,W?{description:W}:void 0),this.histograms.set(f,Q);Q.record($,this.flattenProperties(this.buildAttributes(J)))}recordGauge(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.buildAttributes(J),Z=JSON.stringify(Q),j=this.gaugeValues.get(f);if($===null){if(j){if(j.delete(Z),j.size===0)this.gaugeValues.delete(f),this.gauges.delete(f)}return}let P=j;if(!P)P=new Map,this.gaugeValues.set(f,P);if(!this.gauges.has(f)){let X=this.meter.createObservableGauge(f,W?{description:W}:void 0);X.addCallback((V)=>{for(let Y of this.snapshotGaugeSeries(f))V.observe(Y.value,this.flattenProperties(Y.attributes))}),this.gauges.set(f,X)}P.set(Z,{value:$,attributes:Q})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(f){this.distinctId=f}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(f,$,J){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes($,J));this.logger.emit({severityText:"INFO",body:f,attributes:W})}buildAttributes(f,$=!1){return{...this.commonProperties,...this.metadata,...f,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(f){let $=this.gaugeValues.get(f);if(!$)return[];return Array.from($.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties(f,$="",J=new WeakSet,W=0){if(!f)return{};let H={},Q=100,Z=10;for(let[j,P]of Object.entries(f)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let X=$?`${$}.${j}`:j;if(P===null||P===void 0){H[X]=String(P);continue}if(Array.isArray(P)){let V=P.length>Q?P.slice(0,Q):P;try{H[X]=JSON.stringify(V)}catch{H[X]="[UnserializableArray]"}if(P.length>Q)H[`${X}_truncated`]=!0,H[`${X}_original_length`]=P.length;continue}if(typeof P==="object"){if(P instanceof Date){H[X]=P.toISOString();continue}if(P instanceof Error){H[X]=P.message;continue}if(J.has(P)){H[X]="[Circular]";continue}if(W>=Z){H[X]="[MaxDepthExceeded]";continue}J.add(P),Object.assign(H,this.flattenProperties(P,X,J,W+1));continue}if(th(P)){H[X]=P;continue}try{H[X]=JSON.stringify(P)}catch{H[X]=String(P)}}return H}}function th(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class R4{name;logger;enabled;constructor(f={}){this.name=f.name??"TelemetryLoggerSink",this.logger=f.logger,this.enabled=f.enabled??!0}emit(f,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:f,properties:$})}emitRequired(f,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:f,properties:$})}recordCounter(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:f,value:$,attributes:J,description:W,required:H===!0})}recordHistogram(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:f,value:$,attributes:J,description:W,required:H===!0})}recordGauge(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:f,value:$,attributes:J,description:W,required:H===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class Q2{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new R4({logger:f.logger}));this.metadata={...f.metadata??{}},this.distinctId=f.distinctId,this.commonProperties={...f.commonProperties??{}}}addAdapter(f){this.adapters.push(f)}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return this.adapters.some((f)=>f.isEnabled())}capture(f){let $=this.buildAttributes(f.properties);for(let J of this.adapters)J.emit(f.event,$)}captureRequired(f,$){let J=this.buildAttributes($);for(let W of this.adapters)W.emitRequired(f,J)}recordCounter(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordCounter(f,$,Q,W,H)}recordHistogram(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordHistogram(f,$,Q,W,H)}recordGauge(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordGauge(f,$,Q,W,H)}async flush(){await Promise.all(this.adapters.map((f)=>f.flush()))}async dispose(){await Promise.all(this.adapters.map((f)=>f.dispose()))}buildAttributes(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var $9=()=>{};import{metrics as sh,trace as oh}from"@opentelemetry/api";import{logs as eh}from"@opentelemetry/api-logs";import{OTLPLogExporter as fD}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as $D}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as JD}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as WD}from"@opentelemetry/resources";import{BatchLogRecordProcessor as HD,ConsoleLogRecordExporter as QD,LoggerProvider as ZD}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as jD,MeterProvider as PD,PeriodicExportingMetricReader as $X}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as XD,ConsoleSpanExporter as VD,SimpleSpanProcessor as YD}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as BD}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as AD,ATTR_SERVICE_VERSION as RD}from"@opentelemetry/semantic-conventions";class JX{distinctId;metadata;commonProperties;constructor(f={}){this.distinctId=f.distinctId,this.metadata={...f.metadata??{}},this.commonProperties={...f.commonProperties??{}}}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return!1}capture(f){this.resolveProperties(f.properties)}captureRequired(f,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class Z2{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=WD({[AD]:f.serviceName??"cline",...f.serviceVersion?{[RD]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)sh.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)eh.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return oh.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new A4({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new Q2({...f,adapters:[$],distinctId:c$(f.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(f){let $=J9(this.options.metricsExporter);if($.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(J*0.8)),H=$.map((Q)=>KD(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:W})).filter((Q)=>Q!==null);if(H.length===0)return null;return new PD({resource:f,readers:H})}createTracerProvider(f){let $=J9(this.options.tracesExporter);if($.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,H=[];for(let Q of $){let Z=yD(Q,{endpoint:J,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(Z)H.push(Z)}if(H.length===0)return null;return new BD({resource:f,spanProcessors:H})}createLoggerProvider(f){let $=J9(this.options.logsExporter);if($.length===0)return null;let J=$.map((W)=>{let H=FD(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!H)return null;return new HD(H,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(J.length===0)return null;return new ZD({resource:f,processors:J})}}function F4(f){let $=new Z2(f),J=$.createTelemetryService(f);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:f.enabled??!0,logsExporter:Array.isArray(f.logsExporter)?f.logsExporter.join(","):f.logsExporter,metricsExporter:Array.isArray(f.metricsExporter)?f.metricsExporter.join(","):f.metricsExporter,tracesExporter:Array.isArray(f.tracesExporter)?f.tracesExporter.join(","):f.tracesExporter,otlpProtocol:f.otlpProtocol,hasOtlpEndpoint:Boolean(f.otlpEndpoint),serviceName:f.serviceName,serviceVersion:f.serviceVersion}),{provider:$,telemetry:J}}function i$(f){if(Z6())return{telemetry:new JX(f)};if(f.enabled!==!0)return{telemetry:new Q2({...f,distinctId:c$(f.distinctId)})};return F4(f)}function j2(f){let{telemetry:$,provider:J}=i$(f);return{telemetry:$,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),J?.dispose()])}}}function J9(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function FD(f,$){if(f==="console")return new QD;if(!$.endpoint)return null;let J=W9($.endpoint,"/v1/logs");return new fD({url:J,headers:$.headers})}function yD(f,$){if(f==="console")return new YD(new VD);if(!$.endpoint)return null;let J=W9($.endpoint,"/v1/traces");return new XD(new JD({url:J,headers:$.headers}))}function KD(f,$){if(f==="console")return new $X({exporter:new jD,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=W9($.endpoint,"/v1/metrics");return new $X({exporter:new $D({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function W9(f,$){let J=new URL(f),W=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=W.endsWith($)?W:`${W}${$}`,J.toString()}var SJ=$1(()=>{G0();_J();$9()});var pV={};N(pV,{createOpenTelemetryTelemetryService:()=>F4,createConfiguredTelemetryService:()=>i$,createConfiguredTelemetryHandle:()=>j2,OpenTelemetryProvider:()=>Z2,OpenTelemetryAdapter:()=>A4});var iV=$1(()=>{SJ()});import{initVcr as Qz}from"@cline/shared";import{normalizeProviderId as Jz}from"@cline/llms";var aV={};N(aV,{LocalRuntimeHost:()=>Z0});import{homedir as aL}from"node:os";import{isAbsolute as tL,join as X3,resolve as sL}from"node:path";import{createSessionId as oL,isLikelyAuthError as eL,normalizeUserInput as fz}from"@cline/shared";import{setHomeDirIfUnset as $z}from"@cline/shared/storage";var m3={};N(m3,{createContextCompactionPrepareTurn:()=>h2});import{createHandler as FY}from"@cline/llms";var F3=200000,y3=0.95;var PW=20000;var K3=8;function VY(f){return Math.max(1,Math.ceil(f.length/4))}function V$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
4
+ ...[truncated ${f.length-$} chars]`}function YY(f){if(typeof f==="string")return V$(f,2000);return f.map(($)=>{switch($.type){case"text":return $.text;case"file":return`<file path="${$.path}">
5
+ ${V$($.content,2000)}
6
+ </file>`;case"image":return`[image:${$.mediaType}]`;default:return""}}).join(`
7
+ `)}function BY(f){return Object.entries(f).map(([$,J])=>`${$}=${JSON.stringify(J)}`).join(", ")}function U3(f){if(typeof f.content==="string")return`[${f.role==="user"?"User":"Bot"}]: ${f.content}`;let $=[];for(let J of f.content)switch(J.type){case"text":$.push(`[${f.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":$.push(`[Bot thinking]: ${V$(J.thinking,2000)}`);break;case"redacted_thinking":$.push("[Bot thinking]: [redacted]");break;case"tool_use":$.push(`[Bot tool calls]: ${J.name}(${BY(J.input)})`);break;case"tool_result":$.push(`[Tool result]: ${YY(J.content)}`);break;case"file":$.push(`[${f.role==="user"?"User":"Bot"} file ${J.path}]: ${V$(J.content,2000)}`);break;case"image":$.push(`[${f.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return $.join(`
8
+ `)}function G3(f){return f.map(U3).join(`
9
+
10
+ `).trim()}function T3(){let f=new WeakMap;return($)=>{let J=$,W=f.get(J);if(typeof W==="number")return W;let H=VY(U3($));return f.set(J,H),H}}function G2(f){return f.metadata?.kind==="compaction_summary"}function XW(f){if(!G2(f))return;let $=f.metadata;if(!$)return;let J=$.details;return{kind:"compaction_summary",summary:String($.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number($.tokensBefore??0),generatedAt:Number($.generatedAt??0)}}function AY(f){if(f.role!=="user"||!Array.isArray(f.content))return!1;return f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}function h3(f){return f.role==="user"&&!AY(f)&&!G2(f)}function D3(f){for(let $=0;$<f.length;$+=1)if(h3(f[$]))return $;return-1}function VW(f){for(let $=f.length-1;$>=0;$-=1)if(h3(f[$]))return $;return 0}function M3(f){for(let $=f.length-1;$>=0;$-=1)if(f[$].role==="assistant")return $;return-1}function _3(f){for(let $=f.length-1;$>=0;$-=1)if(G2(f[$]))return $;return-1}function L3(f,$,J){let W=VW(f);if(W<=0)return 0;let H=0,Q=f.length;for(let Z=f.length-1;Z>=0;Z-=1)if(H+=J(f[Z]),Q=Z,H>=$)break;if(Q<=0)return 0;return Math.min(Q,W)}function U2(f){if(typeof f==="string"&&f.trim().length>0)return[f];if(Array.isArray(f))return f.flatMap(($)=>U2($));if(f&&typeof f==="object"){let $=f,J=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...U2($[W]));if(Array.isArray($.files)){for(let W of $.files)if(W&&typeof W==="object")J.push(...U2(W.path))}if(Array.isArray($.file_paths))J.push(...U2($.file_paths));return J}return[]}function K2(f,$){let J=new Set(f);for(let W of $){let H=W.trim();if(!H)continue;J.add(H)}return[...J].sort((W,H)=>W.localeCompare(H))}function z3(f){let $=[],J=[];for(let W of f){let H=XW(W);if(H){$=K2($,H.details.readFiles),J=K2(J,H.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){$=K2($,[Q.path]);continue}if(Q.type!=="tool_use")continue;let Z=U2(Q.input);if(Q.name==="read_files"){$=K2($,Z);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=K2(J,Z)}}return{readFiles:$,modifiedFiles:J}}function RY(f){let $=f.readFiles.length>0?f.readFiles.map((W)=>`- ${W}`).join(`
11
+ `):"- none",J=f.modifiedFiles.length>0?f.modifiedFiles.map((W)=>`- ${W}`).join(`
12
+ `):"- none";return`## Files
13
+ Read:
14
+ ${$}
15
+ Modified:
16
+ ${J}`}function O3(f,$){if(/^## Files$/im.test(f))return f.trim();return`${f.trim()}
17
+
18
+ ${RY($)}`.trim()}function N3(f){let $=[`Summarize this session for continuation. Be concise and factual.
19
+
20
+ ## Goal
21
+ One sentence: what is being built or fixed.
22
+
23
+ ## State
24
+ - Done: completed steps
25
+ - In Progress: current work
26
+ - Blocked: blockers or open questions
27
+
28
+ ## Highlights
29
+ Key technical choices or notable findings (omit if none).
30
+
31
+ ## Next
32
+ Immediate next steps.
33
+
34
+ ## Files
35
+ Read: ${f.fileOps.readFiles.join(", ")||"none"}
36
+ Edited: ${f.fileOps.modifiedFiles.join(", ")||"none"}`];if(f.previousSummary?.trim())$.push(`Previous summary:
37
+ ${f.previousSummary.trim()}`);return $.push(`Conversation:
38
+ ${f.conversationText||"(empty)"}`),$.join(`
39
+
40
+ `)}function q3(f){let $=f.summarizer;if(!$)return{...f.activeProviderConfig,maxOutputTokens:1024,thinking:!1};let J=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0;return{...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:$.knownModels??J?.knownModels,maxOutputTokens:$.maxOutputTokens??1024,thinking:!1}}function b3(f){return{role:"user",content:`Context summary:
41
+
42
+ ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function yY(f){let $=FY(f.providerConfig),J="";for await(let W of $.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:f.request}])){if(W.type==="text"){J+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return f.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:f.providerConfig.modelId,providerId:f.providerConfig.providerId}),J.trim()}async function w3(f){let $=f.context.messages;if($.length<2)return;let J=L3($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let W=$.slice(0,J),H=_3(W),Q=H>=0?XW(W[H])?.summary:void 0,Z=H>=0?W.slice(H+1):W;if(Z.length===0)return;let j=z3(W),P=G3(Z),X=await yY({providerConfig:q3({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:N3({previousSummary:Q,conversationText:P,fileOps:j}),logger:f.logger});if(!X.trim())return;let V=O3(X,j),Y=$.reduce((R,U)=>R+f.estimateMessageTokens(U),0),B=[b3({summary:V,fileOps:j,tokensBefore:Y}),...$.slice(J)],A=B.reduce((R,U)=>R+f.estimateMessageTokens(U),0);return f.logger?.debug("Performed agentic compaction",{messagesBefore:$.length,messagesAfter:B.length,messagesSummarized:J,messagesPreserved:$.length-J,tokensBefore:Y,tokensAfter:A,contextWindowTokens:f.context.contextWindowTokens}),{messages:B}}function S3(f){if(G2(f))return;if(typeof f.content==="string"){let J=f.content.trim();return J?{...f,content:J}:void 0}let $=f.content.filter((J)=>J.type!=="text"||J.text.trim());if($.length===0)return;return{...f,content:$.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J)}}function T2(f,$){return f.reduce((J,W)=>J+$(W),0)}function C3(f,$){let J=Math.max(1,$),W=Math.max(16,J*4);if(typeof f.content==="string"){let Z=V$(f.content,W).trim();return{...f,content:Z||"..."}}let H=W,Q=f.content.map((Z)=>{if(Z.type!=="text"||H<=0)return Z;let j=V$(Z.text,H).trim();return H-=j.length,{...Z,text:j||"..."}});return{...f,content:Q}}function KY(f,$){let J=D3(f),W=VW(f),H=M3(f),Q=[];for(let Z=0;Z<f.length;Z+=1){let j=S3(f[Z]);if(!j)continue;Q.push({index:Z,message:j,estimatedTokens:$(j),isFirstUser:Z===J,isLastUser:Z===W,isLastAssistant:Z===H})}return Q}function E3(f,$,J,W){let H=f[$];H.message=J,H.estimatedTokens=W(J)}function O4(f,$,J,W){let H=T2(f.map((Q)=>Q.message),W);for(let Q=0;Q<f.length&&H>J;){if(!$(f[Q])){Q+=1;continue}H-=f[Q].estimatedTokens,f.splice(Q,1)}}function UY(f,$,J){let W=T2(f.map((Q)=>Q.message),J);if(W<=$)return;for(let Q=f.length-1;Q>=0&&W>$;Q-=1){let Z=f[Q];if(Z.isFirstUser)continue;let j=Math.max(K3,Z.estimatedTokens-(W-$));if(j>=Z.estimatedTokens)continue;E3(f,Q,C3(Z.message,j),J),W=T2(f.map((P)=>P.message),J)}if(W<=$)return;let H=f.findIndex((Q)=>Q.isFirstUser);if(H>=0){let Q=Math.max(1,f[H].estimatedTokens-(W-$));E3(f,H,C3(f[H].message,Q),J)}}function GY(f,$){return JSON.stringify(f)!==JSON.stringify($)}function k3(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.contextWindowTokens)),J=KY(f.context.messages,f.estimateMessageTokens);if(J.length===0)return;O4(J,(Z)=>Z.message.role==="assistant"&&!Z.isLastAssistant,$,f.estimateMessageTokens),O4(J,(Z)=>Z.message.role==="user"&&!Z.isFirstUser&&!Z.isLastUser,$,f.estimateMessageTokens),O4(J,(Z)=>Z.message.role==="assistant"&&Z.isLastAssistant,$,f.estimateMessageTokens),O4(J,(Z)=>Z.message.role==="user"&&Z.isLastUser&&!Z.isFirstUser,$,f.estimateMessageTokens),UY(J,$,f.estimateMessageTokens);let W=J.map((Z)=>Z.message);if(!GY(f.context.messages,W))return;let H=T2(f.context.messages.map((Z)=>S3(Z)??Z),f.estimateMessageTokens),Q=T2(W,f.estimateMessageTokens);return f.logger?.debug("Performed basic compaction",{messagesBefore:f.context.messages.length,messagesAfter:W.length,messagesRemoved:f.context.messages.length-W.length,tokensBefore:H,tokensAfter:Q,targetTokens:$,contextWindowTokens:f.context.contextWindowTokens}),{messages:W}}var TY={basic:({context:f,estimateMessageTokens:$,logger:J})=>k3({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:W,estimateMessageTokens:H,logger:Q})=>w3({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??PW,f.triggerTokens):J?.preserveRecentTokens??PW,estimateMessageTokens:H,logger:Q})};function hY(f){if(typeof f.config.reserveTokens==="number"){let W=Math.max(0,f.config.reserveTokens),H=Math.max(0,f.contextWindowTokens-W);return{shouldCompact:f.inputTokens>H,triggerTokens:H,thresholdRatio:f.contextWindowTokens>0?H/f.contextWindowTokens:0}}let $=f.config.thresholdRatio??y3,J=f.contextWindowTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function DY(f){let $=typeof f.manualTargetRatio==="number"&&Number.isFinite(f.manualTargetRatio)?f.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,$)),W=Math.max(1,Math.floor(Math.min(f.autoTriggerTokens,f.inputTokens*J)));return{triggerTokens:W,thresholdRatio:f.contextWindowTokens>0?W/f.contextWindowTokens:0}}function h2(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let W=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},H=T3(),Q=J?.strategy??"basic",Z=TY[Q],j=$.mode??"auto";return async(P)=>{let X=P.apiMessages.reduce((F,K)=>F+H(K),0),V=J?.contextWindowTokens??P.model.info?.contextWindow??F3;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let Y=hY({inputTokens:X,contextWindowTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(j==="auto"&&!Y.shouldCompact)return;let B=j==="manual"?DY({inputTokens:X,contextWindowTokens:V,autoTriggerTokens:Y.triggerTokens,manualTargetRatio:$.manualTargetRatio}):Y,A={agentId:P.agentId,conversationId:P.conversationId,parentAgentId:P.parentAgentId,iteration:P.iteration,messages:P.messages,model:P.model,contextWindowTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,utilizationRatio:V>0?X/V:0},R=j==="manual"?"manual_compaction":"auto_compaction";P.emitStatusNotice?.(j==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:P.iteration,triggerTokens:B.triggerTokens,contextWindowTokens:V});let U=P.messages.length,y=J?.compact?await J.compact(A):await Z({context:A,providerConfig:{...W,abortSignal:P.abortSignal},compaction:J,mode:j,estimateMessageTokens:H,logger:f.logger});if(y?.messages){let F=y.messages.reduce((K,M)=>K+H(M),0);f.logger?.log("Context compaction completed",{severity:"info",strategy:Q,contextWindowTokens:V,inputTokens:X,afterTokens:F,tokensSaved:X-F,utilizationBefore:`${(X/V*100).toFixed(1)}%`,utilizationAfter:`${(F/V*100).toFixed(1)}%`,thresholdTrigger:`${(B.thresholdRatio*100).toFixed(1)}%`,messagesBefore:U,messagesAfter:y.messages.length,messagesRemoved:U-y.messages.length})}return y}}var n7={};N(n7,{zodToJsonSchema:()=>kA,validateWithZod:()=>SA,resolveToolRoutingConfig:()=>j1,resolveToolPresetName:()=>B0,resolveCoreSelectedToolIds:()=>g4,getCoreHeadlessToolNames:()=>g2,getCoreDefaultEnabledToolIds:()=>x4,getCoreBuiltinToolCatalog:()=>G$,getCoreAcpToolNames:()=>v4,createWindowsShellTool:()=>GW,createWebFetchTool:()=>TW,createWebFetchExecutor:()=>m2,createToolPoliciesWithPreset:()=>C4,createSubmitAndExitTool:()=>_W,createSkillsTool:()=>B$,createSearchTool:()=>KW,createSearchExecutor:()=>k2,createReadFilesTool:()=>yW,createFileReadExecutor:()=>S2,createEditorTool:()=>DW,createEditorExecutor:()=>C2,createDefaultToolsWithPreset:()=>E4,createDefaultTools:()=>S0,createDefaultExecutors:()=>Q1,createBuiltinTools:()=>T$,createBashTool:()=>UW,createBashExecutor:()=>w2,createAskQuestionTool:()=>MW,createApplyPatchTool:()=>hW,createApplyPatchExecutor:()=>b2,WebFetchRequestSchema:()=>RW,ToolPresets:()=>Nf,TEAM_TOOL_NAMES:()=>Y1,SubmitInputSchema:()=>q2,SkillsInputSchema:()=>O2,SearchCodebaseInputSchema:()=>M2,RunCommandsInputSchema:()=>J1,ReadFilesInputSchema:()=>D2,ReadFileRequestSchema:()=>b0,FetchWebContentInputSchema:()=>_2,EditFileInputSchema:()=>L2,DefaultToolNames:()=>ff,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>Z1,AskQuestionInputSchema:()=>N2,ApplyPatchInputSchema:()=>z2,ALL_DEFAULT_TOOL_NAMES:()=>q0});import{validateWithZod as SA,zodToJsonSchema as kA}from"@cline/shared";var ff={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},q0=[ff.READ_FILES,ff.SEARCH_CODEBASE,ff.RUN_COMMANDS,ff.FETCH_WEB_CONTENT,ff.APPLY_PATCH,ff.EDITOR,ff.SKILLS,ff.ASK,ff.SUBMIT_AND_EXIT];import{createTool as V0,validateWithZod as E0,zodToJsonSchema as sf}from"@cline/shared";import{validateWithZod as r3}from"@cline/shared";import{z as D}from"zod";var w0=6000,YW=D.string().describe("The absolute file path of a text file to read content from"),I3=D.object({start_line:D.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:D.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),b0=D.object({path:YW,start_line:I3.shape.start_line,end_line:I3.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),D2=D.object({files:D.array(b0).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),x3=D.union([D2,b0,D.array(b0),D.array(D.string()),D.string(),D.object({files:b0}),D.object({file_paths:D.array(YW)}),D.object({file_paths:D.string()}),D.object({paths:D.array(D.union([YW,b0]))}),D.object({paths:b0}),D.object({paths:D.string()})]),M2=D.object({queries:D.array(D.string()).describe("Array of regex search queries to execute")}),g3=D.union([M2,D.array(D.string()),D.string(),D.object({queries:D.string()})]),Y$=D.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${w0*2} characters) to avoid timeouts.`),J1=D.object({commands:D.array(Y$).describe("Array of shell commands to execute")}),v3=D.union([J1,D.object({commands:Y$}),D.object({command:Y$}),D.object({cmd:Y$}),D.array(D.string()),D.string()]),BW=D.object({command:D.string().min(1).describe("The executable to run directly without shell parsing."),args:D.array(D.string()).optional().describe("Optional argv list passed directly to the executable.")}),u3=D.union([Y$,BW]),AW=D.object({commands:D.array(u3).describe("Array of commands to execute. Prefer structured { command, args } entries for portability; plain strings are still supported and are interpreted by the active shell.")}),c3=D.union([J1,AW,D.object({commands:u3}),D.array(BW),BW,D.object({command:Y$}),D.object({cmd:Y$}),D.array(D.string()),D.string()]),RW=D.object({url:D.string().describe("The URL to fetch"),prompt:D.string().min(2).describe("Analysis prompt for the fetched content")}),_2=D.object({requests:D.array(RW).describe("Array of the URLs for the web fetch requests")}),L2=D.object({path:D.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:D.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${w0} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:D.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${w0} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:D.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),z2=D.object({input:D.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),d3=D.union([z2,D.string()]),O2=D.object({skill:D.string().min(1).describe("Name of the skill to execute."),args:D.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),N2=D.object({question:D.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:D.array(D.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),q2=D.object({summary:D.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:D.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
43
+ 'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
44
+ IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function C0(f){if(f instanceof Error)return f.message;return String(f)}function l3(f){if(typeof f.old_text==="string"&&f.old_text.length>w0)return`Editor input too large: old_text was ${f.old_text.length} characters, exceeding the recommended limit of ${w0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if(f.new_text.length>w0)return`Editor input too large: new_text was ${f.new_text.length} characters, exceeding the recommended limit of ${w0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}function tf(f,$,J){return Promise.race([f,new Promise((W,H)=>{setTimeout(()=>H(Error(J)),$)})])}function p3(f){let $=r3(x3,f);if(typeof $==="string")return[{path:$}];if(Array.isArray($))return $.map((J)=>typeof J==="string"?{path:J}:J);if("files"in $)return Array.isArray($.files)?$.files:[$.files];if("file_paths"in $)return(Array.isArray($.file_paths)?$.file_paths:[$.file_paths]).map((W)=>({path:W}));if("paths"in $)return(Array.isArray($.paths)?$.paths:[$.paths]).map((W)=>typeof W==="string"?{path:W}:W);return[$]}function N4(f){let{path:$,start_line:J,end_line:W}=f;if(J==null&&W==null)return $;return`${$}:${J??1}-${W??"EOF"}`}function i3(f){let{start_line:$,end_line:J}=f;if($==null||J==null||$<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${$}, end_line: ${J})`}function n3(f){let $=r3(c3,f);if(typeof $==="string")return[$];if(Array.isArray($))return $;if("commands"in $)return Array.isArray($.commands)?$.commands:[$.commands];if("command"in $)return"args"in $?[$]:[$.command];if("cmd"in $)return[$.cmd];return[$]}function FW(f){if(typeof f==="string")return f;let $=f.args??[];if($.length===0)return f.command;let J=$.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${f.command} ${J.join(" ")}`}function yW(f,$={}){let J=$.fileReadTimeoutMs??1e4;return V0({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Returns file contents or error messages for each path.",inputSchema:sf(D2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,H)=>{let Q=p3(W);return Promise.all(Q.map(async(Z)=>{let j=i3(Z);if(j)return{query:N4(Z),result:"",error:`Invalid file range: ${j}`,success:!1};try{let P=await tf(f(Z,H),J,`File read timed out after ${J}ms`);return{query:N4(Z),result:P,success:!0}}catch(P){let X=C0(P);return{query:N4(Z),result:"",error:`Error reading file: ${X}`,success:!1}}}))}})}function KW(f,$={}){let J=$.searchTimeoutMs??30000,W=$.cwd??process.cwd();return V0({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:sf(M2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(H,Q)=>{let Z=E0(g3,H),j=Array.isArray(Z)?Z:typeof Z==="object"?Array.isArray(Z.queries)?Z.queries:[Z.queries]:[Z];return Promise.all(j.map(async(P)=>{try{let X=await tf(f(P,W,Q),J,`Search timed out after ${J}ms`),V=X.length>0&&!X.includes("No results found");return{query:P,result:X,success:V}}catch(X){let V=C0(X);return{query:P,result:"",error:`Search failed: ${V}`,success:!1}}}))}})}function UW(f,$={}){let J=$.bashTimeoutMs??30000,W=$.cwd??process.cwd();return V0({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped.",inputSchema:sf(J1),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=E0(v3,H),j;if(typeof Z==="string")j=[Z];else if(Array.isArray(Z))j=Z;else if("commands"in Z)j=Array.isArray(Z.commands)?Z.commands:[Z.commands];else if("command"in Z)j=[Z.command];else j=[Z.cmd];return Promise.all(j.map(async(P)=>{try{let X=await tf(f(P,W,Q),J,`Command timed out after ${J}ms`);return{query:P,result:X,success:!0}}catch(X){let V=C0(X);return{query:P,result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function GW(f,$={}){let J=$.bashTimeoutMs??30000,W=$.cwd??process.cwd();return V0({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:sf(AW),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=n3(H);return Promise.all(Z.map(async(j)=>{try{let P=await tf(f(j,W,Q),J,`Command timed out after ${J}ms`);return{query:FW(j),result:P,success:!0}}catch(P){let X=C0(P);return{query:FW(j),result:"",error:`Command failed: ${X}`,success:!1}}}))}})}function TW(f,$={}){let J=$.webFetchTimeoutMs??30000;return V0({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:sf(_2),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,H)=>{let Q=E0(_2,W);return Promise.all(Q.requests.map(async(Z)=>{try{let j=await tf(f(Z.url,Z.prompt,H),J,`Web fetch timed out after ${J}ms`);return{query:Z.url,result:j,success:!0}}catch(j){let P=C0(j);return{query:Z.url,result:"",error:`Error fetching web content: ${P}`,success:!1}}}))}})}var MY=`Use \`apply_patch\` to edit files with the canonical freeform patch grammar. Pass the patch text directly as the \`input\` string. Prefer the exact format below:
45
+
46
+ *** Begin Patch
47
+ *** Update File: path/to/file.ts
48
+ @@ optional section marker
49
+ [context before]
50
+ -[old line]
51
+ +[new line]
52
+ [context after]
53
+ *** End Patch
54
+
55
+ Supported actions:
56
+ - \`*** Add File: <path>\`
57
+ - \`*** Update File: <path>\`
58
+ - \`*** Delete File: <path>\`
59
+ - optional \`*** Move to: <new path>\` immediately after an Update File header
60
+
61
+ Rules:
62
+ - In an Add File section, every file-content line must start with \`+\`.
63
+ - In an Update section, use context lines plus \`-\` and \`+\` lines to describe the change.
64
+ - Use \`@@\` markers when extra context is needed to disambiguate repeated code blocks.
65
+ - Do not use line numbers; this format is context-based.
66
+ - Prefer sending the patch body directly. Legacy shell wrappers such as \`%%bash\` and \`apply_patch <<"EOF"\` are accepted for compatibility but are not preferred.
67
+
68
+ Example:
69
+
70
+ *** Begin Patch
71
+ *** Update File: src/page.tsx
72
+ @@
73
+ return (
74
+ <div>
75
+ <button onClick={() => console.log("clicked")}>Click me</button>
76
+ + <button onClick={() => console.log("cancel clicked")}>Cancel</button>
77
+ </div>
78
+ );
79
+ }
80
+ *** End Patch`;function hW(f,$={}){let J=$.applyPatchTimeoutMs??30000,W=$.cwd??process.cwd();return V0({name:"apply_patch",description:MY,inputSchema:sf(z2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=E0(d3,H),j=typeof Z==="string"?Z:Z.input;try{return{query:"apply_patch",result:await tf(f({input:j},W,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(P){return{query:"apply_patch",result:"",error:`apply_patch failed: ${C0(P)}`,success:!1}}}})}function DW(f,$={}){let J=$.editorTimeoutMs??30000,W=$.cwd??process.cwd();return V0({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:sf(L2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=E0(L2,H),j=Z.insert_line==null?"edit":"insert",P=l3(Z);if(P)return{query:`${j}:${Z.path}`,result:"",error:P,success:!1};try{let X=await tf(f(Z,W,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${j}:${Z.path}`,result:X,success:!0}}catch(X){let V=C0(X);return{query:`${j}:${Z.path}`,result:"",error:`Editor operation failed: ${V}`,success:!1}}}})}function B$(f,$={}){let J=$.skillsTimeoutMs??15000,W='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',H=V0({name:"skills",description:W,inputSchema:sf(O2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let j=E0(O2,Q);return tf(f(j.skill,j.args||void 0,Z),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(H,"description",{get(){let Q=f.configuredSkills?.filter((Z)=>!Z.disabled).map((Z)=>Z.name);if(Q&&Q.length>0)return`${W} Available skills: ${Q.join(", ")}.`;return W},enumerable:!0,configurable:!0}),H}function MW(f){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:sf(N2),retryable:!1,maxRetries:0,execute:async($,J)=>{let W=E0(N2,$);return f(W.question,W.options,J)}}}function _W(f,$={}){let J=$.submitTimeoutMs??15000;return V0({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:sf(q2),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,H)=>{let Q=E0(q2,W);return tf(f(Q.summary,Q.verified,H),J,`submit_and_exit timed out after ${J}ms`)}})}function S0(f){let{executors:$,enableReadFiles:J=!0,enableSearch:W=!0,enableBash:H=!0,enableWebFetch:Q=!0,enableApplyPatch:Z=!1,enableEditor:j=!0,enableSkills:P=!0,enableAskQuestion:X=!0,enableSubmitAndExit:V=!1,...Y}=f,B=[];if(J&&$.readFile)B.push(yW($.readFile,Y));if(W&&$.search)B.push(KW($.search,Y));if(H&&$.bash)if(process.platform==="win32")B.push(GW($.bash,Y));else B.push(UW($.bash,Y));if(Q&&$.webFetch)B.push(TW($.webFetch,Y));if(j&&$.editor)B.push(DW($.editor,Y));else if(Z&&$.applyPatch)B.push(hW($.applyPatch,Y));if(P&&$.skills)B.push(B$($.skills,Y));let A=V?$.submit:void 0;if(X&&$.askQuestion&&!A)B.push(MW($.askQuestion));if(A)B.push(_W(A,Y));return B}import*as zf from"node:fs/promises";import*as Of from"node:path";var I={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},t3=["%%bash","apply_patch","EOF","```"];class Jf extends Error{constructor(f){super(f);this.name="DiffError"}}function Lf(f){let $={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return f.normalize("NFC").replace(/./gu,(J)=>$[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class LW{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(f,$){this.lines=f;this.currentFiles=$}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning(f){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(f)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(I.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(I.END)??!1}parseNextAction(){let f=this.lines[this.index];if(f?.startsWith(I.UPDATE)){this.parseUpdate(f.substring(I.UPDATE.length).trim());return}if(f?.startsWith(I.DELETE)){this.parseDelete(f.substring(I.DELETE.length).trim());return}if(f?.startsWith(I.ADD)){this.parseAdd(f.substring(I.ADD.length).trim());return}throw new Jf(`Unknown line while parsing: ${f}`)}checkDuplicate(f,$){if(f in this.patch.actions)throw new Jf(`Duplicate ${$} for file: ${f}`)}parseUpdate(f){this.checkDuplicate(f,"update"),this.currentPath=f,this.index++;let $=this.lines[this.index]?.startsWith(I.MOVE)?(this.lines[this.index++]??"").substring(I.MOVE.length).trim():void 0;if(!(f in this.currentFiles))throw new Jf(`Update File Error: Missing File: ${f}`);let J=this.currentFiles[f]??"",W=this.parseUpdateFile(J,f);W.movePath=$,this.patch.actions[f]=W,this.currentPath=void 0}parseUpdateFile(f,$){let J={type:"update",chunks:[]},W=f.split(`
81
+ `),H=0,Q=[I.END,I.UPDATE,I.DELETE,I.ADD,I.END_FILE];while(!Q.some((Z)=>this.lines[this.index]?.startsWith(Z.trim()))){let Z=this.lines[this.index],j=Z?.startsWith("@@ ")?Z.substring(3):void 0;if(j!==void 0||(Z==="@@"?Z:void 0)!==void 0)this.index++;else if(H!==0)throw new Jf(`Invalid Line:
82
+ ${this.lines[this.index]}`);if(j?.trim()){let y=Lf(j.trim());for(let F=H;F<W.length;F++){let K=W[F];if(K&&(Lf(K)===y||Lf(K.trim())===y)){if(H=F+1,Lf(K.trim())===y&&Lf(K)!==y)this.fuzz++;break}}}let[X,V,Y,B]=zY(this.lines,this.index),[A,R,U]=LY(W,X,H,B);if(A===-1){let y=X.join(`
83
+ `);this.addWarning({path:this.currentPath||$,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${U.toFixed(2)}). Chunk skipped.`,context:y.length>200?`${y.substring(0,200)}...`:y}),this.index=Y}else{this.fuzz+=R;for(let y of V)y.origIndex+=A,J.chunks.push(y);H=A+X.length,this.index=Y}}return J}parseDelete(f){if(this.checkDuplicate(f,"delete"),!(f in this.currentFiles))throw new Jf(`Delete File Error: Missing File: ${f}`);this.patch.actions[f]={type:"delete",chunks:[]},this.index++}parseAdd(f){if(this.checkDuplicate(f,"add"),f in this.currentFiles)throw new Jf(`Add File Error: File already exists: ${f}`);this.index++;let $=[],J=[I.END,I.UPDATE,I.DELETE,I.ADD];while(this.hasMoreLines()&&!J.some((W)=>this.lines[this.index]?.startsWith(W.trim()))){let W=this.lines[this.index++];if(W===void 0)break;if(!W.startsWith("+"))throw new Jf(`Invalid Add File line (missing '+'): ${W}`);$.push(W.substring(1))}this.patch.actions[f]={type:"add",newFile:$.join(`
84
+ `),chunks:[]}}}function a3(f,$){let J=f.length>$.length?f:$,W=f.length>$.length?$:f;if(J.length===0)return 1;let H=_Y(W,J);return(J.length-H)/J.length}function _Y(f,$){let J=$.length+1,W=f.length+1,H=Array(J*W).fill(0),Q=(j,P)=>H[j*W+P]??0,Z=(j,P,X)=>{H[j*W+P]=X};for(let j=0;j<=$.length;j++)Z(j,0,j);for(let j=0;j<=f.length;j++)Z(0,j,j);for(let j=1;j<=$.length;j++)for(let P=1;P<=f.length;P++)if($[j-1]===f[P-1])Z(j,P,Q(j-1,P-1));else Z(j,P,1+Math.min(Q(j-1,P-1),Q(j,P-1),Q(j-1,P)));return Q($.length,f.length)}function LY(f,$,J,W){if($.length===0)return[J,0,1];let H=0,Q=(Z)=>{let j=Lf($.join(`
85
+ `));for(let X=Z;X<f.length;X++){let V=Lf(f.slice(X,X+$.length).join(`
86
+ `));if(V===j)return[X,0,1];let Y=a3(V,j);if(Y>H)H=Y}for(let X=Z;X<f.length;X++){let V=Lf(f.slice(X,X+$.length).map((B)=>B.trimEnd()).join(`
87
+ `)),Y=Lf($.map((B)=>B.trimEnd()).join(`
88
+ `));if(V===Y)return[X,1,1]}for(let X=Z;X<f.length;X++){let V=Lf(f.slice(X,X+$.length).map((B)=>B.trim()).join(`
89
+ `)),Y=Lf($.map((B)=>B.trim()).join(`
90
+ `));if(V===Y)return[X,100,1]}let P=0.66;for(let X=Z;X<f.length;X++){let V=Lf(f.slice(X,X+$.length).join(`
91
+ `)),Y=a3(V,j);if(Y>=P)return[X,1000,Y];if(Y>H)H=Y}return[-1,0,H]};if(W){let[Z,j,P]=Q(f.length-$.length);if(Z!==-1)return[Z,j,P];return[Z,j,P]=Q(J),[Z,j+1e4,P]}return Q(J)}function zY(f,$){let J=$,W=[],H=[],Q=[],Z=[],j="keep",P=["@@",I.END,I.UPDATE,I.DELETE,I.ADD,I.END_FILE];while(J<f.length){let X=f[J];if(!X||P.some((B)=>X.startsWith(B.trim())))break;if(X==="***")break;if(X.startsWith("***"))throw new Jf(`Invalid line: ${X}`);J++;let V=j,Y=X;if(Y[0]==="+")j="add";else if(Y[0]==="-")j="delete";else if(Y[0]===" ")j="keep";else j="keep",Y=` ${Y}`;if(Y=Y.slice(1),j==="keep"&&V!==j){if(Q.length||H.length)Z.push({origIndex:W.length-H.length,delLines:H,insLines:Q});H=[],Q=[]}if(j==="delete")H.push(Y),W.push(Y);else if(j==="add")Q.push(Y);else W.push(Y)}if(Q.length||H.length)Z.push({origIndex:W.length-H.length,delLines:H,insLines:Q});if(J<f.length&&f[J]===I.END_FILE)return J++,[W,Z,J,!0];return[W,Z,J,!1]}function zW(f,$,J){let W=Of.isAbsolute($),H=W?Of.normalize($):Of.resolve(f,$);if(!J||W)return H;let Q=Of.relative(f,H);if(Q.startsWith("..")||Of.isAbsolute(Q))throw new Jf(`Path must stay within cwd: ${$}`);return H}function OY(f){return f.split(`
92
+ `).map(($)=>$.replace(/\r$/,""))}function s3(f){if(f.trim()==="")return!1;return t3.some(($)=>f.startsWith($))}function NY(f){let $=0,J=f.length;while($<J&&s3(f[$]??""))$++;while(J>$&&s3(f[J-1]??""))J--;return f.slice($,J)}function qY(f){let $=OY(f),J=$.findIndex((Z)=>Z.startsWith(I.BEGIN)),W=-1;for(let Z=$.length-1;Z>=0;Z--)if($[Z]?.startsWith(I.END)){W=Z;break}if(J!==-1||W!==-1){if(J===-1||W===-1||W<J)throw new Jf("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:$.slice(J,W+1)}}let H=NY($);while(H.length>0&&H[0]==="")H.shift();while(H.length>0&&H[H.length-1]==="")H.pop();return{lines:[I.BEGIN,...H,I.END]}}function bY(f,$){let J=new Set;for(let W of f)for(let H of $)if(W.startsWith(H)){J.add(W.substring(H.length).trim());break}return[...J]}function wY(f,$,J){if($.length===0)return f;let W=f.split(`
93
+ `),H=[],Q=0;for(let Z of $){if(Z.origIndex>W.length)throw new Jf(`${J}: chunk.origIndex ${Z.origIndex} > lines.length ${W.length}`);if(Q>Z.origIndex)throw new Jf(`${J}: currentIndex ${Q} > chunk.origIndex ${Z.origIndex}`);H.push(...W.slice(Q,Z.origIndex)),H.push(...Z.insLines),Q=Z.origIndex+Z.delLines.length}return H.push(...W.slice(Q)),H.join(`
94
+ `)}async function CY(f,$,J,W){let H=bY(f,[I.UPDATE,I.DELETE]),Q={};for(let Z of H){let j=zW($,Z,W),P;try{P=await zf.readFile(j,J)}catch{throw new Jf(`File not found: ${Z}`)}Q[Z]=P.replace(/\r\n/g,`
95
+ `)}return Q}function EY(f,$){let J={};for(let[W,H]of Object.entries(f.actions))switch(H.type){case"delete":J[W]={type:"delete",oldContent:$[W]};break;case"add":if(H.newFile===void 0)throw new Jf("ADD action without file content");J[W]={type:"add",newContent:H.newFile};break;case"update":J[W]={type:"update",oldContent:$[W],newContent:wY($[W]??"",H.chunks,W),movePath:H.movePath};break}return J}async function SY(f,$,J,W){let H=[];for(let[Q,Z]of Object.entries(f)){let j=zW($,Q,W);switch(Z.type){case"delete":await zf.rm(j,{force:!0}),H.push(`${Q}: [deleted]`);break;case"add":if(Z.newContent===void 0)throw new Jf(`Cannot create ${Q} with no content`);await zf.mkdir(Of.dirname(j),{recursive:!0}),await zf.writeFile(j,Z.newContent,{encoding:J}),H.push(Q);break;case"update":{if(Z.newContent===void 0)throw new Jf(`UPDATE change for ${Q} has no new content`);if(Z.movePath){let P=zW($,Z.movePath,W);await zf.mkdir(Of.dirname(P),{recursive:!0}),await zf.writeFile(P,Z.newContent,{encoding:J}),await zf.rm(j,{force:!0}),H.push(`${Q} -> ${Z.movePath}`)}else await zf.writeFile(j,Z.newContent,{encoding:J}),H.push(Q);break}}}return H}function b2(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0}=f;return async(W,H,Q)=>{let Z=qY(W.input),j=await CY(Z.lines,H,$,J),P=new LW(Z.lines,j),{patch:X,fuzz:V}=P.parse(),Y=EY(X,j),B=await SY(Y,H,$,J),A=["Successfully applied patch to the following files:"];for(let R of B)A.push(R);if(V>0)A.push(`Note: Patch applied with fuzz factor ${V}`);if(X.warnings&&X.warnings.length>0)for(let R of X.warnings)A.push(`Warning (${R.path}): ${R.message}`);return A.join(`
96
+ `)}}import{spawn as o3}from"node:child_process";import{getDefaultShell as kY,getShellArgs as mY}from"@cline/shared";function IY(f,$,J,W,H){return new Promise((Q,Z)=>{let j=process.platform==="win32",P=o3(f.executable,f.args,{cwd:f.cwd,env:{...process.env,...f.env},stdio:["pipe","pipe","pipe"],detached:!j}),X=P.pid,V="",Y="",B=0,A=!1,R=!1,U=(G)=>{if(R)return;R=!0,G()},y=()=>{if(!X)return;if(j){o3("taskkill",["/pid",String(X),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-X,"SIGKILL")}catch{P.kill("SIGKILL")}},F=(G)=>{A=!0,y(),U(()=>Z(G))},K=setTimeout(()=>F(Error(`Command timed out after ${J}ms`)),J),M=()=>F(Error("Command was aborted"));if($.signal)$.signal.addEventListener("abort",M);let h=()=>{clearTimeout(K),$.signal?.removeEventListener("abort",M)};P.stdout?.on("data",(G)=>{if(B+=G.length,B<=W)V+=G.toString()}),P.stderr?.on("data",(G)=>{if(B+=G.length,B<=W)Y+=G.toString()}),P.on("close",(G)=>{if(h(),A)return;let T=H?V+(Y?`
97
+ [stderr]
98
+ ${Y}`:""):V;if(B>W)T+=`
99
+
100
+ [Output truncated: ${B} bytes total, showing first ${W} bytes]`;if(G!==0)U(()=>Z(Error(Y||`Command exited with code ${G}`)));else U(()=>Q(T))}),P.on("error",(G)=>{h(),U(()=>Z(Error(`Failed to execute command: ${G.message}`)))})})}function w2(f={}){let{shell:$=kY(process.platform),timeoutMs:J=30000,maxOutputBytes:W=1e6,env:H={},combineOutput:Q=!0}=f;return(Z,j,P)=>{let X=typeof Z!=="string";return IY({executable:X?Z.command:$,args:X?Z.args??[]:mY($,Z),cwd:j,env:H},P,J,W,Q)}}import*as df from"node:fs/promises";import*as cf from"node:path";function xY(f,$,J){let W=cf.isAbsolute($),H=W?cf.normalize($):cf.resolve(f,$);if(!J)return H;if(W)return H;let Q=cf.relative(f,H);if(Q.startsWith("..")||cf.isAbsolute(Q))throw Error(`Path must stay within cwd: ${$}`);return H}function gY(f,$){if($.length===0)return 0;return f.split($).length-1}function vY(f,$,J){let W=f.split(`
101
+ `),H=$.split(`
102
+ `),Q=Math.max(W.length,H.length),Z=["```diff"],j=0;for(let P=0;P<Q;P++){if(j>=J){Z.push("... diff truncated ...");break}let X=W[P],V=H[P];if(X===V)continue;let Y=P+1;if(X!==void 0)Z.push(`-${Y}: ${X}`),j++;if(V!==void 0&&j<J)Z.push(`+${Y}: ${V}`),j++}return Z.push("```"),Z.join(`
103
+ `)}async function uY(f,$,J){return await df.mkdir(cf.dirname(f),{recursive:!0}),await df.writeFile(f,$,{encoding:J}),`File created successfully at: ${f}`}async function cY(f){try{return await df.access(f),!0}catch{return!1}}async function dY(f,$,J,W,H){let Q=await df.readFile(f,W),Z=gY(Q,$);if(Z===0)throw Error(`No replacement performed: text not found in ${f}.`);if(Z>1)throw Error(`No replacement performed: multiple occurrences of text found in ${f}.`);let j=Q.replace($,J??"");await df.writeFile(f,j,{encoding:W});let P=vY(Q,j,H);return`Edited ${f}
104
+ ${P}`}async function rY(f,$,J,W){let Q=(await df.readFile(f,W)).split(`
105
+ `),Z=Q.length+1;if($<1||$>Z)throw Error(`Invalid insert_line: ${$}. insert_line must be a positive one-based boundary line in the range 1-${Z}. Use ${Z} to append at EOF.`);let j=$-1;return Q.splice(j,0,...J.split(`
106
+ `)),await df.writeFile(f,Q.join(`
107
+ `),{encoding:W}),`Inserted content at line ${$} in ${f}.`}function C2(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0,maxDiffLines:W=200}=f;return async(H,Q,Z)=>{let j=xY(Q,H.path,J);if(H.insert_line!=null)return rY(j,H.insert_line,H.new_text,$);if(!await cY(j))return uY(j,H.new_text,$);if(H.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return dY(j,H.old_text,H.new_text,$,W)}}import*as E2 from"node:fs/promises";import*as k0 from"node:path";var lY=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),pY={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function S2(f={}){let{maxFileSizeBytes:$,encoding:J,includeLineNumbers:W}={...pY,...f};return async(H,Q)=>{let{path:Z,start_line:j,end_line:P}=H,X=k0.isAbsolute(Z)?k0.normalize(Z):k0.resolve(process.cwd(),Z),V=k0.extname(X).toLowerCase(),Y=lY.get(V),B=await E2.stat(X);if(!B.isFile())throw Error(`Path is not a file: ${X}`);if(B.size>$)throw Error(`File too large: ${B.size} bytes (max: ${$} bytes). Consider reading specific sections or using a different approach.`);if(Y){if(Q.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let K=await E2.readFile(X);return[{type:"text",text:"Successfully read image"},{type:"image",data:K.toString("base64"),mediaType:Y}]}let R=(await E2.readFile(X,J)).split(`
108
+ `),U=Math.max((j??1)-1,0),y=Math.min(P??R.length,R.length),F=R.slice(U,y);if(W){let K=String(R.length).length;return F.map((M,h)=>`${String(U+h+1).padStart(K," ")} | ${M}`).join(`
109
+ `)}return F.join(`
110
+ `)}}import{spawn as Q7}from"node:child_process";import*as Z7 from"node:fs/promises";import*as w4 from"node:path";var H7={};N(H7,{prewarmFileIndex:()=>b4,getFileIndex:()=>Y0,enrichPromptWithMentions:()=>H1});import{spawn as iY}from"node:child_process";import{readdir as nY}from"node:fs/promises";import NW from"node:path";import{isMainThread as $7,parentPort as e3,Worker as aY}from"node:worker_threads";var tY=15000,sY=600000,oY=1000,eY=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function f7(f){let $=f&&typeof f==="object"&&"code"in f?String(f.code??""):"";return $==="EACCES"||$==="EPERM"||$==="ENOENT"}var W1=new Map;function fB(f){if(W1.size<=1)return;for(let[$,J]of W1.entries()){if(J.pending)continue;if(f-J.lastAccessedAt>sY)W1.delete($)}}function $B(f,$){return NW.relative(f,$).split(NW.sep).join("/")}async function JB(f){let J=(await new Promise((W,H)=>{let Q=iY("rg",["--files","--hidden","-g","!.git"],{cwd:f,stdio:["ignore","pipe","pipe"]}),Z="",j="";Q.stdout.on("data",(P)=>{Z+=P.toString()}),Q.stderr.on("data",(P)=>{j+=P.toString()}),Q.on("error",H),Q.on("close",(P)=>{if(P===0){W(Z);return}H(Error(j||`rg exited with code ${P}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(J)}async function J7(f,$,J){let W;try{W=await nY($,{withFileTypes:!0})}catch(H){if(f7(H))return;throw H}for(let H of W){let Q=NW.join($,H.name);if(H.isDirectory()){if(eY.has(H.name))continue;try{await J7(f,Q,J)}catch(Z){if(f7(Z))continue;throw Z}continue}if(H.isFile())J.add($B(f,Q))}}async function WB(f){let $=new Set;return await J7(f,f,$),$}async function q4(f){try{return await JB(f)}catch{return WB(f)}}function HB(){if($7||!e3)return;let f=e3;f.on("message",($)=>{if($.type!=="index")return;q4($.cwd).then((J)=>{let W={type:"indexResult",requestId:$.requestId,files:Array.from(J)};f.postMessage(W)}).catch((J)=>{let W={type:"indexResult",requestId:$.requestId,error:J instanceof Error?J.message:"Failed to build file index"};f.postMessage(W)})})}class W7{worker=new aY(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",(f)=>{if(f.type!=="indexResult")return;let $=this.pending.get(f.requestId);if(!$)return;if(this.pending.delete(f.requestId),f.error){$.reject(Error(f.error));return}$.resolve(f.files??[])}),this.worker.on("error",(f)=>{this.flushPending(f)}),this.worker.on("exit",(f)=>{if(f!==0)this.flushPending(Error(`File index worker exited with code ${f}`))})}requestIndex(f){let $=++this.nextRequestId,J=new Promise((H,Q)=>{let Z=setTimeout(()=>{this.pending.delete($),H(null)},oY);Z.unref(),this.pending.set($,{resolve:(j)=>{clearTimeout(Z),H(j)},reject:(j)=>{clearTimeout(Z),Q(j)}})}),W={type:"index",requestId:$,cwd:f};return this.worker.postMessage(W),J}flushPending(f){for(let[$,J]of this.pending.entries())J.reject(f),this.pending.delete($)}}HB();var OW;function QB(){if(!$7)return null;if(OW===void 0)OW=new W7;return OW}async function ZB(f){let $=QB();if(!$)return q4(f);try{let J=await $.requestIndex(f);if(J===null)return q4(f);return new Set(J)}catch{return q4(f)}}async function Y0(f,$={}){let J=$.ttlMs??tY,W=Date.now();fB(W);let H=W1.get(f);if(H&&J>0&&W-H.lastBuiltAt<=J&&H.files.size>0)return H.lastAccessedAt=W,H.files;if(H?.pending)return H.lastAccessedAt=W,H.pending;let Q=ZB(f).then((Z)=>{return W1.set(f,{files:Z,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),Z});return W1.set(f,{files:H?.files??new Set,lastBuiltAt:H?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function b4(f,$={}){await Y0(f,{...$,ttlMs:0})}import{stat as jB}from"node:fs/promises";import A$ from"node:path";var PB=/[),.:;!?`'"]+$/,XB=/^[(`'"]+/;function VB(f){let $=f.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let W of $){let H=(W[2]??"").trim();if(H.length===0)continue;let Q=H.replace(XB,"").replace(PB,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function YB(f,$){let J=f.replace(/\\/g,"/"),W=A$.isAbsolute(J)?A$.resolve(J):A$.resolve($,J),H=A$.relative($,W);if(H.startsWith("..")||A$.isAbsolute(H))return;return H.split(A$.sep).join("/")}async function H1(f,$,J={}){let W=VB(f);if(W.length===0)return{prompt:f,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:H,maxFileBytes:Q,maxTotalBytes:Z}=J,j=await Y0($,{ttlMs:J.ttlMs}),P=[],X=[],V=[],Y=0;for(let B of W){if(H&&V.length>=H){X.push(B);continue}let A=YB(B,$);if(!A||!j.has(A)){X.push(B);continue}if(!Q||!Z){P.push(A);continue}let R=A$.join($,A);try{if(!(await jB(R)).isFile()){X.push(B);continue}let y=Y+Q;if(y>Z){X.push(B);continue}Y=y,P.push(A)}catch{X.push(B)}}return{prompt:f,mentions:W,matchedFiles:P,ignoredMentions:X}}var BB=["ts","tsx","js","jsx","mjs","cjs","json","md","mdx","txt","yaml","yml","toml","py","rb","go","rs","java","kt","swift","c","cpp","h","hpp","css","scss","less","html","vue","svelte","sql","sh","bash","zsh","fish","ps1","env","gitignore","dockerignore","editorconfig"],AB=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],R$=null;function RB(){if(R$!==null)return Promise.resolve(R$);return new Promise((f)=>{let $=Q7("rg",["--version"],{stdio:["ignore","pipe","pipe"]});$.on("close",(J)=>{R$=J===0,f(R$)}),$.on("error",()=>{R$=!1,f(!1)}),setTimeout(()=>{if(!$.killed)$.kill("SIGTERM");if(R$===null)R$=!1,f(!1)},1000)})}function FB(f,$,J,W,H=5000,Q){return new Promise((Z)=>{let j=Q7("rg",["--json",`--context=${W}`,"--max-count=1","-i",f],{cwd:$,stdio:["ignore","pipe","pipe"]}),P="",X=!1,V=()=>{if(!j.killed)j.kill("SIGTERM")},Y=setTimeout(()=>{if(!X)X=!0,V(),Z(null)},H),B=(A)=>{if(!X)X=!0,clearTimeout(Y),V(),Z(A)};if(Q?.aborted){V(),Z(null);return}Q?.addEventListener("abort",()=>{B(null)}),j.stdout.on("data",(A)=>{P+=A.toString()}),j.stderr.on("data",()=>{}),j.on("close",(A)=>{if(A===0||A===1){try{let R=[],U=P.split(`
111
+ `).filter((y)=>y.trim());for(let y of U){if(R.length>=J)break;let F=JSON.parse(y);if(F.type==="match"){let K=F.data,M=[];if(F.data.submatches&&F.data.submatches.length>0){let h=F.data.submatches[0];R.push({file:K.path.text,line:K.line_number,column:(h?.start??0)+1,match:h?.match?.text??"",context:M})}}else if(F.type==="context"&&R.length>0){let K=R[R.length-1],M=F.data.line_number===K.line?">":" ";K.context.push(`${M} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}B(R.length>0?R:null)}catch{B(null)}return}B(null)}),j.on("error",()=>{B(null)})})}function yB(f,$,J,W){let H=f.split("/"),Q=H[H.length-1]??"";if(H.length-1>W)return!1;for(let P=0;P<H.length-1;P++)if($.has(H[P]??""))return!1;let j=w4.posix.extname(Q).slice(1).toLowerCase();return J.has(j)||!j&&!Q.startsWith(".")}function k2(f={}){let{includeExtensions:$=BB,excludeDirs:J=AB,maxResults:W=100,contextLines:H=2,maxDepth:Q=20}=f,Z=new Set(J),j=new Set($.map((P)=>P.toLowerCase()));return async(P,X,V)=>{if(V.signal?.aborted)throw Error("Search operation aborted");let Y=await RB(),B=null;if(Y)B=await FB(P,X,W,H,5000,V.signal);if(B){let K=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${P}`,""];for(let M of B)K.push(`${M.file}:${M.line}:${M.column}`),K.push(...M.context),K.push("");if(B.length>=W)K.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return K.join(`
112
+ `)}let A;try{A=new RegExp(P,"gim")}catch(K){throw Error(`Invalid regex pattern: ${P}. ${K instanceof Error?K.message:""}`)}let R=[],U=0,y=await Y0(X);for(let K of y){if(V.signal?.aborted)throw Error("Search operation aborted");if(!yB(K,Z,j,Q))continue;if(R.length>=W)break;U++;let M=w4.join(X,K);try{let G=(await Z7.readFile(M,"utf-8")).split(`
113
+ `);for(let T=0;T<G.length;T++){let z=G[T];A.lastIndex=0;let u=A.exec(z);while(u!==null){if(R.length>=W)break;let vf=Math.max(0,T-H),a=Math.min(G.length-1,T+H),c=[];for(let d=vf;d<=a;d++){let t=d===T?">":" ";c.push(`${t} ${d+1}: ${G[d]}`)}if(R.push({file:K,line:T+1,column:u.index+1,match:u[0],context:c}),u.index===A.lastIndex)A.lastIndex++;u=A.exec(z)}}}catch{}}if(R.length===0)return`No results found for pattern: ${P}
114
+ Searched ${U} files.`;let F=[`Found ${R.length} result${R.length===1?"":"s"} for pattern: ${P}`,`Searched ${U} files.`,""];for(let K of R)F.push(`${K.file}:${K.line}:${K.column}`),F.push(...K.context),F.push("");if(R.length>=W)F.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return F.join(`
115
+ `)}}function KB(f){return f.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
116
+ `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,($,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
117
+ `).replace(/\n{3,}/g,`
118
+
119
+ `).trim()}function m2(f={}){let{timeoutMs:$=30000,maxResponseBytes:J=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:H={},followRedirects:Q=!0}=f;return async(Z,j,P)=>{let X;try{X=new URL(Z)}catch{throw Error(`Invalid URL: ${Z}`)}if(!["http:","https:"].includes(X.protocol))throw Error(`Invalid protocol: ${X.protocol}. Only http and https are supported.`);let V=new AbortController,Y=setTimeout(()=>V.abort(),$),B;if(P.signal)B=()=>V.abort(),P.signal.addEventListener("abort",B);try{let A=await fetch(Z,{method:"GET",headers:{"User-Agent":W,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...H},redirect:Q?"follow":"manual",signal:V.signal});if(clearTimeout(Y),!Q&&A.status>=300&&A.status<400)return`Redirect to: ${A.headers.get("location")}`;if(!A.ok)throw Error(`HTTP ${A.status}: ${A.statusText}`);let R=A.headers.get("content-type")||"",U=A.body?.getReader();if(!U)throw Error("Failed to read response body");let y=[],F=0;while(!0){let{done:z,value:u}=await U.read();if(z)break;if(F+=u.length,F>J)throw U.cancel(),Error(`Response too large: exceeded ${J} bytes`);y.push(u)}let K=new Uint8Array(F),M=0;for(let z of y)K.set(z,M),M+=z.length;let h=new TextDecoder("utf-8").decode(K),G;if(R.includes("text/html")||R.includes("application/xhtml"))G=KB(h);else if(R.includes("application/json"))try{let z=JSON.parse(h);G=JSON.stringify(z,null,2)}catch{G=h}else G=h;let T=[`URL: ${Z}`,`Content-Type: ${R}`,`Size: ${F} bytes`,"","--- Content ---",G.slice(0,50000)];if(G.length>50000)T.push(`
120
+ [Content truncated: showing first 50000 of ${G.length} characters]`);return T.push("","--- Analysis Request ---",`Prompt: ${j}`),T.join(`
121
+ `)}catch(A){if(clearTimeout(Y),A instanceof Error){if(A.name==="AbortError")throw Error(`Request timed out after ${$}ms`);throw A}throw Error(`Fetch failed: ${String(A)}`)}finally{if(P.signal&&B)P.signal.removeEventListener("abort",B)}}}function Q1(f={}){return{readFile:S2(f.fileRead),search:k2(f.search),bash:w2(f.bash),webFetch:m2(f.webFetch),applyPatch:b2(f.applyPatch),editor:C2(f.editor)}}var UB={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion",submit_and_exit:"enableSubmitAndExit"},Z1=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function j7(f,$){if(!$||$.length===0)return!0;let J=f.toLowerCase();return $.some((W)=>J.includes(W.toLowerCase()))}function GB(f,$,J,W){if(f.mode&&f.mode!=="any"&&f.mode!==W)return!1;return j7($,f.providerIdIncludes)&&j7(J,f.modelIdIncludes)}function j1(f,$,J,W){if(!W||W.length===0)return{};let H=new Map;for(let Z of W){if(!GB(Z,f,$,J))continue;for(let j of Z.disableTools??[])H.set(j,!1);for(let j of Z.enableTools??[])H.set(j,!0)}let Q={};for(let[Z,j]of H.entries())Q[UB[Z]]=j;return Q}var Nf={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function B0(f){if(f.mode==="plan")return"plan";if(f.mode==="yolo")return"yolo";return"act"}function C4(f){if(f!=="yolo")return{};let $={enabled:!0,autoApprove:!0},J={"*":$};for(let W of q0)J[W]=$;return J}function E4(f,$){let J=Nf[f],{enableSpawnAgent:W,enableAgentTeams:H,...Q}=J;return S0({...Q,...$})}import{createTool as YA,zodToJsonSchema as BA}from"@cline/shared";import{z as xW}from"zod";import{createAgentRuntime as JA}from"@cline/agents";import{createContributionRegistry as WA}from"@cline/shared";import{createGateway as TB,MODEL_COLLECTIONS_BY_PROVIDER_ID as hB}from"@cline/llms";function qW(f){let $=f.providerConfig;if($?.knownModels)return $.knownModels;if(f.knownModels)return f.knownModels;return hB[f.providerId]?.models??void 0}function P7(f,$){let J=f.providerConfig,W=J?.providerId===f.providerId?J:void 0,H={...W??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.headers??W?.headers,knownModels:qW(f),maxOutputTokens:f.maxTokensPerTurn,reasoningEffort:f.reasoningEffort,thinkingBudgetTokens:f.thinkingBudgetTokens,thinking:f.thinking,logger:$,extensionContext:f.extensionContext};return TB({providerConfigs:[{providerId:H.providerId,apiKey:H.apiKey,baseUrl:H.baseUrl,headers:H.headers,models:H.knownModels?Object.entries(H.knownModels).map(([Q,Z])=>({id:Q,name:Z.name??Q,description:Z.description,contextWindow:Z.contextWindow,maxOutputTokens:Z.maxTokens})):void 0}],logger:$}).createAgentModel({providerId:H.providerId,modelId:H.modelId},{maxTokens:H.maxOutputTokens})}import{normalizeUserInput as X7}from"@cline/shared";var DB=50000,MB=6000000,V7=8000,_B=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),LB=new Set(["read","read_files"]),F$="[outdated - see the latest file content]",Y7="Tool execution was interrupted before a result was produced.",zB=(f)=>`
122
+
123
+ ...[truncated ${f} chars]...
124
+
125
+ `,OB=(f)=>`
126
+
127
+ ...[truncated ${f} chars to fit provider request budget]...
128
+
129
+ `;class wW{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=DB,$=_B,J=MB){this.maxToolResultChars=f;this.targetToolNames=$;this.maxTotalTextBytes=J}buildForApi(f){this.reindex(f);let J=this.addMissingToolResults(f).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let Z=X7(W.content);if(Z!==W.content)return{...W,content:Z}}return W}let H=!1,Q=W.content.map((Z)=>{let j=this.transformBlock(Z,W.role);if(j!==Z)H=!0;return j});return H?{...W,content:Q}:W});return this.truncateToTotalTextBudget(J)}transformBlock(f,$){if($==="user"&&f.type==="text"&&typeof f.text==="string"){let H=X7(f.text);if(H!==f.text)return{...f,text:H};return f}if(f.type==="file"){let H=this.truncateMiddle(f.content);return H===f.content?f:{...f,content:H}}if(f.type!=="tool_result")return f;let J=this.toolNameByIdCache.get(f.tool_use_id),W=f.content;if(this.isReadTool(J)&&f.is_error!==!0){let H=this.getReadLocators(f);if(H.length>0){let Q=H.filter((Z)=>this.isOutdatedReadLocator(Z,f.tool_use_id));if(Q.length>0)W=this.replaceOutdatedReadContent(W,Q)}}if(this.shouldTruncateTool(J))W=this.truncateToolResultContent(W);return W===f.content?f:{...f,content:W}}reindex(f){let $=this.indexedMessageCount===0||f.length>=this.indexedMessageCount&&f[this.indexedMessageCount-1]===this.indexedTailRef;if(f.length<this.indexedMessageCount||!$)this.resetIndexes();for(let J=this.indexedMessageCount;J<f.length;J++){let W=f[J];if(!Array.isArray(W.content))continue;for(let H=0;H<W.content.length;H++){let Q=W.content[H];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${H}`);else if(Q.type==="tool_use"){let Z=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,Z),this.isReadTool(Z)){let j=this.extractLocatorsFromReadToolInput(Q.input);if(j.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,j)}}else if(Q.type==="tool_result"){let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(Z)||Q.is_error===!0)continue;let j=this.getReadLocators(Q);for(let P of j)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(P),Q.tool_use_id),this.isFullFileRead(P))this.latestFullContentOwnerByPathCache.set(P.path,Q.tool_use_id)}}}this.indexedMessageCount=f.length,this.indexedTailRef=f.length>0?f[f.length-1]:void 0}addMissingToolResults(f){let $=this.collectToolResultIds(f),J=[],W=new Map,H=!1,Q=()=>{if(W.size===0)return;Z(this.createMissingToolResultMessage(W)),W.clear(),H=!0},Z=(j)=>{let P=J.at(-1);if(this.shouldMergeUserAfterToolResults(P,j)){J[J.length-1]={...P,content:[...P.content,...this.contentBlocksForUserMerge(j.content)]},H=!0;return}J.push(j)};for(let j of f){if(this.isToolResultOnlyMessage(j)){if(Z(this.appendMissingToolResults(j,W)),W.size>0)W.clear(),H=!0;continue}if(Array.isArray(j.content)){let P=j.content.filter((V)=>V.type==="tool_result"),X=j.content.filter((V)=>V.type!=="tool_result");if(P.length>0){let V=this.appendMissingToolResults({...j,role:"user",content:P},W);if(Z(V),W.size>0)W.clear();H=!0}if(X.length>0||P.length===0){if(P.length===0)Q();let V=P.length>0?{...j,content:X}:j;if(Z(V),V.role==="assistant")this.trackMissingToolCalls(V,$,W)}continue}Q(),Z(j)}return Q(),H?J:f}appendMissingToolResults(f,$){if($.size===0||!Array.isArray(f.content))return f;return{...f,role:"user",content:[...f.content,...this.createMissingToolResultBlocks($)]}}shouldMergeUserAfterToolResults(f,$){return f?.role==="user"&&$.role==="user"&&this.isToolResultOnlyMessage(f)&&this.contentBlocksForUserMerge($.content).length>0}contentBlocksForUserMerge(f){return typeof f==="string"?f.length>0?[{type:"text",text:f}]:[]:f}collectToolResultIds(f){let $=new Set;for(let J of f){if(!Array.isArray(J.content))continue;for(let W of J.content)if(W.type==="tool_result")$.add(W.tool_use_id)}return $}isToolResultOnlyMessage(f){return f.role==="user"&&Array.isArray(f.content)&&f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}trackMissingToolCalls(f,$,J){if(!Array.isArray(f.content))return;for(let W of f.content){if(W.type!=="tool_use"||$.has(W.id))continue;J.set(W.id,W.name)}}createMissingToolResultMessage(f){return{role:"user",content:this.createMissingToolResultBlocks(f)}}createMissingToolResultBlocks(f){return Array.from(f,([$,J])=>({type:"tool_result",tool_use_id:$,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText(f){return f?`${Y7} Tool: ${f}.`:Y7}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators(f){let $=f,J=this.readResultLocatorCache.get($);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent(f.content),this.readResultLocatorCache.set($,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get(f.tool_use_id)??[]}extractLocatorsFromReadToolInput(f){if(!f||typeof f!=="object")return[];let $=f,J=[],W=this.extractLocatorFromReadRequest($);if(W)J.push(W);if(Array.isArray($.files))for(let H of $.files){let Q=this.extractLocatorFromReadRequest(H);if(Q)J.push(Q)}if(Array.isArray($.file_paths)){for(let H of $.file_paths)if(typeof H==="string"&&H.length>0)J.push({path:H,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent(f){if(typeof f==="string")return this.tryParseReadLocators(f);for(let $ of f){if($.type!=="text")continue;let J=this.tryParseReadLocators($.text);if(J.length>0)return J}return[]}tryParseReadLocators(f){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(f))}catch{return[]}}extractLocatorsFromParsedReadResult(f){if(Array.isArray(f)){let J=[];for(let W of f){let H=this.extractLocatorFromResultEntry(W);if(H)J.push(H)}return this.dedupeReadLocators(J)}let $=this.extractLocatorFromResultEntry(f);return $?[$]:[]}extractLocatorFromReadRequest(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(!J)return;return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)}}extractLocatorFromResultEntry(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(J)return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)};if(typeof $.query==="string"&&$.query.length>0)return this.parseReadQuery($.query);return}extractPath(f){let $=[f.path,f.file_path,f.filePath];for(let J of $)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber(f){return typeof f==="number"&&Number.isInteger(f)?f:null}parseReadQuery(f){let $=/^(.*):(\d+)-(EOF|\d+)$/.exec(f);if(!$)return{path:f,startLine:null,endLine:null};return{path:$[1],startLine:Number($[2]),endLine:$[3]==="EOF"?null:Number($[3])}}dedupeReadLocators(f){let $=new Map;for(let J of f)$.set(this.toReadLocatorKey(J),J);return Array.from($.values())}toReadLocatorKey(f){if(this.isFullFileRead(f))return f.path;return`${f.path}:${f.startLine??1}-${f.endLine??"EOF"}`}isFullFileRead(f){return f.startLine==null&&f.endLine==null}isOutdatedReadLocator(f,$){let J=this.latestFullContentOwnerByPathCache.get(f.path);if(J&&J!==$)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(f))!==$}replaceOutdatedReadContent(f,$){let J=new Set($.map((Q)=>this.toReadLocatorKey(Q))),W=new Set($.map((Q)=>Q.path));if(typeof f==="string")return this.replaceOutdatedInString(f,J)??F$;let H=0;for(let Q of f)if(Q.type==="text")H+=this.countOutdatedImageEntries(Q.text,J);return f.map((Q)=>{if(Q.type==="file"){if(!W.has(Q.path))return Q;return{...Q,content:F$}}if(Q.type==="image"){if(H===0)return Q;return H-=1,{type:"text",text:F$}}if(Q.type!=="text")return Q;let Z=this.replaceOutdatedInString(Q.text,J);if(Z===null)return{...Q,text:F$};return Z===Q.text?Q:{...Q,text:Z}})}countOutdatedImageEntries(f,$){let J;try{J=JSON.parse(f)}catch{return 0}let W=Array.isArray(J)?J:[J],H=0;for(let Q of W){if(!Q||typeof Q!=="object")continue;let Z=Q,j=this.extractLocatorFromResultEntry(Z);if(!j)continue;if(!$.has(this.toReadLocatorKey(j)))continue;if(Z.result==="Successfully read image"||Z.content==="Successfully read image")H+=1}return H}replaceOutdatedInString(f,$){let J;try{J=JSON.parse(f)}catch{return null}let W=Array.isArray(J)?J.map((H)=>this.replaceOutdatedReadEntry(H,$)):this.replaceOutdatedReadEntry(J,$);return JSON.stringify(W)}replaceOutdatedReadEntry(f,$){if(!f||typeof f!=="object")return f;let J=this.extractLocatorFromResultEntry(f);if(!J||!$.has(this.toReadLocatorKey(J)))return f;let W={...f};if(typeof W.result==="string")W.result=F$;else if(typeof W.content==="string")W.content=F$;else W.result=F$;return W}isReadTool(f){return!!f&&LB.has(f)}shouldTruncateTool(f){return!!f&&this.targetToolNames.has(f)}truncateToolResultContent(f){if(typeof f==="string")return this.truncateMiddle(f);return f.map(($)=>{if($.type==="file"){let W=this.truncateMiddle($.content);return W===$.content?$:{...$,content:W}}if($.type!=="text")return $;let J=this.truncateMiddle($.text);return J===$.text?$:{...$,text:J}})}truncateMiddle(f){return bW(f,this.maxToolResultChars,zB)}truncateToTotalTextBudget(f){if(this.maxTotalTextBytes<=0)return f;let $=this.countMessageTextBytes(f);if($<=this.maxTotalTextBytes)return f;let J=f.map((H)=>{if(!Array.isArray(H.content))return H;return{...H,content:H.content.map((Q)=>qB(Q))}}),W=this.collectTruncationCandidates(J);for(let H of W){if($<=this.maxTotalTextBytes)break;let Q=H.byteLength;if(Q<=V7)continue;let Z=$-this.maxTotalTextBytes,j=Math.max(V7,Q-Z),P=NB(H.get(),j,OB);H.set(P),$-=Q-Kf(P)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=Kf(J.content);continue}for(let W of J.content)if(W.type==="text")$+=Kf(W.text);else if(W.type==="thinking")$+=Kf(W.thinking);else if(W.type==="file")$+=Kf(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")$+=Kf(W.content);else for(let H of W.content)if(H.type==="text")$+=Kf(H.text);else if(H.type==="file")$+=Kf(H.content)}}return $}collectTruncationCandidates(f){let $=[];for(let J of f){if(!Array.isArray(J.content))continue;for(let W of J.content){if(W.type!=="tool_result")continue;let H=this.toolNameByIdCache.get(W.tool_use_id);if(!this.shouldTruncateTool(H))continue;if(typeof W.content==="string"){$.push({byteLength:Kf(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")$.push({byteLength:Kf(Q.text),get:()=>Q.text,set:(Z)=>{Q.text=Z}});else if(Q.type==="file")$.push({byteLength:Kf(Q.content),get:()=>Q.content,set:(Z)=>{Q.content=Z}})}}return $.sort((J,W)=>W.byteLength-J.byteLength)}}function Kf(f){return Buffer.byteLength(f,"utf8")}function bW(f,$,J){if(f.length<=$)return f;let W=J(f.length-$),H=Math.max(0,Math.floor(($-W.length)/2)),Q=Math.max(0,f.length-H*2),Z=J(Q),j=Math.max(0,Math.floor(($-Z.length)/2)),P=f.slice(0,j),X=j>0?f.slice(-j):"";return`${P}${Z}${X}`}function NB(f,$,J){if(Kf(f)<=$)return f;let W=0,H=f.length,Q=bW(f,0,J);while(W<=H){let Z=W+H>>>1,j=bW(f,Z,J);if(Kf(j)<=$)Q=j,W=Z+1;else H=Z-1}return Q}function qB(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function CW(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class EW{messages=[];conversationId=CW();sessionStarted=!1;constructor(f){if((f?.length??0)>0)this.restore(f??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(f){this.messages.push(f)}appendMessages(f){if(f.length===0)return;this.messages.push(...f)}replaceMessages(f){this.messages=[...f]}resetForRun(){this.messages=[],this.conversationId=CW(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=CW(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function bB(f){let $=CB(f.content),J=[],W=f.id??kB(),H=0,Q=[],Z=()=>{if(Q.length===0)return;let j=H===0?W:`${W}_part_${H}`;H+=1,J.push({id:j,role:f.role,content:Q.map(EB),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:B7(f.metrics)}),Q=[]};if($.length===0)return J.push({id:W,role:f.role,content:[],createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:B7(f.metrics)}),J;for(let j of $){if(j.type!=="tool_result"){Q.push(j);continue}Z(),J.push({id:`${W}_tool_${j.tool_use_id}`,role:"tool",content:[F7(j)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return Z(),J}function S4(f){return f.flatMap(bB)}function wB(f){let $=f.content.map(y7).filter((J)=>J!==void 0);return{id:f.id,role:f.role==="tool"?"user":f.role,content:$,ts:f.createdAt,metadata:f.metadata,modelInfo:f.modelInfo,metrics:SB(f.metrics)}}function P1(f){return f.map(wB)}function R7(f){let $=[];for(let J of f){let W=J.content.map(y7).filter((Z)=>Z!==void 0),H=J.role==="tool"?"user":J.role,Q=$[$.length-1];if(H==="user"&&W.length>0&&W.every((Z)=>Z.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((Z)=>Z.type==="tool_result")){Q.content.push(...W);continue}$.push({role:H,content:W})}return $}function CB(f){if(typeof f==="string")return f.length>0?[{type:"text",text:f}]:[];return[...f]}function EB(f){switch(f.type){case"text":return{type:"text",text:f.text};case"thinking":return{type:"reasoning",text:f.thinking,metadata:f.signature?{signature:f.signature,details:f.details}:f.details?{details:f.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:f.data}};case"image":return{type:"image",image:f.data,mediaType:f.mediaType};case"file":return{type:"file",path:f.path,content:f.content};case"tool_use":return{type:"tool-call",toolCallId:f.id,toolName:f.name,input:f.input,metadata:f.signature?{signature:f.signature}:void 0};case"tool_result":return F7(f)}}function F7(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:"",output:f.content,isError:f.is_error}}function y7(f){switch(f.type){case"text":return{type:"text",text:f.text};case"reasoning":{if(f.redacted===!0)return{type:"redacted_thinking",data:f.metadata?.data??""};let $=f.metadata;return{type:"thinking",thinking:f.text,signature:$?.signature,details:$?.details}}case"image":return typeof f.image==="string"?{type:"image",data:f.image,mediaType:f.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:f.path,content:f.content};case"tool-call":return{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.input??{},signature:f.metadata?.signature};case"tool-result":{let $=f.output,J=typeof $==="string"?$:Array.isArray($)?$:JSON.stringify($);return{type:"tool_result",tool_use_id:f.toolCallId,content:J,is_error:f.isError}}}}function B7(f){if(!f)return;return{inputTokens:f.inputTokens??0,outputTokens:f.outputTokens??0,cacheReadTokens:f.cacheReadTokens??0,cacheWriteTokens:f.cacheWriteTokens??0,cost:f.cost}}function SB(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var A7=0;function kB(){return A7+=1,`msg_${Date.now().toString(36)}_${A7.toString(36)}`}function K7(f){let{agentConfig:$}=f,J=mB($),W=IB($),H=f.hooks,Q=xB($.maxParallelToolCalls);return{sessionId:f.sessionId??$.sessionId,agentId:f.agentId,conversationId:f.conversationId,parentAgentId:f.parentAgentId,agentRole:f.agentRole,systemPrompt:f.systemPrompt??$.systemPrompt,messageModelInfo:W,model:f.model,modelOptions:J,tools:f.tools,hooks:H,prepareTurn:f.prepareTurn,consumePendingUserMessage:$.consumePendingUserMessage,plugins:f.plugins,logger:f.logger??$.logger,telemetry:f.telemetry??gB($.telemetry),initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:Q,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function mB(f){let $={};if(f.thinking!==void 0)$.thinking=f.thinking;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;if(f.maxTokensPerTurn!==void 0)$.maxTokensPerTurn=f.maxTokensPerTurn;if(f.apiTimeoutMs!==void 0)$.apiTimeoutMs=f.apiTimeoutMs;return Object.keys($).length>0?$:void 0}function IB(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function xB(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function gB(f){if(!f)return;return{capture:($,J)=>{f.capture({event:$,properties:J})}}}function vB(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function uB(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function SW(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(SW);let $={};for(let J of Object.keys(f).sort())$[J]=SW(f[J]);return $}function cB(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(SW(f))}catch{return String(f)}}function dB(f,$,J,W){if($===f.lastToolName&&J===f.lastToolSignature)f.consecutiveIdenticalCount++;else f.consecutiveIdenticalCount=1;return f.lastToolName=$,f.lastToolSignature=J,{softWarning:f.consecutiveIdenticalCount===W.softThreshold,hardEscalation:f.consecutiveIdenticalCount>=W.hardThreshold}}var U7={softThreshold:3,hardThreshold:5};class kW{config;state=vB();constructor(f){this.config={softThreshold:f?.softThreshold??U7.softThreshold,hardThreshold:f?.hardThreshold??U7.hardThreshold}}inspect(f){let $=cB(f.input),J=dB(this.state,f.name,$,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){uB(this.state)}}class mW{consecutiveMistakes=0;options;constructor(f){this.options=f}async record(f){let $=this.options.maxConsecutiveMistakes,J=f.forceAtLimit&&$?$:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let W=f.details?.trim()||`consecutive mistake (${f.reason})`;if(this.options.emit({type:"error",error:Error(W),recoverable:!0,iteration:f.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:f.iteration,reason:f.reason,details:f.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!$||J<$)return{action:"continue"};let H=await lB({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details},this.options.onLimitReached);if(H.action==="continue"){let Q=H.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,f.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:H.reason?.trim()||void 0,message:rB({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details,stopReason:H.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function rB(f){let $=[`Stopped after ${f.consecutiveMistakes}/${f.maxConsecutiveMistakes} consecutive mistakes (${f.reason}) at iteration ${f.iteration}.`],J=f.details?.trim();if(J)$.push(`Error: ${J}`);let W=f.stopReason?.trim();if(W)$.push(`Decision: ${W}`);return $.push("Session state was preserved. Send a new prompt to resume from the latest state."),$.join(" ")}async function lB(f,$){if(!$)return{action:"stop",reason:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`};try{return await $(f)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`}}}function pB(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function iB(f){let $=f.content.filter((J)=>J.type==="reasoning");if($.length===0)return;return{reasoning:$.map((J)=>J.text).join(""),redacted:$.some((J)=>J.redacted===!0)}}function nB(f){return f.content.find(($)=>$.type==="tool-result")}function aB(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function tB(f){if(!f||f.isError!==!0)return;if(typeof f.output==="string")return f.output;if(f.output instanceof Error)return f.output.message;try{return JSON.stringify(f.output)}catch{return String(f.output)}}class IW{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate(f){switch(f.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:f.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:f.iteration,hadToolCalls:f.toolCallCount>0,toolCallCount:f.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:f.text,accumulated:f.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:f.text,redacted:f.redacted===!0}];case"assistant-message":return this.translateAssistantMessage(f.message);case"tool-started":return this.translateToolStarted(f);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,update:f.update}];case"tool-finished":return this.translateToolFinished(f);case"usage-updated":return this.translateUsage(f.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:f.message,reason:f.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:f.metadata}];case"run-finished":return this.translateRunFinished(f.result);case"run-failed":return[{type:"error",error:f.error,recoverable:!1,iteration:f.snapshot.iteration}];default:return f}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage(f){let $=[],J=pB(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let W=iB(f);if(W!==void 0)$.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return $}translateToolStarted(f){return this.toolStartedAt.set(f.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,input:f.toolCall.input}]}translateToolFinished(f){let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=$===void 0?void 0:Date.now()-$;this.toolStartedAt.delete(f.toolCall.toolCallId);let W=nB(f.message),H=W?.output,Q=tB(W);return[{type:"content_end",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,output:H,error:Q,durationMs:J}]}translateUsage(f){let $=f.inputTokens-this.lastUsage.inputTokens,J=f.outputTokens-this.lastUsage.outputTokens,W=f.cacheReadTokens-this.lastUsage.cacheReadTokens,H=f.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,j=(f.totalCost??0)-Q;return this.lastUsage={inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost},[{type:"usage",inputTokens:Math.max(0,$),outputTokens:Math.max(0,J),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:H===0?void 0:Math.max(0,H),cost:j===0?void 0:j,totalInputTokens:f.inputTokens,totalOutputTokens:f.outputTokens,totalCacheReadTokens:f.cacheReadTokens===0?void 0:f.cacheReadTokens,totalCacheWriteTokens:f.cacheWriteTokens===0?void 0:f.cacheWriteTokens,totalCost:f.totalCost}]}translateRunFinished(f){let $={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens===0?void 0:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens===0?void 0:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost};return[{type:"done",reason:aB(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function HA(f){if(typeof f==="string")return f;if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}}async function QA(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function ZA(f,$){let J=f.trim(),W=$.map((H)=>H.trim()).filter(Boolean).join(`
130
+
131
+ `);if(J&&W)return`${J}
132
+
133
+ ${W}`;return J||W}function jA(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return{};return{beforeRun:async(J)=>{for(let W of $){let H=await W.beforeRun?.(J);if(H?.stop)return H}return},afterRun:async(J)=>{for(let W of $)await W.afterRun?.(J)},beforeModel:async(J)=>{let W=J.request,H;for(let Q of $){let Z=await Q.beforeModel?.({...J,request:W});if(!Z)continue;if(Z.stop)return Z;H={...H,...Z,options:{...H?.options??{},...Z.options??{}}},W={...W,...Z.messages?{messages:Z.messages}:{},...Z.tools?{tools:Z.tools}:{},...Z.options?{options:{...W.options??{},...Z.options}}:{}}}return H},afterModel:async(J)=>{for(let W of $){let H=await W.afterModel?.(J);if(H?.stop)return H}return},beforeTool:async(J)=>{let W=J.input,H;for(let Q of $){let Z=await Q.beforeTool?.({...J,input:W});if(!Z)continue;if(Z.stop||Z.skip)return Z;if(H={...H,...Z},Object.hasOwn(Z,"input"))W=Z.input}return H},afterTool:async(J)=>{let W=J.result,H;for(let Q of $){let Z=await Q.afterTool?.({...J,result:W});if(!Z)continue;if(Z.stop)return Z;if(H={...H,...Z},Z.result)W=Z.result}return H},onEvent:async(J)=>{for(let W of $)await W.onEvent?.(J)}}}class m0{config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new IW;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor(f,$={}){this.config=f,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=f.parentAgentId,this.logger=$.logger??f.logger,this.telemetry=$.telemetry??f.telemetry,this.createAgentRuntimeImpl=$.createAgentRuntimeImpl??JA,this.conversation=new EW(f.initialMessages),this.messageBuilder=new wW,this.contributionRegistry=WA({extensions:f.extensions?[...f.extensions]:[],setupContext:{session:f.extensionContext?.session,client:f.extensionContext?.client,user:f.extensionContext?.user,workspaceInfo:f.extensionContext?.workspace,automation:f.extensionContext?.automation,logger:f.extensionContext?.logger??this.logger,telemetry:f.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=f.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new mW({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,Z,j)=>PA(this.logger,Q,Z,j),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,Z)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let W=f.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let H=W===!1||W===void 0?void 0:W;this.loopTracker=new kW(H)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools(f){if(f.length===0)return;let $=new Set(this.config.tools.map((W)=>W.name)),J=[...this.config.tools];for(let W of f)if(!$.has(W.name))J.push(W),$.add(W.name);this.config={...this.config,tools:J}}updateConnection(f){let $={...this.config};if(f.providerId!==void 0)$.providerId=f.providerId;if(f.modelId!==void 0)$.modelId=f.modelId;if(f.apiKey!==void 0)$.apiKey=f.apiKey;if(f.baseUrl!==void 0)$.baseUrl=f.baseUrl;if(f.headers!==void 0)$.headers=f.headers;if(f.providerConfig!==void 0)$.providerConfig=f.providerConfig;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinking!==void 0)$.thinking=f.thinking;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;this.config=$}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore(f){this.conversation.restore(f),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}abort(f){let $=typeof f==="string"?f:f instanceof Error?f.message:f===void 0?void 0:String(f);if(this.abortRequested=!0,this.abortReason=$,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort($)}async shutdown(f,$){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run(f,$,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!1})}continue(f,$,J){return this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let f=[];for(let $ of this.contributionRegistry.getRegisteredRules()){let J=await QA($);if(J)f.push(J)}return ZA(this.config.systemPrompt,f)}executeRun(f){let $;return $=this.executeRunInternal(f).finally(()=>{if(this.activeRunPromise===$)this.activeRunPromise=null}),this.activeRunPromise=$,$}async executeRunInternal(f){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let $=new Date,J=f.userMessage;if(J!==void 0){let F=await VA(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let W=await this.composeSystemPrompt(),H=P7(this.config,this.logger),Q=this.contributionRegistry.getRegisteredTools(),Z=new Map;for(let F of Q)Z.set(F.name,F);for(let F of this.config.tools)Z.set(F.name,F);let j=this.conversation.getConversationId(),P=T7(this.config),X=Array.from(Z.values()),V=S4(this.conversation.getMessages()),Y=K7({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:j,parentAgentId:this.parentAgentId,model:H,logger:this.logger,tools:X,toolContextMetadata:{modelSupportsImages:P?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(P,X),initialMessages:V,systemPrompt:W}),B=this.createAgentRuntimeImpl(Y);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let A=B.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,U;try{if(f.isContinue)R=await B.continue(void 0);else R=await B.run("")}catch(F){U=F instanceof Error?F:Error(String(F))}finally{A();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=P1(R.messages);this.conversation.replaceMessages(F)}let y=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:U,startedAt:$,endedAt:y})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch(f){if(this.config.hookErrorMode==="throw")throw f;this.emitLegacyEvent({type:"error",error:f instanceof Error?f:Error(String(f)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let f=jA([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map(($)=>$.hooks)]);return{...f,beforeModel:async($)=>{let J=await f.beforeModel?.($);if(J?.stop)return J;let W=J?.messages??$.request.messages,H=await this.prepareMessagesForModelRequest(W);return{...J,messages:H}}}}createRuntimePrepareTurn(f,$){let J=this.config.prepareTurn;if(!J)return;return async(W)=>{let H=P1(W.messages),Q=await this.prepareProviderMessagesForApi(H),Z=await J({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:H,apiMessages:Q,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:$,model:{id:this.config.modelId,provider:this.config.providerId,info:f},emitStatusNotice:W.emitStatusNotice});if(!Z)return;return{...Z.messages?{messages:S4(Z.messages)}:{},...Z.systemPrompt!==void 0?{systemPrompt:Z.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(R7(f));return S4($)}async prepareProviderMessagesForApi(f){let $=f,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of J)$=await W.build($);return this.messageBuilder.buildForApi($)}handleRuntimeEvent(f){switch(f.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage(f.snapshot.messages,[f.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set(f.toolCall.toolCallId,new Date),this.toolInputs.set(f.toolCall.toolCallId,f.toolCall.input),this.inspectLoopForToolCall(f.toolCall.toolName,f.toolCall.input,f.iteration);break}case"tool-finished":{let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=new Date,W=this.toolInputs.get(f.toolCall.toolCallId);this.toolStartedAt.delete(f.toolCall.toolCallId),this.toolInputs.delete(f.toolCall.toolCallId);let H=f.message.content.find((P)=>P.type==="tool-result"),Q=H?.type==="tool-result"&&H.isError===!0,Z=Q?HA(H?.type==="tool-result"?H.output:void 0):void 0,j={id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:W,output:H?.type==="tool-result"?H.output:void 0,error:Z,durationMs:$===void 0?0:J.getTime()-$.getTime(),startedAt:$??J,endedAt:J};if(this.currentRunToolCalls.push(j),Q){if(this.currentTurnFailedTools+=1,Z)this.currentTurnFailureDetails.push(`[${f.toolCall.toolName}] ${Z}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let $=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if($>0&&J===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:f.iteration,reason:"tool_execution_failed",details:`${$} tool call(s) failed${W?`: ${W}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost};break}default:break}for(let $ of this.eventAdapter.translate(f))this.emitLegacyEvent($)}syncConversationFromRuntimeMessage(f,$){if(f.length>0){this.conversation.replaceMessages(P1(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((H)=>H.id).filter((H)=>typeof H==="string")),W=P1($).filter((H)=>!H.id||!J.has(H.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent(f){for(let $ of this.listeners)try{$(f)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall(f,$,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:f,input:$});if(W.kind==="ok")return;if(W.kind==="soft"){if(W.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:W.message??`Detected repeated tool calls to \`${f}\`; stopping to avoid a loop.`})}enqueueMistakeRecord(f){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let $=await this.mistakeTracker.record(f);if($.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:$.message}]}),this.activeRuntime?.abort($.reason??$.message)})}buildLegacyResult(f){let{runResult:$,thrownError:J,startedAt:W,endedAt:H}=f,Q=H.getTime()-W.getTime(),Z=J?"error":XA($),j=$?.outputText||($?.status==="failed"?$.error?.message:void 0)||"",P=$?{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost}:this.currentRunUsage,X=$?P1($.messages):this.conversation.getMessages(),V=T7(this.config);if(J)throw J;return{text:j,usage:P,messages:X,toolCalls:this.currentRunToolCalls,iterations:$?.iterations??0,finishReason:Z,model:{id:this.config.modelId,provider:this.config.providerId,info:V},startedAt:W,endedAt:H,durationMs:Q}}}function PA(f,$,J,W){if(!f)return;if($==="debug"){f.debug(J,W);return}if($==="error"&&f.error){f.error(J,W);return}let H=$==="warn"?"warn":$==="error"?"error":"info";f.log(J,{...W,severity:H})}function XA(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function VA(f,$,J,W){let{buildInitialUserContent:H}=await Promise.resolve().then(() => G7);return H(f,$,J,W)}function T7(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=qW(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as h7}from"@cline/shared";function D7(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return h7({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
134
+ ${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function M7(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return h7({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function X1(f){let $={...f};return{getRuntimeConfig:()=>$,getConnectionConfig:()=>({providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking}),updateConnectionDefaults:(J)=>{$={...$,...J}}}}function y$(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?D7(f.prompt,$):M7(f.prompt,$);return{...f.configProvider.getConnectionConfig(),systemPrompt:J,tools:f.tools,maxIterations:f.maxIterations??$.maxIterations,parentAgentId:f.parentAgentId,abortSignal:f.abortSignal,onEvent:f.onEvent,hooks:$.hooks,extensions:$.extensions,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval,logger:$.logger,role:f.role}}function V1(f){let $=y$(f),J=new m0($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var AA=xW.object({systemPrompt:xW.string().describe("System prompt defining the sub-agent's behavior"),task:xW.string().describe("Task for the sub-agent to complete")});function I0(f){return YA({name:"spawn_agent",description:"Spawn a sub-agent with a custom system prompt for specialized tasks. Use when delegating work that benefits from focused expertise.",inputSchema:BA(AA),execute:async($,J)=>{let W=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],H=V1({kind:"subagent",prompt:$.systemPrompt,configProvider:f.configProvider,tools:W,maxIterations:f.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),Q=H.getAgentId(),Z=H.getConversationId(),j=J.agentId;if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$})}catch{}try{let P=await H.run($.task),X={text:P.text,iterations:P.iterations,finishReason:P.finishReason,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,result:X})}catch{}return X}catch(P){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,error:P instanceof Error?P:Error(String(P))})}catch{}throw P}},timeoutMs:300000,retryable:!1})}import{createTool as Wf,TEAM_AWAIT_TIMEOUT_MS as RA,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as FA,TEAM_RUN_TEXT_PREVIEW_LIMIT as yA,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as KA,TeamAttachOutcomeFragmentInputSchema as _7,TeamAwaitRunsInputSchema as L7,TeamBroadcastInputSchema as z7,TeamBroadcastToolResultSchema as UA,TeamCancelRunInputSchema as O7,TeamCancelRunToolResultSchema as GA,TeamCleanupInputSchema as N7,TeamCleanupToolResultSchema as TA,TeamCreateOutcomeInputSchema as q7,TeamCreateOutcomeToolResultSchema as hA,TeamFinalizeOutcomeInputSchema as b7,TeamFinalizeOutcomeToolResultSchema as DA,TeamListOutcomesInputSchema as w7,TeamListRunsInputSchema as C7,TeamMailboxMessageToolResultSchema as MA,TeamMissionLogInputSchema as E7,TeamMissionLogToolResultSchema as _A,TeamOutcomeFragmentToolResultSchema as S7,TeamOutcomeToolResultSchema as LA,TeamReadMailboxInputSchema as k7,TeamReviewOutcomeFragmentInputSchema as m7,TeamRunTaskInputSchema as I7,TeamRunTaskToolResultSchema as gW,TeamRunToolSummarySchema as vW,TeamSendMessageInputSchema as x7,TeamSendMessageToolResultSchema as zA,TeamShutdownTeammateInputSchema as g7,TeamSimpleAgentStatusToolResultSchema as v7,TeamSpawnTeammateInputSchema as u7,TeamStatusInputSchema as c7,TeamStatusToolResultSchema as OA,TeamTaskInputSchema as d7,TeamTaskToolResultSchema as x2,validateWithZod as b,zodToJsonSchema as Hf}from"@cline/shared";function r7(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function K$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function NA(f){let $=f.result;if(!$)return;return{textPreview:r7($.text,yA),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function k4(f){return f?.toISOString()}function uW(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:r7(f.message,FA),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:k4(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:k4(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:k4(f.heartbeatAt),lastProgressAt:k4(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:NA(f)}}function qA(f){if(f.status==="failed")throw Error(`Run "${f.id}" failed${f.error?`: ${f.error}`:""}`);if(f.status==="cancelled")throw Error(`Run "${f.id}" was cancelled${f.error?`: ${f.error}`:""}`);if(f.status==="interrupted")throw Error(`Run "${f.id}" was interrupted${f.error?`: ${f.error}`:""}`)}var Y1=["team_spawn_teammate","team_shutdown_teammate","team_status","team_task","team_run_task","team_cancel_run","team_list_runs","team_await_runs","team_send_message","team_broadcast","team_read_mailbox","team_mission_log","team_cleanup","team_create_outcome","team_attach_outcome_fragment","team_review_outcome_fragment","team_finalize_outcome","team_list_outcomes"];function l7(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...U$({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:y$({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function B1(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,W=U$({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!0,includeSpawnTool:f.includeLeadSpawnTool,includeManagementTools:f.includeLeadManagementTools,onLeadToolsUnlocked:f.onLeadToolsUnlocked}),H=[];for(let Q of f.restoredTeammates??[]){if(f.runtime.isTeammateActive(Q.agentId))continue;l7({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:Q}),H.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:H}}function U$(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,W=f.includeManagementTools??!0,H=[];if(J)H.push(Wf({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Hf(u7),execute:async(Z)=>{let j=b(u7,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!$)throw Error("Spawning teammates is disabled in this context.");let P={agentId:j.agentId,rolePrompt:j.rolePrompt};if(l7({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:P}),!W)f.onLeadToolsUnlocked?.(U$({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return b(v7,{agentId:j.agentId,status:"spawned"})}}));if(!W)return H;H.push(Wf({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Hf(g7),execute:async(Z)=>{let j=b(g7,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return f.runtime.shutdownTeammate(j.agentId,j.reason),b(v7,{agentId:j.agentId,status:"stopped"})}})),H.push(Wf({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Hf(c7),execute:async(Z)=>{return b(c7,Z),b(OA,f.runtime.getSnapshot())}})),H.push(Wf({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:Hf(d7),execute:async(Z)=>{let j=b(d7,Z);switch(j.action){case"create":{let P=new Set(KA.create??[]),X=Object.entries(Z).filter(([Y,B])=>P.has(Y)&&B!=null).map(([Y])=>Y),V=f.runtime.createTask({title:K$(j.title,"title"),description:K$(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:f.requesterId});return b(x2,{action:"create",taskId:V.id,status:V.status,...X.length>0?{ignoredFields:X,note:`Ignored fields for action=create: ${X.join(", ")}`}:{}})}case"list":return b(x2,{action:"list",tasks:f.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let P=f.runtime.claimTask(K$(j.taskId,"taskId"),f.requesterId);return b(x2,{action:"claim",taskId:P.id,status:P.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let P=f.runtime.completeTask(K$(j.taskId,"taskId"),f.requesterId,K$(j.summary,"summary"));return b(x2,{action:"complete",taskId:P.id,status:P.status})}case"block":{let P=f.runtime.blockTask(K$(j.taskId,"taskId"),f.requesterId,K$(j.reason,"reason"));return b(x2,{action:"block",taskId:P.id,status:P.status})}}}}));let Q=new Map;return H.push(Wf({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Hf(I7),execute:async(Z)=>{let j=b(I7,Z);if(j.runMode==="async"){let V=f.runtime.startTeammateRun(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0});return b(gW,{agentId:j.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${j.agentId} and queued as ${V.id}.`,runId:V.id})}let P=Q.get(j.agentId);if(P){let V=await P;return b(gW,{...V,status:"joined",deduped:!0,message:`Task for ${j.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let X=f.runtime.routeToTeammate(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0}).then((V)=>b(gW,{agentId:j.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${j.agentId} and completed in sync mode.`,text:V.text,iterations:V.iterations})).finally(()=>{Q.delete(j.agentId)});return Q.set(j.agentId,X),await X}})),H.push(Wf({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Hf(O7),execute:async(Z)=>{let j=b(O7,Z),P=f.runtime.cancelRun(j.runId,j.reason);return b(GA,{runId:P.id,status:P.status})}})),H.push(Wf({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Hf(C7),execute:async(Z)=>b(vW.array(),f.runtime.listRuns(b(C7,Z)).map(uW))})),H.push(Wf({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:Hf(L7),timeoutMs:RA,execute:async(Z)=>{let j=b(L7,Z);if(j.runId){let V=await f.runtime.awaitRun(j.runId);return qA(V),b(vW,uW(V))}let P=await f.runtime.awaitAllRuns(),X=P.filter((V)=>["failed","cancelled","interrupted"].includes(V.status));if(X.length>0){let V=X.map((Y)=>`${Y.id}:${Y.status}${Y.error?`(${Y.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${V}`)}return b(vW.array(),P.map(uW))}})),H.push(Wf({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Hf(x7),execute:async(Z)=>{let j=b(x7,Z),P=f.runtime.sendMessage(f.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return b(zA,{id:P.id,toAgentId:P.toAgentId})}})),H.push(Wf({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Hf(z7),execute:async(Z)=>{let j=b(z7,Z),P=f.runtime.broadcast(f.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return b(UA,{delivered:P.length})}})),H.push(Wf({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Hf(k7),execute:async(Z)=>{let j=b(k7,Z);return b(MA.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:j.unreadOnly,markRead:!0}))}})),H.push(Wf({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Hf(E7),execute:async(Z)=>{let j=b(E7,Z),P=f.runtime.appendMissionLog({agentId:f.requesterId,taskId:j.taskId||void 0,kind:j.kind,summary:j.summary,evidence:j.evidence?.length?j.evidence:void 0,nextAction:j.nextAction||void 0});return b(_A,{id:P.id})}})),H.push(Wf({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Hf(N7),execute:async(Z)=>{if(b(N7,Z),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),b(TA,{status:"cleaned"})}})),H.push(Wf({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Hf(q7),execute:async(Z)=>{let j=b(q7,Z),P=f.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:f.requesterId});return b(hA,{outcomeId:P.id,status:P.status,requiredSections:P.requiredSections})}})),H.push(Wf({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Hf(_7),execute:async(Z)=>{let j=b(_7,Z),P=f.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:f.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return b(S7,{fragmentId:P.id,status:P.status})}})),H.push(Wf({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Hf(m7),execute:async(Z)=>{let j=b(m7,Z),P=f.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:f.requesterId,approved:j.approved});return b(S7,{fragmentId:P.id,status:P.status})}})),H.push(Wf({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Hf(b7),execute:async(Z)=>{let j=b(b7,Z),P=f.runtime.finalizeOutcome(j.outcomeId);return b(DA,{outcomeId:P.id,status:P.status})}})),H.push(Wf({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Hf(w7),execute:async(Z)=>{return b(w7,Z),b(LA.array(),f.runtime.listOutcomes())}})),H}function m4(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}function I4(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var bA=[{id:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:I0({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...Y1]}],wA={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function CA(f){return f==="plan"||f==="yolo"?f:"act"}function i7(f){let $=CA(f.mode),J=Nf[B0({mode:$})],W=j1(f.providerId??"",f.modelId??"",$,Z1);return{mode:$,flags:{...J,...W,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function p7(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=i7($);if(f==="spawn_agent")return J.enableSpawnAgent===!0;if(f==="teams")return J.enableAgentTeams===!0;if(f==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let W=wA[f];return W?J[W]===!0:!1}function EA(f,$){if(f.id==="editor"){let{flags:J}=i7($),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:p7(f.id,$),headlessToolNames:[W?"apply_patch":"editor"]}}return{...f,defaultEnabled:p7(f.id,$)}}function G$(f={}){return bA.map(($)=>EA($,f))}function x4(f={}){return G$(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function g4(f){if(!f.enabled)return new Set;let $=G$(f.availabilityContext),J=new Set($.map((W)=>W.id));if(!f.allowlist||f.allowlist.length===0)return new Set($.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of f.allowlist)if(!J.has(W))throw Error(`Unknown tool "${W}". Available tools: ${$.map((H)=>H.id).join(", ")}`);return new Set(f.allowlist)}function g2(f,$={}){return G$($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function v4(f,$={}){return g2(f,$)}function T$(f={}){let{executorOptions:$={},executors:J,...W}=f,H={...Q1($),...J??{}};return S0({...W,executors:H})}import{mkdirSync as gA,writeFileSync as vA}from"node:fs";import{dirname as uA}from"node:path";import{normalizeUserInput as cA}from"@cline/shared";import{nanoid as dA}from"nanoid";var a7={};N(a7,{sanitizeSessionToken:()=>h$,parseTeamTaskSubSessionId:()=>R1,parseSubSessionId:()=>u2,makeTeamTaskSubSessionId:()=>v2,makeSubSessionId:()=>A1,deriveSubsessionStatus:()=>c2});import{nanoid as mA}from"nanoid";function h$(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function A1(f,$){let J=h$(f),W=h$($),H=`${J}__${W}`;return H.length>180?H.slice(0,180):H}function v2(f,$){let J=h$(f),W=h$($);return`${J}__teamtask__${W}__${mA(6)}`}function R1(f){let J=f.indexOf("__teamtask__");if(J<=0)return null;let W=f.slice(0,J),H=f.slice(J+12),Q=H.lastIndexOf("__");if(Q<=0)return null;let Z=H.slice(0,Q),j=H.slice(Q+2);if(!W||!Z||!j)return null;return{rootSessionId:W,agentId:Z,teamTaskId:j}}function u2(f){if(R1(f))return null;let $="__",J=f.indexOf($);if(J<=0)return null;let W=f.slice(0,J),H=f.slice(J+$.length);if(!W||!H)return null;return{rootSessionId:W,agentId:H}}function c2(f){switch(f.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let $=String(f.reason??"").toLowerCase();if($.includes("cancel")||$.includes("abort")||$.includes("interrupt"))return"cancelled";if($.includes("fail")||$.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as i}from"zod";var t7={};N(t7,{SessionSource:()=>Pf,SESSION_STATUSES:()=>d2});import{SESSION_STATUS_VALUES as IA}from"@cline/shared";var d2=IA,Pf={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var xA=i.enum(d2),Uf=i.object({version:i.literal(1),session_id:i.string().min(1),source:i.string().min(1),pid:i.number().int(),started_at:i.string().min(1),ended_at:i.string().min(1).optional(),exit_code:i.number().int().nullable().optional(),status:xA,interactive:i.boolean(),provider:i.string().min(1),model:i.string().min(1),cwd:i.string().min(1),workspace_root:i.string().min(1),team_name:i.string().min(1).optional(),enable_tools:i.boolean(),enable_spawn:i.boolean(),enable_teams:i.boolean(),prompt:i.string().optional(),metadata:i.record(i.string(),i.unknown()).optional(),messages_path:i.string().min(1).optional()});function s7(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function dW(f,$){let J=[...f??[],...$??[]];if(J.length===0)return;let W=[],H=new Set;for(let Q of J){if(H.has(Q.name))continue;H.add(Q.name),W.push(Q)}return W}function o7(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function A0(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function cW(f,$){let J={...f};J.id=A0(J.id)??dA();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,H={id:A0(W?.id)??A0(J.modelId)??A0($?.id),provider:A0(W?.provider)??A0(J.providerId)??A0($?.provider),family:A0(W?.family)??A0($?.family)};if(delete J.providerId,delete J.modelId,H.id&&H.provider)J.modelInfo={id:H.id,provider:H.provider,...H.family?{family:H.family}:{}};else delete J.modelInfo;return J}function u4(f){return f.map(($)=>cW($))}function c4(f,$,J=[]){let W=f.map((j,P)=>{let X=J[P],Y=X?.role===j.role&&JSON.stringify(X.content)===JSON.stringify(j.content)?{...X,...j}:{...j};return cW(Y)}),H=J.length,Q=[];for(let j=H;j<W.length;j+=1)if(W[j]?.role==="assistant")Q.push(j);if(Q.length===0){let j=[...W].reverse().findIndex((P)=>P.role==="assistant");if(j===-1)return W;Q.push(W.length-1-j)}let Z=Q[Q.length-1];for(let j of Q){let P=W[j],X=P.metrics;if(!X&&j===Z){let V=$.usage;X={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}W[j]={...cW(P,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...X?{metrics:X}:{},ts:P.ts??$.endedAt.getTime()}}return W}function r2(f){return{sessionId:f.sessionId,source:f.source,pid:f.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??void 0,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:f.parentSessionId??void 0,parentAgentId:f.parentAgentId??void 0,agentId:f.agentId??void 0,conversationId:f.conversationId??void 0,isSubagent:f.isSubagent,prompt:f.prompt??void 0,metadata:f.metadata??void 0,messagesPath:f.messagesPath??void 0,updatedAt:f.updatedAt}}var rA=120;function D$(f){let $=f?.trim();return $?$.slice(0,rA):void 0}function rW(f){let $=cA(f??"").trim();if(!$)return;return D$($.split(`
135
+ `)[0]?.trim())}function x0(f){if(!f)return;let $={...f},J=D$(typeof $.title==="string"?$.title:void 0);if(J)$.title=J;else delete $.title;return Object.keys($).length>0?$:void 0}function l2(f){let $=x0(f.metadata)??{},J=f.title!==void 0?D$(f.title):rW(f.prompt);if(J)$.title=J;return Object.keys($).length>0?$:void 0}function lW(f){let $=R1(f);if($)return{agent:"teammate",sessionId:$.rootSessionId,taskType:"team"};let J=u2(f);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:f}}function pW(f){return{version:1,updated_at:f.updatedAt,agent:f.context.agent,sessionId:f.context.sessionId,...f.context.taskType?{taskType:f.context.taskType}:{},messages:u4(f.messages),...f.systemPrompt?{system_prompt:f.systemPrompt}:{}}}function e7(f,$,J){gA(uA(f),{recursive:!0}),vA(f,`${JSON.stringify(pW({updatedAt:$,context:J,messages:[]}),null,2)}
136
+ `,"utf8")}function fQ(f,$){return Uf.parse({version:1,session_id:f.sessionId,source:f.source,pid:f.pid,started_at:f.startedAt,ended_at:$?.endedAt??f.endedAt??void 0,exit_code:$?.exitCode??f.exitCode??void 0,status:$?.status??f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName??void 0,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt??void 0,metadata:$?.metadata??f.metadata??void 0,messages_path:f.messagesPath??void 0})}async function $Q(f,$,J){let W=0;while(!0){let H=await f();if(H===void 0)return{updated:!1};let Q=await $(H);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(W+=1,W>=J)return Q;continue}return Q}}Gf();var ZQ={};N(ZQ,{summarizeUsageFromMessages:()=>a2,getCurrentContextSize:()=>iW,createInitialAccumulatedUsage:()=>u0,accumulateUsageTotals:()=>c0});function u0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function c0(f,$){return{inputTokens:f.inputTokens+Math.max(0,$.inputTokens??0),outputTokens:f.outputTokens+Math.max(0,$.outputTokens??0),cacheReadTokens:f.cacheReadTokens+Math.max(0,$.cacheReadTokens??0),cacheWriteTokens:f.cacheWriteTokens+Math.max(0,$.cacheWriteTokens??0),totalCost:f.totalCost+Math.max(0,$.totalCost??0)}}function y1(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function a2(f){let $=u0();for(let J of f){let W=J.metrics;if(!W)continue;$=c0($,{inputTokens:y1(W.inputTokens),outputTokens:y1(W.outputTokens),cacheReadTokens:y1(W.cacheReadTokens),cacheWriteTokens:y1(W.cacheWriteTokens),totalCost:y1(W.cost)})}return $}function iW(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let W=y1(J.metrics?.inputTokens);return W>0?W:void 0}return}function iA(f){if(!f||typeof f!=="object")return;let $=f,J=$.skill??$.skill_name??$.skillName;if(typeof J!=="string")return;let W=J.trim();return W.length>0?W:void 0}function nW(f){if(!f||typeof f!=="object")return{};let $=f;return{agentId:typeof $.agentId==="string"?$.agentId:void 0,conversationId:typeof $.conversationId==="string"?$.conversationId:void 0,parentAgentId:typeof $.parentAgentId==="string"?$.parentAgentId:void 0}}function U0(f){let $=f.agentId?.trim();if(!$)return;let J=f.parentAgentId?.trim()||void 0,W=f.teamRole,H="root";if(W==="teammate")H="team_teammate";else if(W==="lead")H="team_lead";else if(J)H="subagent";return{agentId:$,agentKind:H,conversationId:f.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:f.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:f.teamId?.trim()||void 0,teamName:f.teamName?.trim()||void 0,teamRole:W,teamAgentId:f.teamAgentId?.trim()||void 0}}function aW(f,$,J){let{sessionId:W,config:H,liveSession:Q,emit:Z}=f,j=H.telemetry,P=Q?.runtime.teamRuntime,X=J?.isPrimaryAgentEvent??!0,V=nW($),Y=U0({agentId:J?.agentId??V.agentId,conversationId:J?.conversationId??V.conversationId,parentAgentId:J?.parentAgentId??V.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??P?.getTeamId(),teamName:J?.teamName??P?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if($.type==="content_start"&&$.contentType==="tool"&&$.toolName==="skills"){let B=iA($.input);if(B)s4(j,{ulid:W,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:H.providerId,modelId:H.modelId,...Y})}if($.type==="content_end"&&$.contentType==="tool"){let B=$.toolName??"unknown",A=!$.error;if(t4(j,{ulid:W,tool:B,autoApproved:void 0,success:A,modelId:H.modelId,provider:H.providerId,...Y}),!A&&(B==="editor"||B==="apply_patch"))o4(j,{ulid:W,modelId:H.modelId,provider:H.providerId,errorType:$.error,...Y})}if($.type==="notice"&&$.reason==="api_error")i2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.message,...Y});if($.type==="error")i2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.error?.message??"unknown error",...Y});if($.type==="usage"&&X&&Q?.turnUsageBaseline)f.usageBySession.set(W,c0(Q.turnUsageBaseline,{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost})),F1(j,{ulid:W,provider:H.providerId,model:H.modelId,source:"assistant",mode:H.mode,...Y}),n4(j,{ulid:W,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:H.modelId,...Y});if($.type==="iteration_end"&&X)f.persistMessages(W,Q?.agent.getMessages()??[],Q?.config.systemPrompt);Z({type:"agent_event",payload:{sessionId:W,event:$,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(X?"lead":void 0):void 0}}),Z({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:o7($),ts:Date.now()}})}function d0(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as Hy}from"@cline/shared";function jQ(f){let $="";for(let J=0;J<f.length;J+=1)$+=String.fromCharCode(f[J]??0);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function nA(f){let J=new TextEncoder().encode(f),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function aA(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),jQ($)}async function H6(){let f=aA(),$=jQ(await nA(f));return{verifier:f,challenge:$}}function Q6(f){return f.endsWith("/")?f.slice(0,-1):f}function M$(f,$){return new URL($,`${Q6(f)}/`).toString()}function K1(f,$={}){let J=f.trim();if(!J)return{};try{let W=new URL(J);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:$.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if($.allowHashCodeState&&J.includes("#")){let[W,H]=J.split("#",2);return{code:W||void 0,state:H||void 0}}if(J.includes("code=")){let W=new URLSearchParams(J);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:$.includeProvider?W.get("provider")??void 0:void 0}}return{code:J}}function tA(f){if(typeof atob==="function")try{return atob(f)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from(f,"base64").toString("utf8")}catch{return null}return null}function Rf(f){if(!f)return null;try{let $=f.split(".");if($.length!==3)return null;let J=$[1];if(!J)return null;let W=J.replace(/-/g,"+").replace(/_/g,"/"),H=W.padEnd(W.length+(4-W.length%4)%4,"="),Q=tA(H);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function U1(f){try{let $=JSON.parse(f),J=$.error,W=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,H=typeof $.error_description==="string"?$.error_description:typeof $.message==="string"?$.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:W,message:H}}catch{return{}}}function _$(f,$){return Date.now()>=f.expires-$}async function G1(f){if(!f.onManualCodeInput){let Q=await f.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let $,J,W=f.onManualCodeInput().then((Q)=>{$=Q,f.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),f.cancelWait()}),H=await f.waitForCallback();if(J)throw J;if(H?.code||H?.error)return{code:H.code,state:H.state,provider:H.provider,error:H.error};if($)return K1($,f.parseOptions);if(await W,J)throw J;if($)return K1($,f.parseOptions);return{}}G0();import{existsSync as CR}from"node:fs";import{discoverPluginModulePaths as ER,resolveConfiguredPluginModulePaths as SR,resolvePluginConfigSearchPaths as kR}from"@cline/shared/storage";import{resolve as BR}from"node:path";import{normalizePluginManifest as AR}from"@cline/shared";import{existsSync as r0,readFileSync as eW}from"node:fs";import{builtinModules as $R,createRequire as yQ}from"node:module";import{dirname as Y6,extname as KQ,isAbsolute as JR,resolve as Ff}from"node:path";import{fileURLToPath as UQ}from"node:url";import{PLUGIN_FILE_EXTENSIONS as WR}from"@cline/shared";var HR=Y6(UQ(import.meta.url)),GQ=yQ(import.meta.url),QR=Ff(HR,"..","..","..","..",".."),sW=ZR(QR),f5=new Set($R.flatMap((f)=>[f,f.replace(/^node:/,"")])),V6=new Set(WR);function ZR(f){let $={},J={"@cline/agents":Ff(f,"packages/agents/src/index.ts"),"@cline/core":Ff(f,"packages/core/src/index.ts"),"@cline/llms":Ff(f,"packages/llms/src/index.ts"),"@cline/shared":Ff(f,"packages/shared/src/index.ts"),"@cline/shared/storage":Ff(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":Ff(f,"packages/shared/src/db/index.ts")};for(let[W,H]of Object.entries(J))if(r0(H))$[W]=H;return $}function TQ(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function oW(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function hQ(f,$){let J=oW($),W=Y6(f);while(!0){let H=Ff(W,"node_modules",J);if(r0(H)||r0(Ff(H,"package.json")))return!0;let Q=Ff(W,"..");if(Q===W)return!1;W=Q}}function jR(f){try{return GQ.resolve(f),!0}catch{return!1}}function PR(f){try{return GQ.resolve(f)}catch{return null}}function XR(f){let J=Y6(f);for(let W=0;W<4;W++){let H=Ff(J,"package.json");if(r0(H))try{let Z=JSON.parse(eW(H,"utf8"));return Z!=null&&typeof Z==="object"&&"cline"in Z}catch{return!1}let Q=Ff(J,"..");if(Q===J)return!1;J=Q}return!1}function VR(f,$){let J=$.startsWith("file:")?UQ($):JR($)?$:Ff(Y6(f),$);if(r0(J)&&V6.has(KQ(J)))return J;for(let W of V6){let H=`${J}${W}`;if(r0(H))return H}for(let W of V6){let H=Ff(J,`index${W}`);if(r0(H))return H}return null}function DQ(f){let $=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let W of J)for(let H of f.matchAll(W)){let Q=H[1];if(Q)$.add(Q)}return[...$]}function MQ(f,$,J=new Set){if(J.has(f)||!r0(f))return;if(J.add(f),!V6.has(KQ(f)))return;let W=eW(f,"utf8");for(let H of DQ(W)){if(H.startsWith("node:")||f5.has(H))continue;if(TQ(H)){if(Object.hasOwn(sW,H)||Object.hasOwn(sW,oW(H))||hQ(f,H)||$&&jR(H))continue;throw Error(`Cannot find module '${oW(H)}'`)}let Q=VR(f,H);if(Q)MQ(Q,$,J)}}function YR(f,$){let J=yQ(f),W={};for(let[H,Q]of Object.entries(sW)){try{J.resolve(H);continue}catch{}W[H]=Q}if($){let H=eW(f,"utf8");for(let Q of DQ(H)){if(!TQ(Q)||Q.startsWith("node:")||f5.has(Q)||Object.hasOwn(W,Q)||hQ(f,Q))continue;let Z=PR(Q);if(Z)W[Q]=Z}}return W}async function _Q(f,$={}){let J=!XR(f);MQ(f,J);let W=YR(f,J),H=await import("jiti"),Q=typeof H==="function"?H:typeof H.default==="function"?H.default:void 0;if(!Q)throw Error("Unable to load jiti");return await Q(f,{alias:W,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...f5],transformModules:Object.keys(W)}).import(f,{})}function LQ(f,$){if(!f)return!0;if(f.providerIds?.length){if(!$?.providerId||!f.providerIds.includes($.providerId))return!1}if(f.modelIds?.length){if(!$?.modelId||!f.modelIds.includes($.modelId))return!1}return!0}function zQ(f){return typeof f==="object"&&f!==null}function $5(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function RR(f,$){if(!zQ(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!$5(f.manifest.capabilities))throw Error(`Invalid plugin module at ${$}: manifest.capabilities must be a string array`);if(f.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${$}: manifest.capabilities cannot be empty`);if(Object.hasOwn(f.manifest,"providerIds")&&!$5(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!$5(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function FR(f,$){if(!zQ(f))throw Error(`Invalid plugin module at ${$}: expected object export`);if(typeof f.name!=="string"||f.name.length===0)throw Error(`Invalid plugin module at ${$}: expected non-empty "name"`);if(!Object.hasOwn(f,"manifest"))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);RR(f,$)}async function e2(f,$={}){let J=BR($.cwd??process.cwd(),f),W=await _Q(J,{useCache:$.useCache}),H=$.exportName??"plugin",Q=W.default??W[H];FR(Q,J);let Z=Q,j=Z.setup,P=j?(X,V)=>{let Y={...$.session,...V.session},B={...V,session:Object.keys(Y).length>0?Y:void 0,client:$.client??V.client,user:$.user??V.user,workspaceInfo:$.workspaceInfo??V.workspaceInfo,automation:$.automation??V.automation,logger:$.logger??V.logger,telemetry:$.telemetry??V.telemetry};return j(X,B)}:void 0;return{...Z,manifest:AR(Z.manifest),setup:P}}async function B6(f,$={}){return(await T0(f,$)).plugins}async function T0(f,$={}){let J=[],W=[],H=new Map,Q=0;for(let Z of f)try{let j=await e2(Z,$);if(!LQ(j.manifest,$))continue;let P=H.get(j.name);if(P)W.push({type:"duplicate_plugin_override",pluginName:j.name,pluginPath:Z,overriddenPluginPath:P.pluginPath,message:`Plugin "${j.name}" from ${Z} overrides ${P.pluginPath}`});H.set(j.name,{plugin:j,pluginPath:Z,order:Q++})}catch(j){let P=j instanceof Error?j.message:String(j);J.push({pluginPath:Z,phase:"load",message:P,stack:j instanceof Error?j.stack:void 0})}return{plugins:[...H.values()].sort((Z,j)=>Z.order-j.order).map((Z)=>Z.plugin),failures:J,warnings:W}}import{existsSync as TR}from"node:fs";import{createRequire as hR}from"node:module";import{dirname as DR,join as A6}from"node:path";import{fileURLToPath as MR}from"node:url";var wQ={};N(wQ,{resolveSubprocessRuntimeExecutable:()=>J5,buildSubprocessSandboxCommand:()=>bQ,SubprocessSandbox:()=>T1,CLINE_JS_RUNTIME_PATH_ENV:()=>qQ});import{spawn as yR}from"node:child_process";import{basename as KR}from"node:path";import{augmentNodeCommandForDebug as UR,withResolvedClineBuildEnv as GR}from"@cline/shared";function OQ(f){if(f instanceof Error)return f;return Error(String(f))}var qQ="CLINE_JS_RUNTIME_PATH";function NQ(f){let $=f?.trim();if(!$)return!1;let J=KR($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function J5(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[qQ]?.trim();if(J)return J;let W=f.execPath?.trim()||process.execPath;if(NQ(W))return W;for(let H of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let Q=H?.trim();if(Q&&NQ(Q))return Q}return"node"}function bQ(f,$={}){let J=J5({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return UR([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class T1{options;process=null;requestCounter=0;pending=new Map;constructor(f){this.options=f}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest(f){let $=this.pending.get(f);if(!$)return;if(this.pending.delete(f),$.timeout)clearTimeout($.timeout);return $}start(){if(this.process&&this.process.exitCode===null)return;let f=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],$=bQ(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=yR($[0]??J5(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:GR(process.env)});this.process=J;let W="",H=(Q)=>{let Z=W+Q;W=Z.length>4000?Z.slice(-4000):Z};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{H(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${OQ(Q).message}`))}),J.on("exit",(Q,Z)=>{this.process=null;let j=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(Z)})${j?`: ${j}`:""}`))})}async call(f,$,J={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let H=`req_${++this.requestCounter}`,Q={type:"call",id:H,method:f,args:$};return await new Promise((Z,j)=>{let P={resolve:(X)=>Z(X),reject:j};if((J.timeoutMs??0)>0)P.timeout=setTimeout(()=>{this.clearPendingRequest(H),this.shutdown().catch(()=>{}),j(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${f}`))},J.timeoutMs);this.pending.set(H,P),W.send(Q,(X)=>{if(!X)return;let V=this.clearPendingRequest(H);if(!V)return;V.reject(Error(`${this.processLabel} failed to send call "${f}": ${OQ(X).message}`))})})}async shutdown(){let f=this.process;if(this.process=null,!f||f.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise(($)=>{let J=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}$()},300);f.once("exit",()=>{clearTimeout(J),$()});try{f.kill("SIGTERM")}catch{clearTimeout(J),$()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage(f){if(!f)return;if(f.type==="event"){if(typeof f.name==="string"&&f.name.length>0)this.options.onEvent?.({name:f.name,payload:f.payload});return}if(f.type!=="response"||!f.id)return;let $=this.clearPendingRequest(f.id);if(!$)return;if(f.ok){$.resolve(f.result);return}$.reject(Error(f.error?.message||`${this.processLabel} call failed`))}failPending(f){for(let[$,J]of this.pending.entries()){if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);J.reject(f)}}}function _R(f){return{...f,contributions:{tools:f.contributions?.tools??[],commands:f.contributions?.commands??[],messageBuilders:f.contributions?.messageBuilders??[],providers:f.contributions?.providers??[],automationEventTypes:f.contributions?.automationEventTypes??[],shortcuts:f.contributions?.shortcuts??[],flags:f.contributions?.flags??[]}}}function R6(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function LR(){let f=DR(MR(import.meta.url)),$=hR(import.meta.url),J=[A6(f,"plugin-sandbox-bootstrap.js"),A6(f,"extensions","plugin-sandbox-bootstrap.js"),A6(f,"agents","plugin-sandbox-bootstrap.js")];for(let Q of J)if(TR(Q))return{file:Q};let W=A6(f,"plugin-sandbox-bootstrap.ts"),H="jiti";try{H=$.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(H)});`,`const jiti = createJiti(${JSON.stringify(W)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(W)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
137
+ `)}}var W5=LR();function H5(f,$){return typeof f==="number"&&f>0?f:$}async function EQ(f){let $=new T1({name:"plugin-sandbox",..."file"in W5?{bootstrapFile:W5.file}:{bootstrapScript:W5.script},onEvent:f.onEvent}),J=H5(f.importTimeoutMs,4000),W=H5(f.hookTimeoutMs,3000),H=H5(f.contributionTimeoutMs,60000),Q={pluginPaths:f.pluginPaths,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,loggerEnabled:Boolean(f.logger)},Z,j=()=>{return Z??=$.call("initialize",Q,{timeoutMs:J}).finally(()=>{Z=void 0}),Z},P;try{P=await $.call("initialize",Q,{timeoutMs:J})}catch(Y){throw await $.shutdown().catch(()=>{}),Y}return{extensions:P.plugins.map(_R).map((Y)=>{let B={name:Y.name,manifest:Y.manifest,setup:(A)=>{zR(A,$,Y,H,j),OR(A,$,Y,H,j),qR(A,$,Y,H,j),NR(A,Y)}};return B.hooks=wR($,Y,W,j),B}),failures:P.failures,shutdown:async()=>{await $.shutdown()},warnings:P.warnings}}function zR(f,$,J,W,H){for(let Q of J.contributions?.tools??[]){let Z={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(j,P)=>{try{return await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:P},{timeoutMs:W})}catch(X){if(!R6(X))throw X;return await H(),await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:P},{timeoutMs:W})}}};f.registerTool(Z)}}function OR(f,$,J,W,H){for(let Q of J.contributions?.commands??[])f.registerCommand({name:Q.name,description:Q.description,handler:async(Z)=>{try{return await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:W})}catch(j){if(!R6(j))throw j;return await H(),await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:W})}}})}function NR(f,$){for(let J of $.contributions?.providers??[])f.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of $.contributions?.automationEventTypes??[])f.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function qR(f,$,J,W,H){for(let Q of J.contributions?.messageBuilders??[])f.registerMessageBuilder({name:Q.name,async build(Z){try{let j=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:W});return CQ(j)?j:Z}catch(j){if(!R6(j))throw j;await H();let P=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:W});return CQ(P)?P:Z}}})}function CQ(f){return Array.isArray(f)&&f.every(($)=>typeof $==="object"&&$!==null&&("role"in $)&&("content"in $))}function bR(f,$,J,W,H){return async(Q)=>{try{return await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:W})}catch(Z){if(!R6(Z))throw Z;return await H(),await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:W})}}}function wR(f,$,J,W){let H={};for(let Q of $.hooks??[])H[Q]=bR(f,$.pluginId,Q,J,W);return Object.keys(H).length>0?H:void 0}function f8(f){return kR(f)}function $8(f){return ER(f)}function O$(f={}){let $=f.cwd??process.cwd(),J=f8(f.workspacePath).flatMap((Z)=>$8(Z)).filter((Z)=>CR(Z)),W=SR(f.pluginPaths??[],$),H=[],Q=new Set;for(let Z of[...W,...J]){if(Q.has(Z))continue;Q.add(Z),H.push(Z)}return P6(H)}async function h1(f={}){let $=O$(f);if($.length===0)return{extensions:[],failures:[],warnings:[]};if(f.mode==="in_process"){let W=await T0($,{cwd:f.cwd,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,automation:f.automation,logger:f.logger,telemetry:f.telemetry});return{extensions:W.plugins,failures:W.failures,warnings:W.warnings}}let J=await EQ({pluginPaths:$,exportName:f.exportName,importTimeoutMs:f.importTimeoutMs,hookTimeoutMs:f.hookTimeoutMs,contributionTimeoutMs:f.contributionTimeoutMs,onEvent:f.onEvent,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,logger:f.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,warnings:J.warnings}}import{execFile as mR}from"node:child_process";import{promisify as IR}from"node:util";var xR=IR(mR);function Q5(f,$){f?.log($,{severity:"warn"})}function gR(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!J.latest||!Array.isArray(J.history))return;let W=J.latest,H=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:H}}async function N$(f,$){let J=await xR("git",["-C",f,...$],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function Z5(f,$){if(!f)return;let J=`refs/cline/checkpoints/${$}/`;try{let{stdout:W}=await N$(f,["for-each-ref","--format=%(refname)",J]),H=W.trim().split(`
138
+ `).filter(Boolean);await Promise.allSettled(H.map((Q)=>N$(f,["update-ref","-d",Q])))}catch{}}async function SQ(f,$,J){if(!f||J.length===0)return;await Promise.allSettled(J.map((W)=>N$(f,["update-ref",`refs/cline/checkpoints/${$}/${W.runCount}`,W.ref])))}function vR(f,$){let J=f.findIndex((W)=>W.runCount===$.runCount);if(J<0)return[...f,$];return f.map((W,H)=>H===J?$:W)}function kQ(f){let $=f.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await N$(f.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},H=async()=>{if(f.createCheckpoint)return await f.createCheckpoint({cwd:f.cwd,sessionId:f.sessionId,runCount:$});if(!await W())return;let Q=async(X)=>{try{let Y=(await N$(f.cwd,["rev-parse","HEAD"])).stdout.trim();if(!Y)return;return{ref:Y,createdAt:Date.now(),runCount:$,kind:"commit"}}catch(V){Q5(f.logger,`${X}: ${V instanceof Error?V.message:String(V)}`);return}},Z=`cline checkpoint session=${f.sessionId} run=${$}`,j="";try{j=(await N$(f.cwd,["stash","create",Z])).stdout.trim()}catch(X){return Q5(f.logger,`Checkpoint snapshot failed: ${X instanceof Error?X.message:String(X)}`),Q("Checkpoint HEAD fallback failed")}if(!j)return Q("Checkpoint HEAD fallback failed");let P=`refs/cline/checkpoints/${f.sessionId}/${$}`;try{await N$(f.cwd,["update-ref",P,j])}catch(X){Q5(f.logger,`Checkpoint store failed: ${X instanceof Error?X.message:String(X)}`);return}return{ref:j,createdAt:Date.now(),runCount:$,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;$+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||$<1)return;let Z=await H();if(!Z)return;let j=await f.readSessionMetadata(),P=gR(j);if(P?.latest.ref===Z.ref)return;let X=vR(P?.history??[],Z);await f.writeSessionMetadata({...j??{},checkpoint:{latest:Z,history:X}});return}}}import{spawn as aR}from"node:child_process";import{appendFileSync as tR,readFileSync as sR}from"node:fs";import{join as oR}from"node:path";import{augmentNodeCommandForDebug as xQ,withResolvedClineBuildEnv as X5}from"@cline/shared";import{ensureHookLogDir as mQ}from"@cline/shared/storage";function D1(f,$){if(!$)return;return{name:f,manifest:{capabilities:["hooks"]},hooks:$}}import{existsSync as uR,readdirSync as cR}from"node:fs";import{basename as dR,extname as rR,join as lR}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as F6,resolveHooksConfigSearchPaths as pR}from"@cline/shared/storage";function J8(f){return pR(f)}var M1;((V)=>{V.TaskStart="TaskStart";V.TaskResume="TaskResume";V.TaskCancel="TaskCancel";V.TaskComplete="TaskComplete";V.TaskError="TaskError";V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.UserPromptSubmit="UserPromptSubmit";V.PreCompact="PreCompact";V.SessionShutdown="SessionShutdown"})(M1||={});var W8={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["TaskError"]:"agent_error",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},iR=new Map(Object.values(M1).map((f)=>[f.toLowerCase(),f])),nR=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function H8(f){let $=rR(f).toLowerCase();if(!nR.has($))return;let J=dR(f,$).trim().toLowerCase();return iR.get(J)}function l0(f){let $=[],J=new Set,W=J8(f).filter((H)=>uR(H));for(let H of W)try{for(let Q of cR(H,{withFileTypes:!0})){if(!Q.isFile())continue;let Z=H8(Q.name);if(!Z)continue;let j=lR(H,Q.name);if(J.has(j))continue;J.add(j),$.push({fileName:Z,hookEventName:W8[Z],path:j})}}catch{}return $.sort((H,Q)=>H.path.localeCompare(Q.path))}function K6(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,W]of Object.entries(f))$[J]=typeof W==="string"?W:JSON.stringify(W);return $}function y6(f,$,J){let W=J instanceof Error?`: ${J.message}`:"",H=`${$}${W}`;if(f){try{f.log(H,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(H)}function eR(f,$){if(!$)return f;if(!f)return{...$};let J=[f.context,$.context].filter((H)=>typeof H==="string"&&H.length>0).join(`
139
+ `),W=[...f.appendMessages??[],...$.appendMessages??[]];return{cancel:f.cancel===!0||$.cancel===!0?!0:void 0,review:f.review===!0||$.review===!0?!0:void 0,context:J||void 0,overrideInput:$.overrideInput!==void 0?$.overrideInput:f.overrideInput,systemPrompt:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,appendMessages:W.length>0?W:void 0}}function fF(f){if(!f||typeof f!=="object")return;let $=f,J=typeof $.context==="string"?$.context:typeof $.contextModification==="string"?$.contextModification:typeof $.errorMessage==="string"?$.errorMessage:void 0;return{cancel:typeof $.cancel==="boolean"?$.cancel:void 0,review:typeof $.review==="boolean"?$.review:void 0,context:J,overrideInput:Object.hasOwn($,"overrideInput")?$.overrideInput:void 0}}function j5(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function Xf(f,$){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:$.rootSessionId||f.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:W,workspaceRoots:$.workspacePath?[$.workspacePath]:[],workspaceInfo:$.workspaceInfo,userId:J,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function $F(f){let $=f.trim();if(!$)return{};let W=$.split(`
140
+ `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),H=W.length>0?W[W.length-1]:$;try{return{parsedJson:JSON.parse(H)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function JF(f,$){let J=f.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((W,H)=>{let Q=!1,Z=()=>{J.off("error",P),J.off("finish",X),f.off("close",V)},j=(Y)=>{if(Q)return;if(Q=!0,Z(),Y){let B=Y.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){W();return}H(Y);return}W()},P=(Y)=>j(Y),X=()=>j(),V=()=>j();J.on("error",P),J.once("finish",X),f.once("close",V);try{J.end($)}catch(Y){j(Y)}})}async function gQ(f,$){if($.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await IQ(f,$)}catch(J){let W=QF($.command,process.platform,J);if(!W)throw J;return await IQ(f,{...$,command:W})}}async function IQ(f,$){let J=xQ($.command,{env:$.env,debugRole:"hook"}),W=aR(J[0],J.slice(1),{cwd:$.cwd,env:X5($.env),stdio:$.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:$.detached}),H=new Promise((B)=>{W.once("spawn",()=>B())}),Q=new Promise((B,A)=>{W.once("error",(R)=>A(R))}),Z=JSON.stringify(f);if(await Promise.race([H,Q]),await JF(W,Z),$.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let j="",P="",X=!1,V;W.stdout.on("data",(B)=>{j+=B.toString()}),W.stderr.on("data",(B)=>{P+=B.toString()});let Y=new Promise((B)=>{if(($.timeoutMs??0)>0)V=setTimeout(()=>{X=!0,W.kill("SIGKILL")},$.timeoutMs);W.once("close",(A)=>{if(V)clearTimeout(V);let{parsedJson:R,parseError:U}=$F(j);B({exitCode:A,stdout:j,stderr:P,parsedJson:R,parseError:U,timedOut:X})})});return await Promise.race([Y,Q])}function WF(f){try{let J=sR(f,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let W=J.slice(2).trim();if(!W)return;let H=W.split(/\s+/).filter(Boolean);return H.length>0?H:void 0}catch{return}}function HF(f){return!!(f&&typeof f==="object"&&("code"in f)&&f.code==="ENOENT")}function QF(f,$=process.platform,J){if($!=="win32"||!HF(J))return;if(f[0]!=="py"||f[1]!=="-3")return;return["python",...f.slice(2)]}function vQ(f){if(f.length===0)return;let[$,...J]=f,W=$.replace(/\\/g,"/").toLowerCase(),H=W.split("/").at(-1)??W;if(H==="env")return vQ(J);if(H==="bash"||H==="sh"||H==="zsh")return[H,...J];if(H==="python3"||H==="python")return process.platform==="win32"?["py","-3",...J]:[H,...J];return f}function ZF(f){let $=WF(f);if($&&$.length>0)return[...vQ($)??$,f];let J=f.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",f];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return xQ(["node",f],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",f];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",f]:["python3",f];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",f];return["bash",f]}function jF(f){let $={};for(let J of l0(f)){if(!J.hookEventName)continue;let W=J.hookEventName,H=$[W]??[];H.push(ZF(J.path)),$[W]=H}return $}async function PF(f){let $;for(let J of f.commands){let W=J.join(" ");try{let H=await gQ(f.payload,{command:J,cwd:f.cwd,env:X5(process.env),detached:!1,timeoutMs:f.timeoutMs});if(H?.timedOut){y6(f.logger,`hook command timed out: ${W}`);continue}if(H?.parseError){y6(f.logger,`hook command returned invalid JSON control output: ${W} (${H.parseError})`);continue}$=eR($,fF(H?.parsedJson))}catch(H){y6(f.logger,`hook command failed: ${W}`,H)}}return $}function q$(f){for(let $ of f.commands){let J=$.join(" ");gQ(f.payload,{command:$,cwd:f.cwd,env:X5(process.env),detached:!0}).catch((W)=>{y6(f.logger,`hook command failed: ${J}`,W)})}}function p0(f){return{agentId:f.agentId,conversationId:f.conversationId??f.runId??f.agentId,parentAgentId:f.parentAgentId??null}}function P5(f,$){return{...p0(f.snapshot),userMessage:$}}function uQ(f){return{...p0(f.snapshot),iteration:f.snapshot.iteration,call:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input}}}function cQ(f){return{...p0(f.snapshot),iteration:f.snapshot.iteration,record:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}}function dQ(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function XF(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}function _1(f){let $={cwd:f.workspacePath,workspacePath:f.workspacePath,rootSessionId:f.rootSessionId,workspaceInfo:f.workspaceInfo},J=(W)=>{let H=`${JSON.stringify({ts:new Date().toISOString(),...W})}
141
+ `,Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??oR(mQ(),"hooks.jsonl");mQ(Z),tR(Z,H,"utf8")};return{beforeRun:async(W)=>{let H=P5(W,"");J({...Xf(H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let H=uQ(W);J({...Xf(H,$),hookName:"tool_call",iteration:H.iteration,tool_call:{id:H.call.id,name:H.call.name,input:H.call.input},preToolUse:{toolName:H.call.name,parameters:K6(H.call.input)}});return},afterTool:async(W)=>{let H=cQ(W);J({...Xf(H,$),hookName:"tool_result",iteration:H.iteration,tool_result:H.record,postToolUse:{toolName:H.record.name,parameters:K6(H.record.input),result:typeof H.record.output==="string"?H.record.output:JSON.stringify(H.record.output),success:!H.record.error,executionTimeMs:H.record.durationMs}});return},afterRun:async({snapshot:W,result:H})=>{let Q=p0(W);if(H.status==="completed"){J({...Xf(Q,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}});return}if(H.status==="aborted"||j5(H.error?.message)){J({...Xf(Q,$),hookName:"agent_abort",reason:H.error?.message,taskCancel:{taskMetadata:{}}});return}if(H.error)J({...Xf(Q,$),hookName:"agent_error",iteration:H.iterations,error:{name:H.error.name,message:H.error.message,stack:H.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let H=P5({snapshot:W.snapshot},dQ(W.message.content));J({...Xf(H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:H.userMessage,attachments:[]}})}}}function Q8(f){let $=jF(f.workspacePath);if(!Object.values($).some((Y)=>Y.length>0))return;let W=async(Y,B)=>{let A=$[B]??[];if(A.length===0)return;q$({commands:A,cwd:f.cwd,logger:f.logger,payload:B==="agent_resume"?{...Xf(Y,f),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...Xf(Y,f),hookName:B,taskStart:{taskMetadata:{}}}})},H=async(Y)=>{let B=$.prompt_submit??[];if(B.length>0)q$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Xf(Y,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Y.userMessage,attachments:[]}}})},Q=async(Y)=>{let B=$.tool_call??[];if(B.length===0)return;return PF({commands:B,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...Xf(Y,f),hookName:"tool_call",iteration:Y.iteration,tool_call:{id:Y.call.id,name:Y.call.name,input:Y.call.input},preToolUse:{toolName:Y.call.name,parameters:K6(Y.call.input)}}})},Z=async(Y)=>{let B=$.tool_result??[];if(B.length===0)return;q$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Xf(Y,f),hookName:"tool_result",iteration:Y.iteration,tool_result:Y.record,postToolUse:{toolName:Y.record.name,parameters:K6(Y.record.input),result:typeof Y.record.output==="string"?Y.record.output:JSON.stringify(Y.record.output),success:!Y.record.error,executionTimeMs:Y.record.durationMs}}})},j=async(Y)=>{let B=$.agent_end??[];if(B.length===0)return;q$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Xf(Y,f),hookName:"agent_end",iteration:Y.iteration,turn:Y.turn,taskComplete:{taskMetadata:{}}}})},P=async(Y)=>{let B=$.agent_error??[];if(B.length===0)return;q$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Xf(Y,f),hookName:"agent_error",iteration:Y.iteration,error:{name:Y.error.name,message:Y.error.message,stack:Y.error.stack}}})},X=async(Y)=>{if(j5(Y.reason)){let A=$.agent_abort??[];if(A.length>0)q$({commands:A,cwd:f.cwd,logger:f.logger,payload:{...Xf(Y,f),hookName:"agent_abort",reason:Y.reason,taskCancel:{taskMetadata:{}}}})}let B=$.session_shutdown??[];if(B.length===0)return;q$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Xf(Y,f),hookName:"session_shutdown",reason:Y.reason}})},V={};if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0||($.prompt_submit?.length??0)>0){if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0)V.beforeRun=async(Y)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(p0(Y.snapshot),B);return};if(($.prompt_submit?.length??0)>0)V.onEvent=async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;await H(P5({snapshot:Y.snapshot},dQ(Y.message.content)))}}if(($.tool_call?.length??0)>0)V.beforeTool=async(Y)=>{let B=await Q(uQ(Y));return XF(B)};if(($.tool_result?.length??0)>0)V.afterTool=async(Y)=>{await Z(cQ(Y));return};if(($.agent_end?.length??0)>0)V.afterRun=async({snapshot:Y,result:B})=>{if(B.status!=="completed")return;await j({...p0(Y),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if(($.agent_error?.length??0)>0||($.agent_abort?.length??0)>0||($.session_shutdown?.length??0)>0){let Y=V.afterRun;V.afterRun=async(B)=>{await Y?.(B);let{snapshot:A,result:R}=B;if(R.status==="aborted"||j5(R.error?.message)){await X({...p0(A),reason:R.error?.message});return}if(R.error)await P({...p0(A),iteration:R.iterations,error:R.error})}}return V}function L1(f){return D1("core.hook_config_files",Q8(f))}function b$(f,$){let J=f.map((W)=>W[$]).filter((W)=>typeof W==="function");if(J.length===0)return;return async(W)=>{let H;for(let Q of J){let Z=await Q(W);if(!Z||typeof Z!=="object")continue;let j=Z;H={...H??{},...j,stop:H?.stop===!0||j.stop===!0?!0:j.stop,options:H?.options||j.options?{...H?.options??{},...j.options??{}}:void 0}}return H}}function w$(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:b$($,"beforeRun"),afterRun:b$($,"afterRun"),beforeModel:b$($,"beforeModel"),afterModel:b$($,"afterModel"),beforeTool:b$($,"beforeTool"),afterTool:b$($,"afterTool"),onEvent:b$($,"onEvent")}}var rQ={};N(rQ,{normalizeRuntimeCapabilities:()=>Vf});function Vf(...f){let $,J;for(let H of f){if(!H)continue;if(H.toolExecutors)$={...$??{},...H.toolExecutors};if(H.requestToolApproval)J=H.requestToolApproval}let W=$&&Object.keys($).length>0;if(!W&&!J)return;return{...W?{toolExecutors:$}:{},...J?{requestToolApproval:J}:{}}}var jZ={};N(jZ,{toProviderConfig:()=>bf,emptyStoredProviderSettings:()=>t0,StoredProviderSettingsSchema:()=>w1,StoredProviderSettingsEntrySchema:()=>i6,ProviderSettingsSchemaTyped:()=>R8});import{z as a0}from"zod";var ZZ={};N(ZZ,{toProviderConfig:()=>bf,safeParseSettings:()=>p6,safeCreateProviderConfig:()=>z5,parseSettings:()=>l6,normalizeProviderId:()=>b1,isBuiltInProviderId:()=>_5,createProviderConfig:()=>L5,SapSettingsSchema:()=>c6,ReasoningSettingsSchema:()=>x6,ProviderSettingsSchema:()=>n0,ProviderProtocolSchema:()=>k6,ProviderIdSchema:()=>A8,ProviderClientSchema:()=>m6,OcaSettingsSchema:()=>d6,ModelCatalogSettingsSchema:()=>r6,GcpSettingsSchema:()=>v6,BUILT_IN_PROVIDER_IDS:()=>M5,BUILT_IN_PROVIDER:()=>B8,AzureSettingsSchema:()=>u6,AwsSettingsSchema:()=>g6,AuthSettingsSchema:()=>I6});import*as qf from"@cline/llms";import{z as _}from"zod";Gf();var eQ={};N(eQ,{refreshOcaToken:()=>j8,loginOcaOAuth:()=>N1,getValidOcaCredentials:()=>P8,generateOcaOpcRequestId:()=>z6,createOcaRequestHeaders:()=>A5,createOcaOAuthProvider:()=>B5,OCI_HEADER_OPC_REQUEST_ID:()=>_6,DEFAULT_INTERNAL_OCA_BASE_URL:()=>z1,DEFAULT_INTERNAL_IDCS_URL:()=>G6,DEFAULT_INTERNAL_IDCS_SCOPES:()=>T6,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>U6,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>O1,DEFAULT_EXTERNAL_IDCS_URL:()=>D6,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>M6,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>h6});import{nanoid as pQ}from"nanoid";class V5{ttlMs;maxEntries;entries=new Map;constructor(f,$){this.ttlMs=f;this.maxEntries=$}get(f,$=Date.now()){this.pruneExpired($);let J=this.entries.get(f);if(!J)return;return this.entries.delete(f),this.entries.set(f,J),J.value}set(f,$,J=Date.now(),W=this.ttlMs){this.pruneExpired(J),this.entries.delete(f);while(this.entries.size>=this.maxEntries){let H=this.entries.keys().next().value;if(H===void 0)break;this.entries.delete(H)}this.entries.set(f,{value:$,expiresAt:J+W})}pruneExpired(f){for(let[$,J]of this.entries)if(J.expiresAt<=f)this.entries.delete($)}}var lQ={};N(lQ,{startLocalOAuthServer:()=>h0});function VF(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function h0(f){let $=await import("node:http"),J=f.host??"127.0.0.1",W=f.timeoutMs??300000,H=f.successHtml??YF,Q=VF(),Z=!1,j=null,P=null,X=null,V=(A)=>{if(Z)return;Z=!0,Q.resolve(A)},Y=()=>{if(j)clearTimeout(j),j=null;let A=X;if(X=null,P)P.close(),P=null;if(A!==null&&f.onClose)Promise.resolve(f.onClose({host:J,port:A})).catch(()=>{})},B=async()=>{return j=setTimeout(()=>{Y(),V(null)},W),Q.promise};for(let A of f.ports){let R=$.createServer((y,F)=>{try{let K=new URL(y.url||"",`http://${J}:${A}`);if(K.pathname!==f.callbackPath){F.statusCode=404,F.end("Not found");return}let M={url:K,code:K.searchParams.get("code")??void 0,state:K.searchParams.get("state")??void 0,provider:K.searchParams.get("provider")??void 0,error:K.searchParams.get("error")??void 0};if(M.error){F.statusCode=400,F.end(`Authentication failed: ${M.error}`),Y(),V(M);return}if(!M.code){F.statusCode=400,F.end("Missing authorization code");return}if(f.expectedState&&M.state!==f.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(H),Y(),V(M)}catch{F.statusCode=500,F.end("Internal error")}}),U=await new Promise((y)=>{let F=(K)=>{R.off("error",F),y({bound:!1,error:K})};R.once("error",F),R.listen(A,J,()=>{R.off("error",F),P=R,y({bound:!0})})});if(U.error){if(U.error.code==="EADDRINUSE")continue;throw Y(),U.error}if(U.bound){X=A;let y=`http://${J}:${A}${f.callbackPath}`;if(f.onListening)await Promise.resolve(f.onListening({host:J,port:A,callbackUrl:y})).catch(()=>{});return{callbackUrl:y,waitForCallback:B,cancelWait:()=>{Y(),V(null)},close:()=>{Y(),V(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var YF=`<!DOCTYPE html>
142
+ <html lang="en">
143
+ <head>
144
+ <meta charset="utf-8">
145
+ <meta name="viewport" content="width=device-width, initial-scale=1">
146
+ <title>Authentication Successful</title>
147
+ <style>
148
+ * { margin: 0; padding: 0; box-sizing: border-box; }
149
+ body {
150
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
151
+ min-height: 100vh;
152
+ display: flex;
153
+ align-items: center;
154
+ justify-content: center;
155
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
156
+ color: #fff;
157
+ }
158
+ .container { text-align: center; padding: 48px; max-width: 420px; }
159
+ .icon {
160
+ width: 72px; height: 72px; margin: 0 auto 24px;
161
+ background: linear-gradient(135deg, #10a37f 0%, #1a7f64 100%);
162
+ border-radius: 50%;
163
+ display: flex; align-items: center; justify-content: center;
164
+ }
165
+ .icon svg { width: 36px; height: 36px; stroke: #fff; stroke-width: 3; fill: none; }
166
+ h1 { font-size: 24px; font-weight: 600; margin-bottom: 12px; }
167
+ p { font-size: 15px; color: rgba(255,255,255,0.7); line-height: 1.5; }
168
+ .closing { margin-top: 32px; font-size: 13px; color: rgba(255,255,255,0.5); }
169
+ </style>
170
+ </head>
171
+ <body>
172
+ <div class="container">
173
+ <div class="icon">
174
+ <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
175
+ </div>
176
+ <h1>Authentication Successful</h1>
177
+ <p>You're now signed in. You can close this window.</p>
178
+ <p class="closing">This window will close automatically...</p>
179
+ </div>
180
+ <script>setTimeout(() => window.close(), 3000);</script>
181
+ </body>
182
+ </html>`;var U6="a8331954c0cf48ba99b5dd223a14c6ea",G6="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",T6="openid offline_access",z1="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",h6="c1aba3deed5740659981a752714eba33",D6="https://login-ext.identity.oraclecloud.com",M6="openid offline_access",O1="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",_6="opc-request-id",BF="/auth/oca",AF=Array.from({length:11},(f,$)=>48801+$),RF=300000,FF=30000,iQ=30000,yF=600000;class L6 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OcaOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var i0={internal:{clientId:U6,idcsUrl:G6,scopes:T6,baseUrl:z1},external:{clientId:h6,idcsUrl:D6,scopes:M6,baseUrl:O1}},Z8=new Map,KF=86400000,UF=300000,GF=32,Y5=new V5(KF,GF);function nQ(f){if(typeof f==="function")return f();return f??"internal"}function aQ(f){return{internal:{clientId:f?.internal?.clientId??i0.internal.clientId,idcsUrl:f?.internal?.idcsUrl??i0.internal.idcsUrl,scopes:f?.internal?.scopes??i0.internal.scopes,baseUrl:f?.internal?.baseUrl??i0.internal.baseUrl},external:{clientId:f?.external?.clientId??i0.external.clientId,idcsUrl:f?.external?.idcsUrl??i0.external.idcsUrl,scopes:f?.external?.scopes??i0.external.scopes,baseUrl:f?.external?.baseUrl??i0.external.baseUrl}}}function TF(f=Date.now()){let $=f-yF;for(let[J,W]of Z8.entries())if(W.createdAt<$)Z8.delete(J)}function hF(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let H=Rf($)?.exp;if(typeof H==="number"&&H>0)return H*1000;let Z=Rf(J)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return Date.now()+3600000}function tQ(f,$,J){let W=f.access_token;if(!W)throw Error("Token response did not include an access token");let H=f.refresh_token??J?.refresh;if(!H)throw Error("Token response did not include a refresh token");let Q=Rf(f.id_token),Z=Rf(W),j=Q?.sub??Z?.sub,P=Q?.email??Z?.email;return{access:W,refresh:H,expires:hF(f,W,f.id_token),accountId:j??J?.accountId,email:P??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:$,subject:j,idToken:f.id_token}}}async function sQ(f,$){let J=Q6(f),W=Y5.get(J);if(W)return W;let H=`${J}/.well-known/openid-configuration`,Q=await fetch(H,{method:"GET",signal:AbortSignal.timeout($)});if(!Q.ok){let P=`${J}/oauth2/v1/token`;return Y5.set(J,P,Date.now(),UF),P}let j=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return Y5.set(J,j),j}function oQ(f){return{code:f.error,message:f.error_description}}async function DF(f){let $=Z8.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");Z8.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,W=await sQ(J.idcsUrl,f.requestTimeoutMs),H=new URLSearchParams({grant_type:"authorization_code",code:f.code,redirect_uri:$.redirectUri,client_id:J.clientId,code_verifier:$.verifier}),Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,signal:AbortSignal.timeout(f.requestTimeoutMs)}),Z=await Q.json();if(!Q.ok){let P=oQ(Z);throw new L6(`Token exchange failed: ${Q.status}${P.message?` - ${P.message}`:""}`,{status:Q.status,errorCode:P.code})}let j=Rf(Z.id_token);if(!Z.id_token||!j)throw Error("No ID token received from OCA");if(j.nonce!==$.nonce)throw Error("OIDC nonce verification failed");return tQ(Z,f.mode)}function MF(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${Q6($.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",$.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",$.scopes),J.searchParams.set("code_challenge",f.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",f.callbackUrl),J.searchParams.set("state",f.state),J.searchParams.set("nonce",f.nonce),J.toString()}async function N1(f){R0(f.telemetry,"oca");let $=aQ(f.config),J=nQ(f.mode),W=f.callbackPorts?.length?f.callbackPorts:AF,H=f.callbackPath??BF,Q=f.requestTimeoutMs??iQ,Z=await h0({ports:W,callbackPath:H,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),j=Z.callbackUrl;if(!j)throw Error("Unable to bind local OAuth callback server");let P=pQ(16),X=pQ(16),{verifier:V,challenge:Y}=await H6();TF(),Z8.set(P,{verifier:V,nonce:X,mode:J,redirectUri:j,createdAt:Date.now()});let B=MF({callbackUrl:j,mode:J,state:P,nonce:X,challenge:Y,config:$});f.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let A=await G1({waitForCallback:Z.waitForCallback,cancelWait:Z.cancelWait,onManualCodeInput:f.callbacks.onManualCodeInput}),R=A.code,U=A.state;if(A.error)throw Error(`OAuth error: ${A.error}`);if(!R){if(!f.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!U||U!==P)throw Error("State mismatch");let y=await DF({code:R,state:U,mode:J,config:$,requestTimeoutMs:Q});return F0(f.telemetry,"oca"),K0(f.telemetry,{id:y.accountId,email:y.email,provider:"oca"}),y}catch(A){throw y0(f.telemetry,"oca",A instanceof Error?A.message:String(A)),A}finally{Z.close()}}async function j8(f,$={}){let J=aQ($.config),W=$.requestTimeoutMs??iQ,H=f.metadata?.mode,Q=H==="internal"||H==="external"?H:nQ($.mode),Z=Q==="external"?J.external:J.internal,j=await sQ(Z.idcsUrl,W),P=new URLSearchParams({grant_type:"refresh_token",refresh_token:f.refresh,client_id:Z.clientId}),X=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:P,signal:AbortSignal.timeout(W)}),V=await X.json();if(!X.ok){let Y=oQ(V);throw new L6(`Token refresh failed: ${X.status}${Y.message?` - ${Y.message}`:""}`,{status:X.status,errorCode:Y.code})}return tQ(V,Q,f)}async function P8(f,$,J){if(!f)return null;let W=$?.refreshBufferMs??J?.refreshBufferMs??RF,H=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??FF;if($?.forceRefresh!==!0&&!_$(f,W))return f;try{return await j8(f,J)}catch(Z){if(Z instanceof L6&&Z.isLikelyInvalidGrant())return g0(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function B5(f={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login($){return N1({...f,callbacks:$})},async refreshToken($){return j8($,f)},getApiKey($){return $.access}}}async function z6(f,$){let J=new TextEncoder,W=async(X)=>{let V=await crypto.subtle.digest("SHA-256",J.encode(X));return Array.from(new Uint8Array(V).slice(0,4),(Y)=>Y.toString(16).padStart(2,"0")).join("")},[H,Q]=await Promise.all([W($),W(f)]),Z=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),j=new Uint32Array(1);crypto.getRandomValues(j);let P=(j[0]??0).toString(16).padStart(8,"0");return H+Q+Z+P}async function A5(f){let $=await z6(f.taskId,f.accessToken);return{Authorization:`Bearer ${f.accessToken}`,"Content-Type":"application/json",client:f.metadata?.client??"Cline","client-version":f.metadata?.clientVersion??"unknown","client-ide":f.metadata?.clientIde??"unknown","client-ide-version":f.metadata?.clientIdeVersion??"unknown",[_6]:$}}var QZ={};N(QZ,{resolveProviderConfig:()=>Y8,getProviderConfig:()=>S6,getLiveModelsCatalog:()=>q1,clearPublicModelsCatalogCache:()=>dF,clearPrivateModelsCatalogCache:()=>D5,clearLiveModelsCatalogCache:()=>h5,OPENAI_COMPATIBLE_PROVIDERS:()=>V8,DEFAULT_MODELS_CATALOG_URL:()=>C6});import*as Af from"@cline/llms";function R5(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(typeof $==="string")return $.trim();if($&&typeof $==="object"){let J=$;for(let W of[J.id,J.name,J.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter(($)=>$.length>0)}function _F(f,$){let J=R5(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let W=f,H=R5(W.data??W.models);if(H.length>0)return H;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let Z=Object.keys(W.models).filter((j)=>j.trim().length>0);if(Z.length>0)return Z}let Q=W.providers?.[$];if(Q&&typeof Q==="object"){let j=R5(Q.models??Q);if(j.length>0)return j}return[]}async function O6(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return _F(await J.json(),$)}function fZ(f){return f.replace(/\/+$/,"")}function N6(f,$,J){let W=J?.trim();if(!W)return;let H=f?.trim();if(!H||!$?.trim())return W;try{let Q=new URL(W),Z=new URL($),j=new URL(H);if(Q.origin!==Z.origin)return W;let P=fZ(Z.pathname),X=fZ(j.pathname);if(P&&Q.pathname.startsWith(`${P}/`)){let V=Q.pathname.slice(P.length);j.pathname=`${X}${V}`}else j.pathname=Q.pathname;return j.search=Q.search,j.hash=Q.hash,j.toString()}catch{return W}}function LF(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function zF(f){if(f.baseUrl.length===0)return!1;switch(f.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return f.protocol==="openai-chat"}}var OF=Object.values(Af.MODEL_COLLECTIONS_BY_PROVIDER_ID).map((f)=>({id:f.provider.id,baseUrl:f.provider.baseUrl??"",modelsSourceUrl:f.provider.modelsSourceUrl,modelId:f.provider.defaultModelId,knownModels:LF(f.models),capabilities:f.provider.capabilities?[...f.provider.capabilities]:void 0,env:f.provider.env?[...f.provider.env]:void 0,client:f.provider.client,protocol:f.provider.protocol})),$Z=Object.fromEntries(OF.map((f)=>[f.id,f]));function NF(f){return $Z[f]}function qF(){return Object.fromEntries(Object.entries($Z).filter(([,f])=>zF(f)))}function JZ(f=[]){let $=f.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return $.length>0?$:void 0}var C6="https://models.dev/api.json",bF=600000,WZ=300000,wF=5000,w6=new Map,X8=new Map,y5=new Map,q6=new Map;async function CF(){return Af.getGeneratedProviderModels()}async function EF(f,$={},J={},W={},H={},Q={}){let Z=await CF(),j=Af.resolveProviderModelCatalogKeys(f),P=Object.assign({},...j.map((Y)=>Z[Y]??{})),X=Boolean(Af.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl),V=Object.keys(H).length>0;if(X&&V)return Af.sortModelsByReleaseDate({...H,...Q});return Af.sortModelsByReleaseDate({...P,...$,...J,...W,...H,...Q})}function SF(f,$){let J=Af.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((W)=>$[W]??{}))}function U5(f){let $=f?.trim();return $&&$.length>0?$:""}function G5(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function kF(f){let $=2166136261;for(let J=0;J<f.length;J+=1)$^=f.charCodeAt(J),$+=($<<1)+($<<4)+($<<7)+($<<8)+($<<24);return($>>>0).toString(16)}function mF(f,$){return`${f}:${U5($.baseUrl)}:${kF(G5($)??"")}`}async function T5(f,$,J=wF){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await fetch(f,{...$,signal:W.signal})}finally{clearTimeout(H)}}function F5(f,$,J){if(J&&!f.includes($))f.push($)}function E6(f,$){let J=["streaming","tools"];return F5(J,"images",Boolean($.supportsImages)),F5(J,"prompt-cache",Boolean($.supportsPromptCache)),F5(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}async function IF(f,$){let J=await T5("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let H=(await J.json())?.data??[],Q={};for(let Z of H){let j=Z.id?.trim();if(!j)continue;if(j.includes("whisper")||j.includes("tts")||j.includes("embedding"))continue;let P=Z.supported_features??[];Q[j]=E6(j,{name:j,contextWindow:Z.context_length,maxTokens:Z.max_completion_tokens,supportsReasoning:P.includes("reasoning")||P.includes("reasoning_effort"),supportsImages:!1})}return Q}async function xF(f,$){let J=await T5("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":$}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let H=(await J.json())?.data??[],Q={};for(let Z of H){let j=Z.id?.trim();if(!j)continue;Q[j]=E6(j,{name:j,contextWindow:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}function gF(f){let $=U5(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function vF(f,$){let W=`${gF(f.baseUrl)}/v1/model/info`,H=async(X)=>T5(W,{method:"GET",headers:{accept:"application/json",...X}}),Q=await H({"x-litellm-api-key":$});if(!Q.ok)Q=await H({Authorization:`Bearer ${$}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let j=(await Q.json())?.data??[],P={};for(let X of j){let V=X.model_name?.trim(),B=X.litellm_params?.model?.trim()||V;if(!B)continue;let A=X.model_info,R=E6(B,{name:V??B,maxTokens:A?.max_output_tokens??A?.max_tokens,contextWindow:A?.max_input_tokens??A?.max_tokens,supportsImages:A?.supports_vision,supportsPromptCache:A?.supports_prompt_caching,supportsReasoning:A?.supports_reasoning});if(P[B]=R,V)P[V]={...R,id:V,name:V}}return P}var HZ={baseten:IF,hicap:xF,litellm:vF},K5=new Map,b6=new Map;function uF(f,$){return`${f}:${U5($.baseUrl)}`}async function cF(f,$,J){let W=Af.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],H=N6(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!H)return{};let Q=$?.cacheTtlMs??WZ,Z=uF(f,J),j=Date.now(),P=K5.get(Z);if(P&&P.expiresAt>j)return P.data;let X=b6.get(Z);if(X)return X;let V=O6(H,f).then((Y)=>{let B=Object.fromEntries(Y.map((A)=>[A,E6(A,{name:A})]));return K5.set(Z,{data:B,expiresAt:j+Q}),B}).finally(()=>{b6.delete(Z)});return b6.set(Z,V),V}function dF(){K5.clear(),b6.clear()}async function rF(f,$){let J=G5($);if(!J)return{};let W=HZ[f];if(!W)return{};return W($,J)}function lF(f,$,J){if(!J)return!1;if(!HZ[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(G5(J))}async function pF(f,$,J){let W=$?.cacheTtlMs??WZ,H=mF(f,J),Q=Date.now(),Z=y5.get(H);if(Z&&Z.expiresAt>Q)return Z.data;let j=q6.get(H);if(j)return j;let P=rF(f,J).then((X)=>{return y5.set(H,{data:X,expiresAt:Q+W}),X}).finally(()=>{q6.delete(H)});return q6.set(H,P),P}async function iF(f){return Af.fetchModelsDevProviderModels(f)}async function q1(f={}){let $=f.url??C6,J=f.cacheTtlMs??bF,W=Date.now(),H=w6.get($);if(H&&H.expiresAt>W)return H.data;let Q=X8.get($);if(Q)return Q;let Z=iF($).then((j)=>{return w6.set($,{data:j,expiresAt:W+J}),j}).finally(()=>{X8.delete($)});return X8.set($,Z),Z}function h5(f){if(f){w6.delete(f),X8.delete(f);return}w6.clear(),X8.clear()}function D5(){y5.clear(),q6.clear()}function nF(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:JZ(J.capabilities)}]))}var V8=nF(qF());function S6(f){let $=NF(f);if(!$||!$.baseUrl)return;return{baseUrl:$.baseUrl,modelId:$.modelId,knownModels:$.knownModels,capabilities:JZ($.capabilities)}}async function Y8(f,$,J){let W=S6(f);if(!W)return;try{let H=$?.loadLatestOnInit?await q1($):void 0,Q=H?SF(f,H):{},Z=J&&lF(f,$,J)?await pF(f,$,J):{},P=Boolean(Af.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:W.modelId,baseUrl:W.baseUrl}:J,X=P?await cF(f,$,P).catch(()=>({})):{},V=await EF(f,W.knownModels,Q,Z,X,J?.knownModels);return{...W,knownModels:V}}catch(H){if($?.failOnError)throw H;return W}}var B8=qf.BUILT_IN_PROVIDER,M5=qf.BUILT_IN_PROVIDER_IDS,_5=qf.isBuiltInProviderId,b1=qf.normalizeProviderId,A8=_.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),k6=_.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),m6=_.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),I6=_.object({apiKey:_.string().optional(),accessToken:_.string().optional(),refreshToken:_.string().optional(),expiresAt:_.number().int().positive().optional(),accountId:_.string().optional()}),aF=_.enum(["none","low","medium","high","xhigh"]),x6=_.object({enabled:_.boolean().optional(),effort:aF.optional(),budgetTokens:_.number().int().positive().optional()}),g6=_.object({accessKey:_.string().optional(),secretKey:_.string().optional(),sessionToken:_.string().optional(),region:_.string().optional(),profile:_.string().optional(),authentication:_.enum(["iam","api-key","profile"]).optional(),usePromptCache:_.boolean().optional(),useCrossRegionInference:_.boolean().optional(),useGlobalInference:_.boolean().optional(),endpoint:_.string().url().optional(),customModelBaseId:_.string().optional()}),v6=_.object({projectId:_.string().optional(),region:_.string().optional()}),u6=_.object({apiVersion:_.string().optional(),useIdentity:_.boolean().optional()}),c6=_.object({clientId:_.string().optional(),clientSecret:_.string().optional(),tokenUrl:_.string().url().optional(),resourceGroup:_.string().optional(),deploymentId:_.string().optional(),useOrchestrationMode:_.boolean().optional(),api:_.enum(["orchestration","foundation-models"]).optional(),defaultSettings:_.record(_.string(),_.unknown()).optional()}),d6=_.object({mode:_.enum(["internal","external"]).optional(),usePromptCache:_.boolean().optional()}),r6=_.object({loadLatestOnInit:_.boolean().optional(),loadPrivateOnAuth:_.boolean().optional(),url:_.string().url().optional(),cacheTtlMs:_.number().int().positive().optional(),failOnError:_.boolean().optional()}),n0=_.object({provider:A8,apiKey:_.string().optional(),auth:I6.optional(),model:_.string().optional(),protocol:k6.optional(),client:m6.optional(),routingProviderId:A8.optional(),maxTokens:_.number().int().positive().optional(),contextWindow:_.number().int().positive().optional(),baseUrl:_.string().url().optional(),headers:_.record(_.string(),_.string()).optional(),timeout:_.number().int().positive().optional(),reasoning:x6.optional(),aws:g6.optional(),gcp:v6.optional(),azure:u6.optional(),sap:c6.optional(),oca:d6.optional(),region:_.string().optional(),apiLine:_.enum(["china","international"]).optional(),capabilities:_.array(_.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth"])).optional(),modelCatalog:r6.optional()});function l6(f){return n0.parse(f)}function p6(f){return n0.safeParse(f)}function tF(f){return f.protocol==="openai-responses"||f.client==="openai"}function bf(f,$={}){let J=f.provider,W=b1(J),H=$.includeKnownModels!==!1,Q=f.reasoning?.effort||"none",Z=Q==="none"?void 0:Q,j=V8[W],P=Object.assign({},...qf.resolveProviderModelCatalogKeys(W).map((U)=>qf.getGeneratedModelsForProvider(U))),X=Object.keys(P)[0],V=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,Y=f.baseUrl??(W==="oca"?f.oca?.mode==="internal"?z1:O1:j?.baseUrl),B=f.routingProviderId??(tF(f)&&W!==B8.OPENAI_NATIVE?B8.OPENAI_NATIVE:void 0),A=H?j?.knownModels??(Object.keys(P).length>0?P:void 0):void 0,R={providerId:J,clientType:f.client,routingProviderId:B,modelId:f.model??j?.modelId??X??"default",...H?{knownModels:A}:{},apiKey:V,accessToken:f.auth?.accessToken,refreshToken:f.auth?.refreshToken,accountId:f.auth?.accountId,baseUrl:Y,headers:f.headers,timeoutMs:f.timeout,maxOutputTokens:f.maxTokens,maxContextTokens:f.contextWindow,thinking:f.reasoning?.enabled,reasoningEffort:Z,thinkingBudgetTokens:f.reasoning?.budgetTokens,region:f.region??f.aws?.region??f.gcp?.region,apiLine:f.apiLine,useCrossRegionInference:f.aws?.useCrossRegionInference,useGlobalInference:f.aws?.useGlobalInference,aws:f.aws?{accessKey:f.aws.accessKey,secretKey:f.aws.secretKey,sessionToken:f.aws.sessionToken,authentication:f.aws.authentication,profile:f.aws.profile,usePromptCache:f.aws.usePromptCache,endpoint:f.aws.endpoint,customModelBaseId:f.aws.customModelBaseId}:void 0,gcp:f.gcp?{projectId:f.gcp.projectId,region:f.gcp.region}:void 0,azure:f.azure,sap:f.sap,oca:f.oca,capabilities:f.capabilities??j?.capabilities,modelCatalog:f.modelCatalog?{loadLatestOnInit:f.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:f.modelCatalog.loadPrivateOnAuth,url:f.modelCatalog.url,cacheTtlMs:f.modelCatalog.cacheTtlMs,failOnError:f.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(R).filter(([U,y])=>y!==void 0))}function L5(f){let $=l6(f);return bf($)}function z5(f){let $=p6(f);if($.success)return{success:!0,config:bf($.data)};return{success:!1,error:$.error}}var R8=n0;var i6=a0.object({settings:n0,updatedAt:a0.string().datetime(),tokenSource:a0.enum(["manual","oauth","migration"]).default("manual")}),w1=a0.object({version:a0.literal(1),lastUsedProvider:a0.string().min(1).optional(),providers:a0.record(a0.string(),i6)});function t0(){return{version:1,providers:{}}}G0();var YZ={};N(YZ,{InMemoryWorkspaceManager:()=>E1});import{upsertWorkspaceInfo as fy,WorkspaceManifestSchema as N5}from"@cline/shared";var VZ={};N(VZ,{normalizeWorkspacePath:()=>D0,generateWorkspaceInfoWithDiagnostics:()=>F8,generateWorkspaceInfo:()=>C1,buildWorkspaceMetadataWithInfo:()=>O5,buildWorkspaceMetadata:()=>y8});import{basename as sF,resolve as oF}from"node:path";import{performance as PZ}from"node:perf_hooks";import{processWorkspaceInfo as XZ}from"@cline/shared";import eF from"simple-git";function D0(f){return oF(f)}async function C1(f){return(await F8(f)).info}function n6(f){if(f instanceof Error)return{errorType:f.name?.trim()||f.constructor.name||"Error",message:f.message};return{errorType:"Error",message:String(f)}}async function F8(f){let $=D0(f),J={rootPath:$,hint:sF($)},W;try{let H=eF({baseDir:$});if(!await H.checkIsRepo())return{info:J,vcsType:"none"};try{let Z=await H.getRemotes(!0);if(Z.length>0){let j=Z.map((P)=>{let X=P.refs.fetch||P.refs.push;return`${P.name}: ${X}`});J.associatedRemoteUrls=j}}catch(Z){W??=n6(Z)}try{let Z=(await H.revparse(["HEAD"])).trim();if(Z.length>0)J.latestGitCommitHash=Z}catch(Z){W??=n6(Z)}try{let Z=(await H.branch()).current.trim();if(Z.length>0)J.latestGitBranchName=Z}catch(Z){W??=n6(Z)}return{info:J,vcsType:"git",error:W}}catch(H){return{info:J,vcsType:"none",error:n6(H)}}}async function y8(f){let $=await C1(f);return XZ($)}async function O5(f){let $=PZ.now(),J=await F8(f),W=PZ.now()-$,H=J.info;return{workspaceInfo:H,workspaceMetadata:XZ(H),durationMs:W,vcsType:J.vcsType,initError:J.error}}class E1{manifest;listeners=new Set;constructor(f){this.manifest=N5.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await C1(f);return this.manifest=fy(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=D0(f),J=this.manifest.workspaces[$];if(J)return this.manifest=N5.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath($);return this.manifest=N5.parse({...this.manifest,currentWorkspacePath:W.rootPath}),this.emit({type:"workspace_switched",workspace:W}),W}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}getCurrentWorkspace(){let f=this.manifest.currentWorkspacePath;if(!f)return;return this.manifest.workspaces[f]}getWorkspace(f){let $=D0(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}Gf();import{createHash as $y}from"node:crypto";var BZ=new Set,AZ=new Set;function Jy(f){return $y("sha256").update(f).digest("hex")}function Wy(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function RZ(f){if(!f.telemetry)return;let $=Jy(f.rootPath),J=f.rootCount??1;if(!BZ.has($))BZ.add($),r4(f.telemetry,{root_count:J,vcs_types:Wy(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!AZ.has($)){AZ.add($);let W=Error(f.initError.message);W.name=f.initError.errorType||"Error",l4(f.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function Qy(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function Zy(f,$,J){if($.length>0)for(let Q of $)J?.log(Q.message,{severity:"warn"});if(f.length===0)return;let W=f.slice(0,3).map(Qy).join("; "),H=f.length>3?`; and ${f.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${W}${H}. Use --verbose for more details.`,{severity:"warn"});for(let Q of f)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function jy(f,$){let J=typeof f.thinking==="boolean",W=typeof f.reasoningEffort==="string";if(!J&&!W)return $;return{...$??{},...J?{enabled:f.thinking}:{},...W?{effort:f.reasoningEffort}:{}}}function Py(f,$){return Hy(f,$)}function Xy(f){let $=0;for(let J of f??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;$+=1}return $}function Vy(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||Yy(f.accessToken);if($.originator="cline",$.session_id=f.sessionId,$["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)$["ChatGPT-Account-Id"]=J;return $}function Yy(f){let $=f?.trim();if(!$)return;let J=Rf($),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let H=J?.organizations?.[0]?.id;if(typeof H==="string"&&H.length>0)return H;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function By(f,$,J,W,H){let Q=J.getProviderSettings(f.providerId),Z=W||Q?.modelCatalog?{...W??{},...Q?.modelCatalog??{}}:void 0,j={...Q??{},provider:f.providerId,model:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.providerId==="openai-codex"?Vy({sessionId:$,configHeaders:f.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:f.apiKey??Q?.auth?.accessToken??Q?.apiKey}):f.headers??Q?.headers,reasoning:jy(f,Q?.reasoning),modelCatalog:Z},P=bf(j);if(f.knownModels)P.knownModels=f.knownModels;if(f.extensionContext)P.extensionContext=f.extensionContext;let V=f.fetch??P.fetch??H;if(V)P.fetch=V;return P}async function FZ(f){let{input:$,sessionId:J,providerSettingsManager:W,defaultTelemetry:H,defaultCapabilities:Q,defaultToolPolicies:Z,defaultFetch:j,onPluginEvent:P,onTeamEvent:X,createSpawnTool:V,localRuntime:Y,readSessionMetadata:B,writeSessionMetadata:A}=f,R=d0($.config),{modelCatalogDefaults:U,userInstructionService:y,configExtensions:F,onTeamRestored:K,...M}=Y??{},h=Object.keys(M).length>0?M:void 0,{workspaceInfo:G,workspaceMetadata:T,durationMs:z,vcsType:u,initError:vf}=await O5(R),a=h?.extensionContext,c={...a??{},workspace:{...G,...a?.workspace??{}},session:{...a?.session??{},sessionId:J},logger:a?.logger??h?.logger,telemetry:a?.telemetry??h?.telemetry??H};RZ({telemetry:c.telemetry,rootPath:G.rootPath,workspaceInfo:G,rootCount:1,vcsType:u,durationMs:z,initError:vf,featureFlagEnabled:!0});let d=L1({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:h?.logger,workspaceInfo:G}),t=s7(h?.hooks)?void 0:_1({rootSessionId:J,workspacePath:R,workspaceInfo:G}),nf=w$([h?.hooks,t]),C;if(Py(F,"plugins"))try{C=await h1({pluginPaths:h?.pluginPaths,workspacePath:R,cwd:$.config.cwd,onEvent:P,providerId:$.config.providerId,modelId:$.config.modelId,workspaceInfo:G,session:c.session,client:c.client,user:c.user,logger:c.logger,telemetry:c.telemetry,automation:c.automation}),Zy(C.failures,C.warnings,h?.logger)}catch(y2){let r=y2 instanceof Error?y2.message:String(y2);h?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let uf=dW(d?[d]:void 0,dW(h?.extensions,X6(C?.extensions))),$f={...$.config,...h??{},sessionId:J,hooks:nf,extensions:uf,extensionContext:c,telemetry:c.telemetry},R2=By($f,J,W,U,j),P$=w$([$f.hooks,$f.checkpoint?.enabled===!0?kQ({cwd:$f.cwd,sessionId:J,logger:$f.logger,createCheckpoint:$f.checkpoint?.createCheckpoint,initialRunCount:Xy($.initialMessages),readSessionMetadata:B,writeSessionMetadata:A}):void 0]),X$={...$f,providerConfig:R2,workspaceMetadata:T,hooks:P$},e$=$.toolPolicies??$f.toolPolicies??Z,F2=Vf(Q,$.capabilities),z4=F2?.requestToolApproval,QW=F2?.toolExecutors,f1=new E1({currentWorkspacePath:G.rootPath,workspaces:{[G.rootPath]:G}});return{effectiveInput:$,config:X$,providerConfig:R2,workspaceMetadata:T,workspaceInfo:G,extensions:uf,hooks:P$,toolPolicies:e$,requestToolApproval:z4,pluginSandboxShutdown:C?.shutdown,runtimeBuilderInput:{config:X$,hooks:P$,extensions:uf,onTeamEvent:X,createSpawnTool:V,onTeamRestored:K,userInstructionService:y,configExtensions:F,toolExecutors:QW,workspaceManager:f1,logger:X$.logger,telemetry:X$.telemetry}}}import{existsSync as t6,mkdirSync as Ay,readdirSync as Ry,rmdirSync as Fy,rmSync as yy,unlinkSync as Ky}from"node:fs";import{dirname as yZ,join as a6}from"node:path";function s(){return new Date().toISOString()}function K8(f){if(!f||!t6(f))return;try{Ky(f)}catch{}}function Uy(f){let $=R1(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=u2(f);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:f,fileStem:f}}class q5{ensureSessionsDir;constructor(f){this.ensureSessionsDir=f}sessionArtifactsDir(f){return a6(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!t6($))Ay($,{recursive:!0});return $}sessionMessagesPath(f){return a6(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return a6(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!t6($)){$=yZ($);continue}try{if(Ry($).length>0)break;Fy($)}catch{break}$=yZ($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!t6(f))return;try{yy(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:W,fileStem:H}=Uy(f),Q=this.sessionArtifactsDir(W);return{messagesPath:a6(Q,`${H}.messages.json`)}}}import{resolveDocumentsExtensionPath as Gy}from"@cline/shared/storage";Gf();function KZ(f,$,J,W,H){if(J)i4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});else p4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});Ty(f.telemetry,{workspacePath:W})}function Ty(f,$){let J=Gy("Hooks"),W=l0($.workspacePath),H=new Map;for(let Q of W){let Z=Q.hookEventName??"unknown",j=H.get(Z)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))j.global+=1;else j.workspace+=1;H.set(Z,j)}for(let[Q,Z]of H.entries())W6(f,Q,Z.global,Z.workspace)}function UZ(f,$){for(let J of $.mentions)$6(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)e4(f,"file",J.length);for(let J of $.ignoredMentions)f6(f,"file","not_found",J)}var nV={};N(nV,{ProviderSettingsManager:()=>P0});import{chmodSync as tV,existsSync as f3,mkdirSync as qL,readFileSync as bL,writeFileSync as wL}from"node:fs";import{basename as sV,dirname as $3}from"node:path";import{resolveProviderSettingsPath as CL}from"@cline/shared/storage";var L={};N(L,{writeHubDiscovery:()=>KJ,writeGlobalSettings:()=>L$,withHubStartupLock:()=>UJ,verifyHubConnection:()=>f0,updateLocalProvider:()=>nJ,truncateNotificationBody:()=>y4,toggleDisabledTool:()=>j6,toTeamProgressLifecycleEvent:()=>p1,toProviderConfig:()=>bf,toHubHealthUrl:()=>hH,toHookConfigFileName:()=>H8,summarizeUsageFromMessages:()=>a2,stopLocalHubServerGracefully:()=>CH,startLocalOAuthServer:()=>h0,startHubWebSocketServer:()=>t$,startHubServer:()=>oX,startClineDeviceAuth:()=>k5,splitCoreSessionConfig:()=>v8,spawnDetachedHubServer:()=>u1,setTelemetryOptOutGlobally:()=>YQ,setDisabledTools:()=>tW,setDisabledPlugin:()=>FQ,sendHubCommand:()=>HX,saveLocalProviderSettings:()=>m9,saveLocalProviderOAuthCredentials:()=>v9,sanitizeTeamName:()=>I4,sanitizeSessionToken:()=>h$,safeParseSettings:()=>p6,safeCreateProviderConfig:()=>z5,runSubprocessEvent:()=>f2,runHook:()=>J2,reviveTeamStateDates:()=>m4,restartLocalHubIfIdleAfterStartupTimeout:()=>hJ,resolveWorkspaceHubOwnerContext:()=>aj,resolveWorkflowsConfigSearchPaths:()=>E8,resolveSkillsConfigSearchPaths:()=>w8,resolveSharedHubOwnerContext:()=>Qf,resolveSessionBackend:()=>sH,resolveRulesConfigSearchPaths:()=>C8,resolveProviderConfig:()=>Y8,resolvePluginConfigSearchPaths:()=>f8,resolveMcpServerRegistrations:()=>Y4,resolveLocalClineAuthToken:()=>u9,resolveHubUrl:()=>H9,resolveHubOwnerContext:()=>M0,resolveHubEndpointOptions:()=>Sf,resolveHubBuildId:()=>J$,resolveHooksConfigSearchPaths:()=>J8,resolveDisabledToolNames:()=>rf,resolveDisabledPluginPaths:()=>o2,resolveDefaultMcpSettingsPath:()=>Q$,resolveDefaultHubPort:()=>v1,resolveDefaultHubPathname:()=>zH,resolveDefaultHubHost:()=>LH,resolveCoreSelectedToolIds:()=>g4,resolveCompatibleLocalHubUrl:()=>f4,resolveClineDir:()=>lj,resolveClineDataDir:()=>t8,resolveAndLoadAgentPlugins:()=>h1,resolveAgentPluginPaths:()=>O$,requestHubShutdown:()=>e8,requestDesktopToolApproval:()=>N9,rememberRecoverableLocalHubUrl:()=>W$,registerMcpServersFromSettingsFile:()=>o1,registerDisposable:()=>zL,refreshProviderModelsFromSource:()=>I9,refreshOpenAICodexToken:()=>M8,refreshOcaToken:()=>j8,refreshClineToken:()=>h8,readSessionCheckpointHistory:()=>K4,readHubDiscovery:()=>Zf,readGlobalSettings:()=>of,probeHubServer:()=>Bf,probeHubConnection:()=>WX,prewarmFileIndex:()=>b4,prewarmDetachedHubServer:()=>GJ,parseWorkflowConfigFromMarkdown:()=>b8,parseUserCommandEnvelope:()=>LL,parseSkillConfigFromMarkdown:()=>N8,parseSettings:()=>l6,parseRuleConfigFromMarkdown:()=>q8,parseHookEventPayload:()=>$2,openaiCodexOAuthProvider:()=>v5,normalizeWorkspacePath:()=>D0,normalizeUserInput:()=>_L,normalizeRuntimeCapabilities:()=>Vf,normalizeProviderId:()=>b1,normalizeOpenAICodexCredentials:()=>g5,normalizeOAuthProvider:()=>x9,normalizeHubWebSocketUrl:()=>H$,noopBasicLogger:()=>ML,migrateLegacyProviderSettings:()=>_4,mergeRulesForSystemPrompt:()=>g1,mergeAgentHooks:()=>w$,makeTeamTaskSubSessionId:()=>v2,makeSubSessionId:()=>A1,loginOpenAICodex:()=>m1,loginOcaOAuth:()=>N1,loginLocalProvider:()=>g9,loginClineOAuth:()=>k1,loadOpenTelemetryAdapter:()=>AL,loadMcpSettingsFile:()=>V4,loadLlmsConfigFromFile:()=>s9,loadAgentPluginsFromPathsWithDiagnostics:()=>T0,loadAgentPluginsFromPaths:()=>B6,loadAgentPluginFromPath:()=>e2,listSessionHistoryFromBackend:()=>KH,listPluginTools:()=>g8,listLocalProviders:()=>S9,listHookConfigFiles:()=>l0,isToolDisabledGlobally:()=>BQ,isTelemetryOptedOutGlobally:()=>Z6,isRuleEnabled:()=>jJ,isPluginDisabledGlobally:()=>RQ,isOpenAICodexTokenExpired:()=>x5,isHubReconnectableTransportError:()=>bH,isHubCommandTimeoutError:()=>TJ,isDiscoveryFilePresent:()=>ij,isClineAccountActionRequest:()=>s6,isBuiltInProviderId:()=>_5,identifyAccount:()=>K0,hasMcpSettingsFile:()=>s1,getValidOpenAICodexCredentials:()=>_8,getValidOcaCredentials:()=>P8,getValidClineCredentials:()=>D8,getProviderConfigFields:()=>c9,getProviderConfig:()=>S6,getLocalProviderModels:()=>k9,getLiveModelsCatalog:()=>q1,getFileIndex:()=>Y0,getCurrentContextSize:()=>iW,getCoreHeadlessToolNames:()=>g2,getCoreDefaultEnabledToolIds:()=>x4,getCoreBuiltinToolCatalog:()=>G$,getCoreAcpToolNames:()=>v4,getClineDefaultSystemPrompt:()=>FL,generateWorkspaceInfoWithDiagnostics:()=>F8,generateWorkspaceInfo:()=>C1,generateOcaOpcRequestId:()=>z6,formatRulesForSystemPrompt:()=>x1,formatDisplayUserInput:()=>DL,filterExtensionToolRegistrations:()=>X6,filterDisabledTools:()=>z$,filterDisabledPluginPaths:()=>P6,fetchClineRecommendedModels:()=>a9,executeClineAccountAction:()=>o6,ensureHubWebSocketServer:()=>vJ,ensureHubServer:()=>eX,ensureDetachedHubServer:()=>sj,ensureCustomProvidersLoaded:()=>iJ,ensureCompatibleLocalHubUrl:()=>g$,enrichPromptWithMentions:()=>H1,emptyWorkspaceManifest:()=>hL,emptyStoredProviderSettings:()=>t0,discoverPluginModulePaths:()=>$8,deriveSubsessionStatus:()=>c2,deleteLocalProvider:()=>aJ,defineLlmsConfig:()=>t9,createWorkflowsConfigDefinition:()=>m8,createUserInstructionConfigService:()=>o0,createToolPoliciesWithPreset:()=>C4,createTool:()=>TL,createTeamName:()=>cJ,createSubprocessHooks:()=>wJ,createSpawnAgentTool:()=>I0,createSkillsConfigDefinition:()=>S8,createSessionHost:()=>a1,createRuntimeHost:()=>a1,createRulesConfigDefinition:()=>k8,createProviderConfig:()=>L5,createOpenTelemetryTelemetryService:()=>F4,createOcaRequestHeaders:()=>A5,createOcaOAuthProvider:()=>B5,createOAuthClientCallbacks:()=>T8,createMcpTools:()=>e1,createLocalHubScheduleRuntimeHandlers:()=>uJ,createLlmsSdk:()=>e9,createInitialAccumulatedUsage:()=>u0,createInMemoryHubOwnerContext:()=>pj,createHubServerUrl:()=>lf,createHubAuthToken:()=>yJ,createHookConfigFileHooks:()=>Q8,createHookConfigFileExtension:()=>L1,createHookAuditHooks:()=>_1,createDisabledMcpToolPolicy:()=>B4,createDisabledMcpToolPolicies:()=>NJ,createDelegatedAgentConfigProvider:()=>X1,createDelegatedAgent:()=>V1,createDefaultToolsWithPreset:()=>E4,createDefaultTools:()=>S0,createDefaultMcpServerClientFactory:()=>t1,createDefaultExecutors:()=>Q1,createCoreSettingsService:()=>S$,createCoreSessionSnapshot:()=>$0,createContributionRegistry:()=>GL,createContextCompactionPrepareTurn:()=>h2,createConfiguredTelemetryService:()=>i$,createConfiguredTelemetryHandle:()=>j2,createClineTelemetryServiceMetadata:()=>UL,createClineTelemetryServiceConfig:()=>KL,createClineOAuthProvider:()=>I5,createBuiltinTools:()=>T$,createAgentTeamsTools:()=>U$,createAgentRuntime:()=>NL,createAgentHooksExtension:()=>D1,connectToHub:()=>kJ,completeClineDeviceAuth:()=>m5,clearPrivateModelsCatalogCache:()=>D5,clearLiveModelsCatalogCache:()=>h5,clearHubDiscovery:()=>Ef,captureWorkspacePathResolved:()=>HQ,captureWorkspaceInitialized:()=>r4,captureWorkspaceInitError:()=>l4,captureToolUsage:()=>t4,captureTokenUsage:()=>n4,captureTaskRestarted:()=>i4,captureTaskCreated:()=>p4,captureTaskCompleted:()=>p2,captureSubagentExecution:()=>n2,captureSkillUsed:()=>s4,captureProviderApiError:()=>i2,captureModeSwitch:()=>a4,captureMentionUsed:()=>e4,captureMentionSearchResults:()=>$6,captureMentionFailed:()=>f6,captureHookDiscovery:()=>W6,captureExtensionActivated:()=>WQ,captureDiffEditFailure:()=>o4,captureConversationTurnEvent:()=>F1,captureAuthSucceeded:()=>F0,captureAuthStarted:()=>R0,captureAuthLoggedOut:()=>g0,captureAuthFailed:()=>y0,captureAgentTeamCreated:()=>J6,captureAgentCreated:()=>v0,buildWorkspaceMetadata:()=>y8,buildTeamProgressSummary:()=>l1,buildDelegatedAgentConfig:()=>y$,bootstrapAgentTeams:()=>B1,addLocalProvider:()=>E9,accumulateUsageTotals:()=>c0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>O8,UnifiedConfigFileWatcher:()=>C$,ToolPresets:()=>Nf,TelemetryService:()=>Q2,TelemetryLoggerSink:()=>R4,TEAM_TOOL_NAMES:()=>Y1,SubprocessSandbox:()=>T1,StoredProviderSettingsSchema:()=>w1,StoredProviderSettingsEntrySchema:()=>i6,SqliteTeamStore:()=>s$,SqliteSessionStore:()=>W0,SessionVersioningService:()=>j$,SessionVersioningError:()=>Df,SessionSource:()=>Pf,SapSettingsSchema:()=>c6,SKILLS_CONFIG_DIRECTORY_NAME:()=>z8,SESSION_STATUSES:()=>d2,RpcClineAccountService:()=>G8,RemoteRuntimeHost:()=>r1,ReasoningSettingsSchema:()=>x6,RULES_CONFIG_DIRECTORY_NAME:()=>ZJ,ProviderSettingsSchema:()=>n0,ProviderSettingsManager:()=>P0,ProviderProtocolSchema:()=>k6,ProviderIdSchema:()=>A8,ProviderClientSchema:()=>m6,OpenTelemetryProvider:()=>Z2,OcaSettingsSchema:()=>d6,OPENAI_COMPATIBLE_PROVIDERS:()=>V8,OCI_HEADER_OPC_REQUEST_ID:()=>_6,NodeHubClient:()=>pf,NativeHubTransportAdapter:()=>h4,ModelCatalogSettingsSchema:()=>r6,LocalRuntimeHost:()=>Z0,Llms:()=>RL,InMemoryWorkspaceManager:()=>E1,InMemoryMcpManager:()=>r$,HubUIClient:()=>Z9,HubTransportError:()=>yf,HubSessionClient:()=>Q9,HubServerTransport:()=>X2,HubScheduleService:()=>H2,HubScheduleCommandService:()=>W2,HubRuntimeHost:()=>_0,HubCommandError:()=>c1,HookEventPayloadSchema:()=>bJ,HookEventNameSchema:()=>qJ,HookConfigFileName:()=>M1,HOOK_CONFIG_FILE_EVENT_MAP:()=>W8,HOOKS_CONFIG_DIRECTORY_NAME:()=>F6,GlobalSettingsSchema:()=>s2,GcpSettingsSchema:()=>v6,FileTeamPersistenceStore:()=>tJ,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>JW,DefaultToolNames:()=>ff,DefaultRuntimeBuilder:()=>B2,DefaultLlmsSdk:()=>L4,DEFAULT_MODELS_CATALOG_URL:()=>C6,DEFAULT_INTERNAL_OCA_BASE_URL:()=>z1,DEFAULT_INTERNAL_IDCS_URL:()=>G6,DEFAULT_INTERNAL_IDCS_SCOPES:()=>T6,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>U6,DEFAULT_HUB_PORT:()=>MH,DEFAULT_HUB_PATHNAME:()=>_H,DEFAULT_HUB_HOST:()=>DH,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>O1,DEFAULT_EXTERNAL_IDCS_URL:()=>D6,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>M6,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>h6,CoreSettingsService:()=>e0,CoreSessionService:()=>Q0,ContributionRegistry:()=>yL,ClineCore:()=>P4,ClineAccountService:()=>U8,ChatViewStateSchema:()=>i9,ChatSummarySchema:()=>$W,ChatSessionStatusSchema:()=>oJ,ChatSessionConfigSchema:()=>sJ,ChatMessageSchema:()=>fW,ChatMessageRoleSchema:()=>eJ,CORE_TELEMETRY_EVENTS:()=>g,CORE_BUILD_VERSION:()=>n9,BrowserWebSocketHubAdapter:()=>T4,BUILT_IN_PROVIDER_IDS:()=>M5,BUILT_IN_PROVIDER:()=>B8,AzureSettingsSchema:()=>u6,AwsSettingsSchema:()=>g6,AuthSettingsSchema:()=>I6,AgentTeamsRuntime:()=>d$,AgentTeam:()=>n1,Agent:()=>OL,ALL_DEFAULT_TOOL_NAMES:()=>q0});O(L,Fg);import*as RL from"@cline/llms";import{buildClineSystemPrompt as FL,ContributionRegistry as yL,createClineTelemetryServiceConfig as KL,createClineTelemetryServiceMetadata as UL,createContributionRegistry as GL,createTool as TL,emptyWorkspaceManifest as hL,formatDisplayUserInput as DL,noopBasicLogger as ML,normalizeUserInput as _L,parseUserCommandEnvelope as LL,registerDisposable as zL}from"@cline/shared";import"@cline/shared/storage";var TZ={};N(TZ,{isClineAccountActionRequest:()=>s6,executeClineAccountAction:()=>o6,RpcClineAccountService:()=>G8,ClineAccountService:()=>U8});function hy(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function GZ(f,$,J){let W=hy(J);if(W)return W;let H=$.trim();if(H){let Q=H.length>200?`${H.slice(0,200)}...`:H;return`Cline account request failed with status ${f}: ${Q}`}return`Cline account request failed with status ${f}`}class U8{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(f){let $=f.apiBaseUrl.trim();if(!$)throw Error("apiBaseUrl is required");this.apiBaseUrl=$,this.getAuthTokenFn=f.getAuthToken,this.getCurrentUserIdFn=f.getCurrentUserId,this.getOrganizationMemberIdFn=f.getOrganizationMemberId,this.getHeadersFn=f.getHeaders,this.requestTimeoutMs=f.requestTimeoutMs??30000,this.fetchImpl=f.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance(f){let $=await this.resolveUserId(f);return this.request(`/api/v1/users/${encodeURIComponent($)}/balance`)}async fetchUsageTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/usages`)).items??[]}async fetchPaymentTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}`)}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}/balance`)}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId($,f.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent($)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount(f){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:f?.trim()||null},expectNoContent:!0})}async resolveUserId(f){let $=f?.trim();if($)return $;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let H=await this.fetchMe();if(!H.id?.trim())throw Error("Unable to resolve current user id");return H.id}async resolveOrganizationMemberId(f,$){let J=$?.trim();if(J)return J;let H=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(f):void 0)?.trim();if(H)return H;let Z=(await this.fetchUserOrganizations()).find((j)=>j.organizationId===f)?.memberId;if(!Z?.trim())throw Error(`Unable to resolve memberId for organization ${f}`);return Z}async request(f,$){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},H=new AbortController,Q=setTimeout(()=>H.abort(),this.requestTimeoutMs);try{let Z=await this.fetchImpl(new URL(f,this.apiBaseUrl),{method:$?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...W??{}},body:$?.body!==void 0?JSON.stringify($.body):void 0,signal:H.signal});if(Z.status===204||$?.expectNoContent){if(!Z.ok)throw Error(`Cline account request failed with status ${Z.status}`);return}let j=await Z.text(),P;if(j.trim())try{P=JSON.parse(j)}catch{if(!Z.ok)throw Error(GZ(Z.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Z.ok)throw Error(GZ(Z.status,j,P));if(typeof P==="object"&&P!==null){let X=P;if(typeof X.success==="boolean"){if(!X.success)throw Error(X.error||"Cline account request failed");if(X.data!==void 0)return X.data}}if(P===void 0||P===null)throw Error("Cline account response payload was empty");return P}finally{clearTimeout(Q)}}}function s6(f){return f.action==="clineAccount"}async function o6(f,$){switch(f.operation){case"fetchMe":return $.fetchMe();case"fetchBalance":return $.fetchBalance(f.userId);case"fetchUsageTransactions":return $.fetchUsageTransactions(f.userId);case"fetchPaymentTransactions":return $.fetchPaymentTransactions(f.userId);case"fetchUserOrganizations":return $.fetchUserOrganizations();case"fetchOrganizationBalance":return $.fetchOrganizationBalance(f.organizationId);case"fetchOrganizationUsageTransactions":return $.fetchOrganizationUsageTransactions({organizationId:f.organizationId,memberId:f.memberId});case"switchAccount":return await $.switchAccount(f.organizationId),{updated:!0};case"fetchFeaturebaseToken":return $.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String(f)}`)}}class G8{executor;constructor(f){this.executor=f}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(f){return this.request({action:"clineAccount",operation:"fetchBalance",...f?.trim()?{userId:f.trim()}:{}})}async fetchUsageTransactions(f){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchPaymentTransactions(f){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:$})}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:$,...f.memberId?.trim()?{memberId:f.memberId.trim()}:{}})}async switchAccount(f){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:f?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request(f){return(await this.executor.runProviderAction(f)).result}}var hZ={};N(hZ,{createOAuthClientCallbacks:()=>T8});function T8(f){return{onAuth:({url:$,instructions:J})=>{if(f.onOutput?.(J??"Complete sign-in in your browser."),f.openUrl)try{Promise.resolve(f.openUrl($)).catch((W)=>{f.onOpenUrlError?.({url:$,error:W})})}catch(W){f.onOpenUrlError?.({url:$,error:W})}f.onOutput?.($)},onPrompt:f.onPrompt,onServerListening:f.onServerListening,onServerClose:f.onServerClose}}Gf();var qZ={};N(qZ,{startClineDeviceAuth:()=>k5,refreshClineToken:()=>h8,loginClineOAuth:()=>k1,getValidClineCredentials:()=>D8,createClineOAuthProvider:()=>I5,completeClineDeviceAuth:()=>m5});var e6={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},LZ={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},b5="https://api.workos.com",w5="client_01K3A541FN8TA3EPPHTD2325AR",Dy="/auth",DZ=Array.from({length:11},(f,$)=>48801+$),My=300000,_y=30000,S1=30000,Ly=300,zy=5;class s0 extends Error{status;errorCode;constructor(f,$){super(f);this.name="ClineOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function Oy(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function C5(f,$,J={}){let W=f.userInfo.clineUserId??J.accountId,H=f.refreshToken??J.refresh;if(!H)throw Error("Token response did not include a refresh token");return{access:f.accessToken,refresh:H,expires:Oy(f.expiresAt),accountId:W??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function E5(f){if(!f)return{};return typeof f==="function"?await f():f}function MZ(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function _Z(f){await new Promise(($)=>setTimeout($,f))}function S5(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function zZ(f,$){let J=await fetch(M$(b5,LZ.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??S1)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new s0(`Device authorization failed: ${J.status}${W.error_description?` - ${W.error_description}`:""}`,{status:J.status,errorCode:W.error});if(!W.device_code||!W.user_code||!W.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:W.device_code,userCode:W.user_code,verificationUri:W.verification_uri,verificationUriComplete:W.verification_uri_complete,expiresInSeconds:MZ(W.expires_in,Ly),pollIntervalSeconds:MZ(W.interval,zy)}}async function OZ(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let W=await fetch(M$(f.workosApiBaseUrl,LZ.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:f.deviceCode,client_id:f.clientId}),signal:AbortSignal.timeout(f.requestTimeoutMs)}),H=await W.json().catch(()=>({}));if(W.ok){if(!H.access_token||!H.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:H.access_token,refreshToken:H.refresh_token,tokenType:H.token_type??"Bearer"}}switch(H.error){case"authorization_pending":{await _Z(J*1000);break}case"slow_down":{J+=1,await _Z(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new s0(H.error_description||"WorkOS authorization failed",{status:W.status,errorCode:H.error});default:throw new s0(`WorkOS token polling failed: ${W.status}${H.error_description?` - ${H.error_description}`:""}`,{status:W.status,errorCode:H.error})}f.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function NZ(f,$,J){let W={accessToken:f.accessToken,refreshToken:f.refreshToken},H=await fetch(M$($.apiBaseUrl,e6.register),{method:"POST",headers:{"Content-Type":"application/json",...await E5($.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout($.requestTimeoutMs??S1)});if(!H.ok){let Z=await H.text().catch(()=>""),j=U1(Z);throw new s0(`Token registration failed: ${H.status}${j.message?` - ${j.message}`:""}`,{status:H.status,errorCode:j.code})}let Q=await H.json();return C5(S5(Q,"Invalid token exchange response"),J??$.provider)}async function Ny(f,$,J,W){let H={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:W??J.provider},Q=await fetch(M$(J.apiBaseUrl,e6.token),{method:"POST",headers:{"Content-Type":"application/json",...await E5(J.headers)},body:JSON.stringify(H),signal:AbortSignal.timeout(J.requestTimeoutMs??S1)});if(!Q.ok){let j=await Q.text().catch(()=>""),P=U1(j);throw new s0(`Token exchange failed: ${Q.status}${P.message?` - ${P.message}`:""}`,{status:Q.status,errorCode:P.code})}let Z=await Q.json();return C5(S5(Z,"Invalid token exchange response"),W??J.provider)}async function k1(f){R0(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:DZ,W=f.callbackPath??Dy,H=$?null:await h0({ports:J,callbackPath:W,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),Q=H?.callbackUrl||`http://127.0.0.1:${J[0]??DZ[0]}${W}`;try{let Z;if($){let j=w5,P=await zZ(j,f);f.callbacks.onAuth({url:P.verificationUriComplete??P.verificationUri,instructions:`Enter this code in your browser: ${P.userCode}`});let X=await OZ({clientId:j,deviceCode:P.deviceCode,expiresInSeconds:P.expiresInSeconds,initialPollIntervalSeconds:P.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??S1,workosApiBaseUrl:b5,onProgress:f.callbacks.onProgress});Z=await NZ(X,f,f.provider)}else{let j=new URL(M$(f.apiBaseUrl,e6.authorize));j.searchParams.set("client_type","extension"),j.searchParams.set("callback_url",Q),j.searchParams.set("redirect_uri",Q),f.callbacks.onAuth({url:j.toString(),instructions:"Continue the authentication process in your browser."});let P,X=f.provider,V=await G1({waitForCallback:H?.waitForCallback??(async()=>null),cancelWait:H?.cancelWait??(()=>{}),onManualCodeInput:f.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(V.error)throw Error(`OAuth error: ${V.error}`);if(P=V.code,X=V.provider??X,!P){let Y=await f.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=K1(Y,{includeProvider:!0});P=B.code,X=B.provider??X}if(!P)throw Error("Missing authorization code");Z=await Ny(P,Q,f,X)}return F0(f.telemetry,f.provider??"cline"),K0(f.telemetry,{id:Z.accountId,email:Z.email,provider:f.provider??"cline"}),Z}catch(Z){throw y0(f.telemetry,f.provider??"cline",Z instanceof Error?Z.message:String(Z)),Z}finally{H?.close()}}async function k5(f){return await zZ(w5,f)}async function m5(f){let $=f.provider??"cline";R0(f.telemetry,$);try{let J=await OZ({clientId:w5,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??S1,workosApiBaseUrl:b5}),W=await NZ(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return F0(f.telemetry,$),K0(f.telemetry,{id:W.accountId,email:W.email,provider:$}),W}catch(J){throw y0(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function h8(f,$){let J=await fetch(M$($.apiBaseUrl,e6.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await E5($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??S1)});if(!J.ok){let Q=await J.text().catch(()=>""),Z=U1(Q);throw new s0(`Token refresh failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let W=await J.json(),H=f.metadata?.provider??$.provider;return C5(S5(W,"Invalid token refresh response"),H,f)}async function D8(f,$,J){if(!f)return null;let W=J?.refreshBufferMs??My,H=J?.retryableTokenGraceMs??_y;if(J?.forceRefresh!==!0&&!_$(f,W))return f;try{return await h8(f,$)}catch(Z){if(Z instanceof s0&&Z.isLikelyInvalidGrant())return g0($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function I5(f){return{id:"cline",name:"Cline Account",usesCallbackServer:!(f.useWorkOSDeviceAuth??!0),async login($){return k1({...f,callbacks:$})},async refreshToken($){return h8($,f)},getApiKey($){return`workos:${$.access}`}}}Gf();var CZ={};N(CZ,{refreshOpenAICodexToken:()=>M8,openaiCodexOAuthProvider:()=>v5,normalizeOpenAICodexCredentials:()=>g5,loginOpenAICodex:()=>m1,isOpenAICodexTokenExpired:()=>x5,getValidOpenAICodexCredentials:()=>_8,OPENAI_CODEX_OAUTH_CONFIG:()=>o});import{nanoid as qy}from"nanoid";var o={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class fJ extends Error{status;errorCode;constructor(f,$){super(f);this.name="OpenAICodexOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function by(f,$,J=o.redirectUri){let W=await fetch(o.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:o.clientId,code:f,code_verifier:$,redirect_uri:J}),signal:AbortSignal.timeout(o.httpTimeoutMs)});if(!W.ok)return{type:"failed"};let H=await W.json();if(!H.access_token||!H.refresh_token||typeof H.expires_in!=="number")return{type:"failed"};return{type:"success",access:H.access_token,refresh:H.refresh_token,expires:Date.now()+H.expires_in*1000,email:H.email,idToken:H.id_token}}async function wy(f){try{let $=await fetch(o.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:f,client_id:o.clientId}),signal:AbortSignal.timeout(o.httpTimeoutMs)});if(!$.ok){let W=await $.text().catch(()=>""),H=U1(W);throw new fJ(`Token refresh failed: ${$.status}${H.message?` - ${H.message}`:""}`,{status:$.status,errorCode:H.code})}let J=await $.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch($){if($ instanceof fJ)throw $;return{type:"failed"}}}async function Cy(f="pi"){let{verifier:$,challenge:J}=await H6(),W=qy(32),H=new URL(o.authorizationEndpoint);return H.searchParams.set("response_type","code"),H.searchParams.set("client_id",o.clientId),H.searchParams.set("redirect_uri",o.redirectUri),H.searchParams.set("scope",o.scopes),H.searchParams.set("code_challenge",J),H.searchParams.set("code_challenge_method","S256"),H.searchParams.set("state",W),H.searchParams.set("id_token_add_organizations","true"),H.searchParams.set("codex_cli_simplified_flow","true"),H.searchParams.set("originator",f),{verifier:$,state:W,url:H.toString()}}function Ey(){try{let f=new URL(o.redirectUri),$=f.port.length>0?Number.parseInt(f.port,10):o.callbackPort;return{host:f.hostname||"localhost",port:Number.isFinite($)?$:o.callbackPort,callbackPath:f.pathname||"/auth/callback",redirectUri:f.toString()}}catch{return{host:"localhost",port:o.callbackPort,callbackPath:"/auth/callback",redirectUri:o.redirectUri}}}function bZ(f,$){let J=$?Rf($):Rf(f),W=J?J:Rf(f),Q=W?.[o.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=W?.organizations;if(Array.isArray(Z)&&Z.length>0){let P=Z[0];if(typeof P?.id==="string"&&P.id.length>0)return P.id}let j=W?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return null}function wZ(f,$){let J=bZ(f.access,f.idToken)??$?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:f.access,refresh:f.refresh||$?.refresh||"",expires:f.expires,accountId:J,email:f.email??$?.email,metadata:{...$?.metadata??{},provider:"openai-codex"}}}async function m1(f){R0(f.telemetry,"openai-codex");let $=Ey(),{verifier:J,state:W,url:H}=await Cy(f.originator),Q=await h0({host:$.host,ports:[$.port],callbackPath:$.callbackPath,expectedState:W});f.onAuth({url:H,instructions:"Continue the authentication process in your browser."});let Z;try{let j=await G1({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:f.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(j.state&&j.state!==W)throw Error("State mismatch");if(Z=j.code,!Z){let V=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),Y=K1(V,{allowHashCodeState:!0});if(Y.state&&Y.state!==W)throw Error("State mismatch");Z=Y.code}if(!Z)throw Error("Missing authorization code");let P=await by(Z,J,$.redirectUri);if(P.type!=="success")throw Error("Token exchange failed");let X=wZ(P);return F0(f.telemetry,"openai-codex"),K0(f.telemetry,{id:X.accountId,email:X.email,provider:"openai-codex"}),X}catch(j){throw y0(f.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{Q.close()}}async function M8(f,$){let J=await wy(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=wZ(J,$);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function _8(f,$){if(!f)return null;let J=$?.refreshBufferMs??o.refreshBufferMs,W=$?.retryableTokenGraceMs??o.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!_$(f,J))return f;try{return await M8(f.refresh,f)}catch(Q){if(Q instanceof fJ&&Q.isLikelyInvalidGrant())return g0($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function x5(f,$=o.refreshBufferMs){return _$(f,$)}function g5(f){let $=f.accountId??bZ(f.access);if(!$)throw Error("Failed to extract accountId from token");return{...f,accountId:$,metadata:{...f.metadata??{},provider:"openai-codex"}}}var v5={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login(f){return m1({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput})},async refreshToken(f){return M8(f.refresh,f)},getApiKey(f){return f.access}};var xP={};N(xP,{ClineCore:()=>P4});function EZ(f){if(f===!0)return{};if(!f)return;return f}function SZ(f){if(f==="user")return"global";return f}class u5{getService;constructor(f){this.getService=f}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent(f){let $=this.getService().ingestEvent(f);return{event:$.event,duplicate:$.duplicate,matchedSpecIds:$.matchedSpecs.map((J)=>J.specId),queuedRuns:$.queuedRuns,suppressions:$.suppressions}}listEvents(f){return this.getService().listEventLogs(f)}getEvent(f){return this.getService().getEventLog(f)}listSpecs(f){return this.getService().listSpecs(f)}listRuns(f){return this.getService().listRuns(f)}}function kZ(f){let{host:$}=f;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),H=await $.startSession({source:J.source?.trim()||Pf.CLI,interactive:!1,config:{providerId:b1(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:my(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:f.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:H.sessionId,startResult:{sessionId:H.sessionId,manifestPath:H.manifestPath,messagesPath:H.messagesPath}}},async sendSession(J,W){let H=await $.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content),delivery:W.delivery});if(!H)throw Error("ClineCore automation runtime returned no result");return{result:ky(H)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function $J(f){let $=Sy(f.automationService,f.automation),J=f.context?.client??(f.clientName?{name:f.clientName}:void 0),W=f.context?.user??(f.distinctId?{distinctId:f.distinctId}:void 0),H=f.context?.logger??f.logger,Q=f.context?.telemetry??f.telemetry;if(!$&&!J&&!W&&!H&&!Q)return f.context;return{...f.context??{},...J?{client:J}:{},...W?{user:W}:{},...H?{logger:H}:{},...Q?{telemetry:Q}:{},...$?{automation:$}:{}}}function Sy(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function ky(f){return{text:f.text,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost},inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function my(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}var Wj={};N(Wj,{createCoreSettingsService:()=>S$,CoreSettingsService:()=>e0});import{existsSync as n5}from"node:fs";import{basename as fj,isAbsolute as VK,relative as YK}from"node:path";var aZ={};N(aZ,{resolveWorkflowsConfigSearchPaths:()=>E8,resolveSkillsConfigSearchPaths:()=>w8,resolveRulesConfigSearchPaths:()=>C8,parseWorkflowConfigFromMarkdown:()=>b8,parseSkillConfigFromMarkdown:()=>N8,parseRuleConfigFromMarkdown:()=>q8,createWorkflowsConfigDefinition:()=>m8,createUserInstructionConfigService:()=>o0,createSkillsConfigDefinition:()=>S8,createRulesConfigDefinition:()=>k8,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>O8,UnifiedConfigFileWatcher:()=>C$,SKILLS_CONFIG_DIRECTORY_NAME:()=>z8,RULES_CONFIG_DIRECTORY_NAME:()=>ZJ});import{createHash as Iy}from"node:crypto";import{watch as xy}from"node:fs";import{readdir as gy,readFile as vy}from"node:fs/promises";import{join as uy}from"node:path";function cy(f){return Iy("sha1").update(f).digest("hex")}function xZ(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function mZ(f){return xZ(f)&&f.code==="ENOENT"}function IZ(f){return xZ(f)&&(f.code==="EACCES"||f.code==="EPERM")}class C${definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor(f,$){if(f.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=f,this.debounceMs=$?.debounceMs??75,this.emitParseErrors=$?.emitParseErrors??!1;for(let J of f){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let W of J.directories){let H=this.baseTypesByDirectory.get(W);if(H)H.add(J.type);else this.baseTypesByDirectory.set(W,new Set([J.type]))}}}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let f of this.watchersByDirectory.values())f.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let f of this.definitions)await this.refreshTypeInternal(f)})}async refreshType(f){let $=this.definitionsByType.get(f);if(!$)throw Error(`Unknown unified config type '${f}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal($)})}getSnapshot(f){let $=this.recordsByType.get(f);return new Map([...$?.entries()??[]].map(([J,W])=>[J,{...W}]))}getAllSnapshots(){let f=new Map;for(let[$,J]of this.recordsByType.entries())f.set($,new Map([...J.entries()].map(([W,H])=>[W,{...H}])));return f}emit(f){for(let $ of this.listeners)$(f)}enqueueRefresh(f){return this.refreshQueue=this.refreshQueue.then(f,f),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let f=this.buildDesiredTypesByDirectory();for(let[$,J]of this.watchersByDirectory.entries()){if(f.has($))continue;J.close(),this.watchersByDirectory.delete($)}this.watchedTypesByDirectory=f;for(let $ of f.keys()){if(this.watchersByDirectory.has($))continue;try{let J=xy($,()=>{let W=this.watchedTypesByDirectory.get($);if(!W)return;for(let H of W)this.pendingTypes.add(H);this.scheduleFlush()});this.watchersByDirectory.set($,J),J.on("error",(W)=>{let H=this.watchedTypesByDirectory.get($);if(!H)return;for(let Q of H)this.emit({kind:"error",type:Q,error:W,filePath:$})})}catch(J){if(!mZ(J)&&!IZ(J)){let W=f.get($);if(!W)continue;for(let H of W)this.emit({kind:"error",type:H,error:J,filePath:$})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let f=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let $ of f){let J=this.definitionsByType.get($);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal(f){let{records:$,discoveredDirectories:J}=await this.loadDefinition(f),W=this.recordsByType.get(f.type)??new Map;for(let[H,Q]of W.entries()){if($.has(H))continue;this.emit({kind:"remove",type:f.type,id:H,filePath:Q.filePath})}for(let[H,Q]of $.entries()){let Z=W.get(H);if(Z&&Z.filePath===Q.filePath&&Z.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:H,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set(f.type,$),this.discoveredDirectoriesByType.set(f.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition(f){let $=new Map,J=new Set;for(let W of f.directories){J.add(W);let H=f.discoverFiles?await f.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let Q of H){let{fileName:Z,filePath:j}=Q;if(J.add(Q.directoryPath),f.includeFile&&!f.includeFile(Z,j))continue;try{let P=await vy(j,"utf8"),X={type:f.type,directoryPath:Q.directoryPath,fileName:Z,filePath:j,content:P},V=f.parseFile(X),Y=f.resolveId(V,X).trim();if(!Y)continue;$.set(Y,{type:f.type,id:Y,item:V,filePath:j,fingerprint:cy(P)})}catch(P){if(this.emitParseErrors)this.emit({kind:"error",type:f.type,error:P,filePath:j})}}}return{records:$,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let f=new Map;for(let[$,J]of this.baseTypesByDirectory.entries())f.set($,new Set(J));for(let[$,J]of this.discoveredDirectoriesByType.entries())for(let W of J){let H=f.get(W);if(H)H.add($);else f.set(W,new Set([$]))}return f}async readDirectoryFileCandidates(f){try{return(await gy(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:uy(f,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch($){if(mZ($)||IZ($))return[];throw $}}}import{readdir as c5,readFile as dy,stat as gZ}from"node:fs/promises";import{basename as E$,dirname as ry,extname as d5,join as Tf}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as ZJ,resolveRulesConfigSearchPaths as ly,resolveSkillsConfigSearchPaths as py,resolveWorkflowsConfigSearchPaths as iy,SKILLS_CONFIG_DIRECTORY_NAME as z8,WORKFLOWS_CONFIG_DIRECTORY_NAME as O8}from"@cline/shared/storage";import ny from"yaml";var JJ="SKILL.md",ay="managed.json",ty=new Set([".md",".markdown",".txt"]);function r5(f){return f.trim().toLowerCase()}function L8(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"}function WJ(f){return ty.has(d5(f).toLowerCase())}async function l5(f){try{let $=await c5(f,{withFileTypes:!0}),J=[];for(let W of $){if(!W.isDirectory())continue;let H=Tf(f,W.name),Q=Tf(H,ay);try{let Z=await dy(Q,"utf8"),j=JSON.parse(Z);if(j&&typeof j==="object")J.push(H)}catch(Z){if(L8(Z))continue;if(Z?.name==="SyntaxError")continue;throw Z}}return J.sort((W,H)=>W.localeCompare(H))}catch($){if(L8($))return[];throw $}}function p5(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,W,H]=J;try{let Q=ny.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:H,hadFrontmatter:!0}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);return{data:{},body:f,hadFrontmatter:!0,parseError:Z}}}function HJ(f,$,J){if(f===void 0||f===null){if(J)throw Error(`Missing required frontmatter field '${$}'.`);return}if(typeof f!=="string")throw Error(`Frontmatter field '${$}' must be a string.`);let W=f.trim();if(!W&&J)throw Error(`Frontmatter field '${$}' cannot be empty.`);return W||void 0}function I1(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function N8(f,$){let{data:J,body:W,parseError:H}=p5(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in skill file.");let j=HJ(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:HJ(J.description,"description",!1),disabled:I1(J.disabled,"disabled")??(I1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function q8(f,$){let{data:J,body:W,parseError:H}=p5(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in rule file.");let Z=HJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing rule name.");return{name:Z,disabled:I1(J.disabled,"disabled")??(I1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function b8(f,$){let{data:J,body:W,parseError:H}=p5(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let Z=HJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing workflow name.");return{name:Z,disabled:I1(J.disabled,"disabled")??(I1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function w8(f){return py(f)}function C8(f){return ly(f)}function E8(f){return iy(f)}async function vZ(f){if(E$(f)===".cline"){let $=await l5(f);return(await Promise.all($.map((W)=>vZ(Tf(W,z8))))).flat()}try{let $=await c5(f,{withFileTypes:!0}),J=[];for(let W of $){if(W.isFile()&&W.name===JJ){J.push({directoryPath:f,fileName:W.name,filePath:Tf(f,W.name)});continue}if(W.isDirectory())J.push({directoryPath:Tf(f,W.name),fileName:JJ,filePath:Tf(f,W.name,JJ)})}return J}catch($){if(L8($))return[];throw $}}async function QJ(f){if(E$(f)===".cline"){let $=await l5(f);return(await Promise.all($.map((W)=>QJ(Tf(W,"rules.md"))))).flat()}try{if((await gZ(f)).isFile())return[{directoryPath:ry(f),fileName:E$(f),filePath:f}]}catch($){if(!L8($))throw $}try{let J=(await c5(f,{withFileTypes:!0})).filter((H)=>H.isFile()&&WJ(H.name)).map((H)=>({directoryPath:f,fileName:H.name,filePath:Tf(f,H.name)})),W=Tf(f,"AGENTS.md");try{if((await gZ(W)).isFile()){if(!J.some((Z)=>Z.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch($){if(L8($))return[];throw $}}async function sy(f){if(E$(f)===".cline"){let $=await l5(f);return(await Promise.all($.map((W)=>QJ(Tf(W,O8))))).flat()}return QJ(f)}function S8(f){let $=f?.directories??w8(f?.workspacePath),J=f?.workspacePath?Tf(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...$,J]:$,discoverFiles:vZ,includeFile:(W)=>W===JJ,parseFile:(W)=>N8(W.content,E$(W.directoryPath)),resolveId:(W)=>r5(W.name)}}function k8(f){let $=f?.directories??C8(f?.workspacePath),J=f?.workspacePath?Tf(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:QJ,includeFile:(W,H)=>W===".clinerules"||WJ(W)||WJ(H),parseFile:(W)=>q8(W.content,E$(W.filePath,d5(W.filePath))),resolveId:(W)=>r5(W.name)}}function m8(f){let $=f?.directories??E8(f?.workspacePath),J=f?.workspacePath?Tf(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:sy,includeFile:(W)=>WJ(W),parseFile:(W)=>b8(W.content,E$(W.filePath,d5(W.filePath))),resolveId:(W)=>r5(W.name)}}function uZ(f){let $=[S8(f?.skills),k8(f?.rules),m8(f?.workflows)];return new C$($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as cZ}from"@cline/shared";function oy(f,$){if(f.description?.trim())return cZ(f.description,".");if($==="workflow")return;return cZ(f.instructions,".")}function ey(f){return f.disabled!==!0}function dZ(f,$){return[...f.getSnapshot($).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>ey(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:oy(W.item,$),kind:$})).sort((J,W)=>J.name.localeCompare(W.name))}function I8(f){let $=new Map;for(let J of[...dZ(f,"workflow"),...dZ(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,W)=>J.name.localeCompare(W.name))}function rZ(f,$){if(!f.startsWith("/")||f.length<2)return f;let J=f.match(/^\/(\S+)/);if(!J)return f;let W=J[1];if(!W)return f;let H=W.length+1,Q=f.slice(H),Z=I8($).find((j)=>j.name===W);return Z?`${Z.instructions}${Q}`:f}var pZ={};N(pZ,{mergeRulesForSystemPrompt:()=>g1,loadRulesForSystemPromptFromWatcher:()=>i5,listEnabledRulesFromWatcher:()=>lZ,isRuleEnabled:()=>jJ,formatRulesForSystemPrompt:()=>x1});function jJ(f){return f.disabled!==!0}function x1(f){if(f.length===0)return"";return`
183
+
184
+ # Rules
185
+ ${f.map((J)=>`## ${J.name}
186
+ ${J.instructions}`).join(`
187
+
188
+ `)}`}function g1(f,$){let J=f?.trim(),W=$?.trim();if(J&&W)return`${J}
189
+
190
+ ${W}`;return J||W||void 0}function lZ(f){return[...f.getSnapshot("rule").values()].map((J)=>J.item).filter(jJ).sort((J,W)=>J.name.localeCompare(W.name))}function i5(f){return x1(lZ(f))}function PJ(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function fK(f){if(!f||f.length===0)return;let $=f.map(PJ).filter((J)=>J.length>0);return $.length>0?new Set($):void 0}function $K(f,$,J){if(!J)return!0;let W=PJ(f),H=PJ($),Q=W.includes(":")?W.split(":").at(-1)??W:W,Z=H.includes(":")?H.split(":").at(-1)??H:H;return J.has(W)||J.has(H)||J.has(Q)||J.has(Z)}function x8(f,$){let J=fK($);return[...f.getSnapshot("skill").entries()].map(([H,Q])=>{let Z=Q.item;return{id:H,name:Z.name.trim(),description:Z.description?.trim(),disabled:Z.disabled===!0,skill:Z}}).filter((H)=>$K(H.id,H.name,J))}function JK(f,$){return x8(f,$).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function WK(f,$,J){let W=PJ($);if(!W)return{error:"Missing skill name."};let H=x8(f,J),Q=H.find((V)=>V.id===W);if(Q){let{skill:V}=Q;if(V.disabled===!0)return{error:`Skill "${V.name}" is configured but disabled.`};return{id:Q.id,skill:V}}let Z=W.includes(":")?W.split(":").at(-1)??W:W,j=H.filter(({id:V})=>{if(V===Z)return!0;return V.endsWith(`:${Z}`)}),P=j.filter(({skill:V})=>V.disabled!==!0);if(P.length===1){let{id:V,skill:Y}=P[0];return{id:V,skill:Y}}if(P.length>1)return{error:`Skill "${$}" is ambiguous. Use one of: ${P.map(({id:V})=>V).join(", ")}`};if(j.length===1){let{skill:V}=j[0];return{error:`Skill "${V.name}" is configured but disabled.`}}if(j.length>1)return{error:`Skill "${$}" is ambiguous, and all matches are disabled: ${j.map(({id:V})=>V).join(", ")}`};let X=JK(f,J);return{error:X.length>0?`Skill "${$}" not found. Available skills: ${X.join(", ")}`:"No skills are currently available."}}function HK(f,$=Promise.resolve(),J){let W=new Set,H=async(Q,Z)=>{await $;let j=WK(f,Q,J);if("error"in j)return j.error;let{id:P,skill:X}=j;if(W.has(P))return`Skill "${X.name}" is already running.`;W.add(P);try{let V=Z?.trim(),Y=V?`
191
+ <command-args>${V}</command-args>`:"",B=X.description?.trim()?`Description: ${X.description.trim()}
192
+
193
+ `:"";return`<command-name>${X.name}</command-name>${Y}
194
+ <command-instructions>
195
+ ${B}${X.instructions}
196
+ </command-instructions>`}finally{W.delete(P)}};return Object.defineProperty(H,"configuredSkills",{get:()=>x8(f,J).map(({skill:Q,...Z})=>Z),enumerable:!0,configurable:!1}),H}function iZ(f){let $=f.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((W)=>Boolean(W))},async setup(W){if(await $,f.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>i5(f.watcher)});if(f.registerSkillsTool)W.registerTool(B$(HK(f.watcher,$,f.allowedSkillNames)));for(let H of I8(f.watcher).filter((Q)=>Q.kind==="skill"&&f.includeSkills||Q.kind==="workflow"&&f.includeWorkflows))W.registerCommand({name:H.name,description:H.description,handler:(Q)=>{let Z=Q.trim();return Z?`${H.instructions}
197
+
198
+ ${Z}`:H.instructions}})}}}class nZ{watcher;ready;stopped=!1;constructor(f){this.watcher=uZ(f)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType(f){await this.start(),await this.watcher.refreshType(f)}listRecords(f){return[...this.watcher.getSnapshot(f).entries()].map(([$,J])=>({type:f,id:$,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return I8(this.watcher)}resolveRuntimeSlashCommand(f){return rZ(f,this.watcher)}hasConfiguredSkills(f){return x8(this.watcher,f).length>0}createExtension(f){return iZ({...f,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function o0(f){return new nZ(f)}import{readFile as QK,writeFile as ZK}from"node:fs/promises";import sZ from"yaml";function jK(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,W,H]=J,Q=sZ.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:H,hadFrontmatter:!0}}function tZ(f,$){return`---
199
+ ${sZ.stringify(f).trimEnd()}
200
+ ---
201
+ ${$}`}function PK(f,$){let{data:J,body:W,hadFrontmatter:H}=jK(f);if(!H&&$)return f;if($){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return W;return tZ(J,W)}return J.disabled=!0,tZ(J,W)}async function oZ({filePath:f,enabled:$}){let J=await QK(f,"utf8"),W=PK(J,$);return await ZK(f,W),{filePath:f,enabled:$,disabled:!$}}G0();var eZ={};N(eZ,{listPluginTools:()=>g8});G0();function XK(f,$){if(!f.setup)return[];let J=[],W={registerTool:(H)=>J.push(H),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return f.setup(W,{workspaceInfo:$}),J}async function g8(f){let $=O$({workspacePath:f.workspacePath,cwd:f.cwd}),J=rf(f.disabledToolNames),W=[];for(let H of $){let Q=await T0([H],{cwd:f.cwd,providerId:f.providerId,modelId:f.modelId});for(let Z of Q.plugins)for(let j of XK(Z,{rootPath:f.workspacePath}))W.push({name:j.name,pluginName:Z.name,path:H,source:H.startsWith(f.workspacePath)?"workspace-plugin":"global-plugin",enabled:!J.has(j.name),description:j.description?.trim()||void 0})}return W.sort((H,Q)=>{let Z=H.name.localeCompare(Q.name);if(Z!==0)return Z;return H.path.localeCompare(Q.path)})}function a5(f,$){if(!$)return"global";let J=YK($,f);return!J.startsWith("..")&&!VK(J)?"workspace":"global"}function XJ(f){return[...f].sort(($,J)=>{let W=(H)=>{switch(H){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if($.source!==J.source)return W($.source)-W(J.source);return $.name.localeCompare(J.name)})}function Jj(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function $j(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=Jj(f);if(!J)return await $(void 0);let W=o0({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await W.start(),await $(W)}finally{W.stop()}}function BK(f,$){if(!f)return;let J=f.listRecords("skill");if($.id){let W=J.find((H)=>H.id===$.id);if(W)return W}for(let W of J)if(W.filePath===$.path||W.item.name===$.name||W.id===$.name)return W;return}class e0{async list(f={}){return await $j(f,async($)=>{let J=Jj(f),W=[],H=[],Q=[],Z=[];if($){for(let j of $.listRecords("workflow")){let P=j.item;W.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"workflow",source:a5(j.filePath,J),description:P.instructions,toggleable:!1})}for(let j of $.listRecords("rule")){let P=j.item;H.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"rule",source:a5(j.filePath,J),description:P.instructions,toggleable:!1})}for(let j of $.listRecords("skill")){let P=j.item;Q.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"skill",source:a5(j.filePath,J),description:P.description,toggleable:!0})}}if(J)try{for(let j of await g8({workspacePath:J,cwd:f.cwd,providerId:f.availabilityContext?.providerId,modelId:f.availabilityContext?.modelId}))Z.push({id:`${j.pluginName}:${j.name}:${j.path}`,name:j.name,path:j.path,enabled:j.enabled,kind:"tool",source:j.source,description:j.description,toggleable:!0})}catch{}return{workflows:XJ(W.filter((j)=>n5(j.path))),rules:XJ(H.filter((j)=>n5(j.path))),skills:XJ(Q.filter((j)=>n5(j.path))),tools:XJ(Z)}})}async toggle(f){if(f.type==="skills")return await $j(f,async($)=>{let J=BK($,f),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${f.id??f.name??fj(f.path??"")}'.`);let H=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=f.enabled??(H!==void 0?!H:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${f.id??f.name??fj(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await oZ({filePath:W,enabled:Q}),await $?.refreshType("skill"),{snapshot:await this.list({...f,userInstructionService:$}),changedTypes:["skills"]}});if(f.type==="tools"){if(!f.name?.trim())throw Error("Tool settings toggle requires a tool name.");if(f.enabled===void 0)j6(f.name);else AQ(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function S$(){return new e0}function Hj(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await S$().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await S$().toggle($)}}}function Qj(f){function $(){let J=f.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return $().list(J)},update(J){return $().update(J)},delete(J){return $().delete(J)}}}var Zj={};N(Zj,{splitCoreSessionConfig:()=>v8});function v8(f){let{hooks:$,logger:J,telemetry:W,extensionContext:H,extraTools:Q,extensions:Z,onTeamEvent:j,onConsecutiveMistakeLimitReached:P,checkpoint:X,compaction:V,...Y}=f,B={};if($)B.hooks=$;if(J)B.logger=J;if(W)B.telemetry=W;if(H)B.extensionContext=H;if(Q)B.extraTools=Q;if(Z)B.extensions=Z;if(j)B.onTeamEvent=j;if(P)B.onConsecutiveMistakeLimitReached=P;if(X?.createCheckpoint)B.checkpoint=X;if(V?.compact)B.compaction=V;let A=Object.keys(B).length>0?B:void 0;return{config:{...Y,...X?{checkpoint:{enabled:X.enabled}}:{},...V?{compaction:{enabled:V.enabled,strategy:V.strategy,thresholdRatio:V.thresholdRatio,reserveTokens:V.reserveTokens,preserveRecentTokens:V.preserveRecentTokens,contextWindowTokens:V.contextWindowTokens,summarizer:V.summarizer}}:{}},...A?{localRuntime:A}:{}}}function jj(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...AK(f.localRuntime)},localRuntime:f.localRuntime}:f}function t5(f,$={}){let J=v8(f.config),W=Vf($.defaultCapabilities,f.capabilities),H=RK(J.localRuntime,f.localRuntime),Q=$.withExtensionContext?.(H?.extensionContext);if(Q)H={...H??{},extensionContext:Q};return{...f,...J,...H?{localRuntime:H}:{},...W?{capabilities:W}:{}}}function AK(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:W,onTeamRestored:H,...Q}=f;return Q}function RK(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}Gf();function Pj(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:g.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??Pf.CORE,providerId:f.input.config.providerId,modelId:f.input.config.modelId,enableTools:f.input.config.enableTools,enableSpawnAgent:f.input.config.enableSpawnAgent,enableAgentTeams:f.input.config.enableAgentTeams,clientName:f.clientName,runtimeAddress:f.runtimeAddress}})}function u8(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function s5(f){let $=f?.trim();return $?$:void 0}function FK(f,$){let J=f?.trim();if(!J)return $;let W=Date.parse(J);if(!Number.isFinite(W))return $;return new Date(W).toISOString()}function Xj(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function Vj(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function yK(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function KK(f,$){let J=f.eventId.trim(),W=f.eventType.trim(),H=f.source.trim(),Q=s5(f.subject),Z=s5(f.dedupeKey)??`${W}:${H}:${Q??J}`;return{eventId:J,eventType:W,source:H,subject:Q,occurredAt:FK(f.occurredAt,$),workspaceRoot:s5(f.workspaceRoot),payload:u8(f.payload)?f.payload:void 0,attributes:u8(f.attributes)?f.attributes:void 0,dedupeKey:Z}}function o5(f,$){if(!$)return;let J=$.split("."),W=f;for(let H of J){if(!u8(W))return;W=W[H]}return W}function UK(f,$){if(f.attributes&&Object.hasOwn(f.attributes,$))return f.attributes[$];if(f.payload&&Object.hasOwn(f.payload,$))return f.payload[$];let J={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload},W=o5(J,$);if(W!==void 0)return W;if(f.attributes){let H=o5(f.attributes,$);if(H!==void 0)return H}if(f.payload)return o5(f.payload,$);return}function VJ(f,$){if(Array.isArray($))return $.some((J)=>VJ(f,J));if(Array.isArray(f))return f.some((J)=>VJ(J,$));if(u8($)){if(!u8(f))return!1;return Object.entries($).every(([J,W])=>VJ(f[J],W))}return Object.is(f,$)}function GK(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,W])=>VJ(UK(f,J),W))}class e5{store;nowFn;logger;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now()),this.logger=f.logger}ingestEvent(f){let $=new Date(this.nowFn()).toISOString(),J=KK(f,$),W=this.store.insertEventLog(J,{receivedAtIso:$});if(!W.created)return this.logger?.debug("cron.event.duplicate",{eventId:W.record.eventId,eventType:W.record.eventType,source:W.record.source}),{event:W.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:W.record.dedupeKey}]};try{let H=this.store.listEventSpecsForType(J.eventType),Q=[],Z=[],j=[];for(let V of H){if(!GK(J,V.filters)){Q.push({specId:V.specId,externalId:V.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}Z.push(V);let Y=this.materializeForSpec(V,J,W.record.receivedAt);if(Y.run)j.push(Y.run);else Q.push({specId:V.specId,externalId:V.externalId,reason:Y.reason,dedupeKey:J.dedupeKey})}let P=Z.length===0?"unmatched":j.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:P,matchedSpecCount:Z.length,queuedRunCount:j.length,suppressedCount:Q.filter((V)=>V.reason!=="filter_mismatch").length});let X=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:P,matchedSpecCount:Z.length,queuedRunCount:j.length}),{event:X??W.record,duplicate:!1,matchedSpecs:Z,queuedRuns:j,suppressions:Q}}catch(H){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:H instanceof Error?H.message:String(H)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:H});throw H}}materializeForSpec(f,$,J){let W=$.dedupeKey??$.eventId,H=f.debounceSeconds??0;if(H>0){let P=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:W});if(P){let X=yK(P.scheduledFor,Xj(J,H)),V=this.store.updateQueuedEventRunForDebounce({runId:P.runId,triggerEventId:$.eventId,scheduledFor:X});if(V)return{run:V,reason:"dedupe_window"}}}let Q=f.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:f.specId,dedupeKey:W,sinceIso:Vj(J,Q)}))return{reason:"dedupe_window"};let Z=f.cooldownSeconds??0;if(Z>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:Vj(J,Z)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:H>0?Xj(J,H):J}),reason:"dedupe_window"}}}class c8{store;nowFn;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now())}materializeAll(){let f={oneOffQueued:0,scheduleQueued:0},$=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of $)if(this.materializeOneOff(W))f.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of J)try{if(this.materializeSchedule(W))f.scheduleQueued+=1}catch{}return f}materializeOneOff(f){if(f.triggerKind!=="one_off")return!1;if(!f.enabled||f.removed)return!1;if(this.store.hasOneOffRunForRevision(f.specId,f.revision))return!1;return this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(f){if(f.triggerKind!=="schedule")return!1;if(!f.enabled||f.removed)return!1;if(!f.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:f.specId,nowMs:this.nowFn()}).queued}}import{basename as zK}from"node:path";import{buildClineSystemPrompt as OK}from"@cline/shared";import{nowIso as Yj}from"@cline/shared/db";import{mkdirSync as TK,writeFileSync as hK}from"node:fs";import{join as DK}from"node:path";import{resolveCronReportsDir as MK}from"@cline/shared/storage";function f$(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function k$(f,$){if($===void 0||$===null)return;return`${f}: ${f$($)}`}function _K(f,$,J){let W=[`runId: ${f$(f.runId)}`,`specId: ${f$($.specId)}`,`externalId: ${f$($.externalId)}`,`title: ${f$($.title)}`,`triggerKind: ${f$(f.triggerKind)}`,`status: ${f$(f.status)}`,`sourcePath: ${f$($.sourcePath)}`],H=[k$("sessionId",f.sessionId),k$("startedAt",f.startedAt),k$("completedAt",f.completedAt),k$("triggerEventId",f.triggerEventId),k$("triggerEventType",J?.eventType),k$("triggerEventSource",J?.source),k$("triggerEventSubject",J?.subject)];for(let Q of H)if(Q)W.push(Q);return`---
202
+ ${W.join(`
203
+ `)}
204
+ ---
205
+ `}function LK(f){let $=[];if(f.triggerEvent){let J=f.triggerEvent,W=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((H)=>H.length>0);$.push(`## Trigger Event
206
+
207
+ ${W.join(`
208
+ `)}
209
+ `)}if(f.error)$.push(`## Error
210
+
211
+ ${f.error}
212
+ `);if(f.finalText&&f.finalText.trim().length>0)$.push(`## Summary
213
+
214
+ ${f.finalText.trim()}
215
+ `);if(f.usage){let J=f.usage,W=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",f.durationMs!==void 0?`- durationMs: ${f.durationMs}`:""].filter((H)=>H.length>0);if(W.length>0)$.push(`## Usage
216
+
217
+ ${W.join(`
218
+ `)}
219
+ `)}if(f.toolCalls&&f.toolCalls.length>0){let J=f.toolCalls.map((W)=>{let H=[`- ${W.name}`];if(W.durationMs!==void 0)H.push(`(${W.durationMs}ms)`);if(W.error)H.push(`error: ${W.error}`);return H.join(" ")});$.push(`## Tool Calls
220
+
221
+ ${J.join(`
222
+ `)}
223
+ `)}return $.join(`
224
+ `)}function fH(f){let $=MK(f.specs);TK($,{recursive:!0});let J=DK($,`${f.run.runId}.md`),W=`${_K(f.run,f.spec,f.data.triggerEvent)}
225
+ ${LK(f.data)}`;return hK(J,W,"utf8"),J}class $H{globalMaxConcurrency;activeExecutions=new Map;constructor(f){this.globalMaxConcurrency=Math.max(1,Math.floor(f))}acquire(f,$,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(J)),H=this.activeExecutions.get(f)??new Set;if(H.size>=W)return!1;return H.add($),this.activeExecutions.set(f,H),!0}release(f,$){let J=this.activeExecutions.get(f);if(!J)return;if(J.delete($),J.size===0)this.activeExecutions.delete(f)}getGlobalActiveCount(){let f=0;for(let $ of this.activeExecutions.values())f+=$.size;return f}}var NK=15000,qK=90,Bj=["rules","skills","plugins"];function bK(f,$){return new Set(f.extensions??Bj).has($)}function wK(f,$){if(f.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let W of f.tools)J[W]={enabled:!0,autoApprove:!0};if($==="yolo")J[ff.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function CK(f){let $=f?.trim();if(!$)return;return["# Notes Directory",`Use ${$} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
226
+ `)}class JH extends Error{constructor(f){super(f);this.name="TimeoutError"}}async function EK(f,$){if($<=0)return f;let J,W=new Promise((H,Q)=>{J=setTimeout(()=>{Q(new JH("cron run timed out"))},$)});try{return await Promise.race([f,W])}finally{if(J)clearTimeout(J)}}class d8{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor(f){this.store=f.store,this.materializer=f.materializer,this.options=f,this.limiter=new $H(f.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,(f.claimLeaseSeconds??qK)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let f=Math.max(2000,this.options.pollIntervalMs??NK);await this.tick(),this.timer=setInterval(()=>void this.tick(),f)}async stop(){let f=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!f)return;let $=[...this.activeRuns.entries()];await Promise.all($.map(async([J,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:W.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let f=this.store.claimDueRuns({nowIso:Yj(),leaseMs:this.claimLeaseMs});await Promise.allSettled(f.map(($)=>this.executeClaim($)))}catch(f){let $=this.options.logger;if($)if($.error)$.error("cron.runner.tick.failed",{error:f});else $.log("cron.runner.tick.failed",{error:f})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([f,$])=>{let J=this.store.getRun(f);return J?[{...J,...$}]:[]})}async executeClaim(f){let $=f.run,J=this.store.getSpec($.specId);if(!J){this.store.completeRun($.runId,{status:"failed",error:"spec not found",claimToken:f.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun($.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:f.claimToken});return}let W=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,$.runId,W)){this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,$.runId),this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set($.runId,{claimToken:f.claimToken});let Q=$.triggerEventId?this.store.getEventLog($.triggerEventId):void 0,Z,j,P=Date.now(),X;if(J.timeoutSeconds&&J.timeoutSeconds>0)X=P+J.timeoutSeconds*1000;try{j=this.startClaimLeaseHeartbeat(f);let V=await this.buildStartRequest(J);if(Z=(await this.options.runtimeHandlers.startSession(V)).sessionId.trim(),!Z)throw Error("runtime returned empty sessionId");this.activeRuns.set($.runId,{claimToken:f.claimToken,sessionId:Z}),this.store.attachSessionIdToRun($.runId,Z);let B={config:V,prompt:this.buildPrompt(J,Q)},A=this.options.runtimeHandlers.sendSession(Z,B),R=X?Math.max(1,X-Date.now()):0,y=(await EK(A,R)).result,F=Date.now(),K=fH({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:Z,status:"done"},spec:J,data:{finalText:y.text,usage:y.usage,toolCalls:y.toolCalls,durationMs:F-P,triggerEvent:Q}});this.store.completeRun($.runId,{status:"done",sessionId:Z,reportPath:K,claimToken:f.claimToken}),this.store.updateSpecLastRunAt(J.specId,Yj())}catch(V){let Y=V instanceof JH;if(Z&&Y)try{await this.options.runtimeHandlers.abortSession(Z)}catch{}let B=V instanceof Error?V.message:String(V),A=Date.now(),R=fH({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:Z,status:"failed"},spec:J,data:{error:B,durationMs:A-P,triggerEvent:Q}});this.store.completeRun($.runId,{status:"failed",sessionId:Z,reportPath:R,error:B,claimToken:f.claimToken})}finally{if(j?.(),Z)try{await this.options.runtimeHandlers.stopSession(Z)}catch{}this.activeRuns.delete($.runId),this.limiter.release(J.specId,$.runId)}}buildPrompt(f,$){let J=f.prompt??"";if(!$)return J;let W={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload};return`${J}
227
+
228
+ Trigger event:
229
+ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim(f.run.runId,f.claimToken,W))clearInterval(J)},$);return()=>clearInterval(J)}async buildSystemPrompt(f,$,J,W){let H=CK(f.notesDirectory),Q=g1(void 0,H),Z=await y8($),j=OK({ide:"Cline Cron",workspaceRoot:$,workspaceName:zK($),metadata:Z,rules:f.systemPrompt?void 0:Q,mode:J,providerId:W,overridePrompt:f.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return f.systemPrompt?g1(j,Q)??j:j}async buildStartRequest(f){let $=(f.workspaceRoot??"").trim(),J=(f.providerId??"").trim(),W=(f.modelId??"").trim(),H=f.metadata?.__hubRuntimeOptions&&typeof f.metadata.__hubRuntimeOptions==="object"&&!Array.isArray(f.metadata.__hubRuntimeOptions)?f.metadata.__hubRuntimeOptions:void 0,Q=typeof f.metadata?.__hubScheduleCwd==="string"&&f.metadata.__hubScheduleCwd.trim()?f.metadata.__hubScheduleCwd.trim():$;if(!$)throw Error("cron spec requires workspaceRoot");let Z=f.mode==="plan"?"plan":f.mode==="act"?"act":"yolo";return{workspaceRoot:$,cwd:Q,provider:J,model:W,mode:Z,source:f.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt(f,$,Z,J),maxIterations:f.maxIterations,enableTools:H?.enableTools??!0,enableSpawn:H?.enableSpawn??!0,enableTeams:H?.enableTeams??!0,autoApproveTools:H?.autoApproveTools??!0,toolPolicies:wK(f,Z),configExtensions:Bj.filter((j)=>bK(f,j))}}}import{existsSync as JU,readdirSync as WU,readFileSync as HU,statSync as QU}from"node:fs";import{relative as ZU}from"node:path";import{resolveCronSpecsDir as jU}from"@cline/shared/storage";function r8(f,$,J,W){let H=new Set;function Q(Z){let j=Z.toLowerCase();if(W){let X=W.indexOf(j);if(X!==-1)return X+$}let P=Number(Z);if(!Number.isInteger(P)||P<$||P>J)throw Error(`Invalid cron value "${Z}" for range [${$}-${J}]`);return P}for(let Z of f.split(",")){if(Z==="*"){for(let X=$;X<=J;X+=1)H.add(X);continue}let j=Z.indexOf("/");if(j!==-1){let X=Z.slice(0,j),V=Number(Z.slice(j+1));if(!Number.isInteger(V)||V<1)throw Error(`Invalid step "${Z.slice(j+1)}"`);let Y=$,B=J;if(X!=="*"){let A=X.indexOf("-");if(A!==-1)Y=Q(X.slice(0,A)),B=Q(X.slice(A+1));else Y=Q(X)}if(Y>B)throw Error(`Invalid cron range "${X}"`);for(let A=Y;A<=B;A+=V)H.add(A);continue}let P=Z.indexOf("-");if(P!==-1){let X=Q(Z.slice(0,P)),V=Q(Z.slice(P+1));if(X>V)throw Error(`Invalid cron range "${Z}"`);for(let Y=X;Y<=V;Y+=1)H.add(Y);continue}H.add(Q(Z))}return[...H].sort((Z,j)=>Z-j)}var SK=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Rj=["sun","mon","tue","wed","thu","fri","sat"];function l8(f,$,J){let W=f[$];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${$+1}`);return W}function WH(f,$){let J=f[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${$}`);return J}function HH(f){let $=f.trim().split(/\s+/);if($.length!==5)throw Error(`Invalid cron pattern "${f}": expected 5 fields, got ${$.length}`);return{minutes:r8(l8($,0,f),0,59),hours:r8(l8($,1,f),0,23),daysOfMonth:r8(l8($,2,f),1,31),months:r8(l8($,3,f),1,12,SK),daysOfWeek:r8(l8($,4,f),0,6,Rj)}}function QH(f){HH(f)}function Fj(f,$,J=Date.now()){m$(f,J,$)}var Aj=new Map,kK=new Map(Rj.map((f,$)=>[f,$]));function yj(f){let $=f?.trim();return $?$:void 0}function Kj(f){let $=Aj.get(f);if($)return $;let J=new Intl.DateTimeFormat("en-US",{timeZone:f,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return Aj.set(f,J),J}function mK(f){let $=yj(f);if(!$)return;Kj($).format(new Date)}function IK(f,$){let J=Kj($).formatToParts(new Date(f)),W=new Map(J.map((Z)=>[Z.type,Z.value])),H=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=kK.get(H);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${$}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:Q,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function xK(f){let $=new Date(f);return{month:$.getMonth()+1,dayOfMonth:$.getDate(),dayOfWeek:$.getDay(),hour:$.getHours(),minute:$.getMinutes()}}function gK(f,$){return f.months.includes($.month)&&f.daysOfMonth.includes($.dayOfMonth)&&f.daysOfWeek.includes($.dayOfWeek)&&f.hours.includes($.hour)&&f.minutes.includes($.minute)}function vK(f,$,J){let W=HH(f),H=new Date($);H.setSeconds(0,0);let Q=H.getTime()+60000,Z=new Date($);Z.setFullYear(Z.getFullYear()+4);let j=Z.getTime();while(Q<=j){if(gK(W,IK(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${f}" in timezone "${J}"`)}function m$(f,$,J){let W=yj(J);if(W)return mK(W),vK(f,$,W);let H=HH(f),Q=new Date($);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let Z=new Date($);Z.setFullYear(Z.getFullYear()+4);while(Q<=Z){let{month:j,dayOfMonth:P,dayOfWeek:X,hour:V,minute:Y}=xK(Q.getTime());if(!H.months.includes(j)){let B=H.months.find((R)=>R>j)??WH(H.months,"months"),A=B<=j?1:0;Q=new Date(Q.getFullYear()+A,B-1,1,0,0,0,0);continue}if(!H.daysOfMonth.includes(P)||!H.daysOfWeek.includes(X)){Q=new Date(Q.getFullYear(),Q.getMonth(),P+1,0,0,0,0);continue}if(!H.hours.includes(V)){let B=H.hours.find((R)=>R>V)??WH(H.hours,"hours"),A=B<=V?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+A,B,0,0,0);continue}if(!H.minutes.includes(Y)){let B=H.minutes.find((R)=>R>Y)??WH(H.minutes,"minutes"),A=B<=Y?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+A,B,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${f}"`)}import{createHash as uK}from"node:crypto";import cK from"yaml";function dK(f){let $=f.replace(/\\/g,"/");if($.startsWith("events/")&&$.endsWith(".event.md"))return"event";if($.endsWith(".cron.md"))return"schedule";return"one_off"}function rK(f){let $=f.replace(/\r\n/g,`
230
+ `);if(!$.startsWith(`---
231
+ `))return{frontmatter:void 0,body:f};let J=$.slice(4),W=J.indexOf(`
232
+ ---`);if(W===-1)return{frontmatter:void 0,body:f};let H=J.slice(0,W),Q=J.slice(W+4);if(Q.startsWith(`
233
+ `))Q=Q.slice(1);return{frontmatter:H,body:Q}}function wf(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function lK(f){if(!Array.isArray(f))return;let $=f.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return $.length>0?$:void 0}function PH(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return f}function pK(f){let $=PH(f);if(!$)return;let J=wf($.providerId),W=wf($.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function iK(f){if(typeof f!=="string")return;let $=f.trim().toLowerCase();if($==="act"||$==="plan"||$==="yolo")return $;return}function Gj(f,$={}){let J=Array.isArray(f)?f:typeof f==="string"?f.split(","):void 0;if(!J)return;let W=[...new Set(J.map((H)=>typeof H==="string"?H.trim():"").filter((H)=>H.length>0))];if(Array.isArray(f)&&$.preserveEmptyArray)return W;return W.length>0?W:void 0}var nK=new Set(q0);function aK(f){let $=Gj(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((W)=>!nK.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return $}var tK=new Set(["rules","skills","plugins"]);function sK(f){let $=Gj(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((W)=>!tK.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return $}function ZH(f){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return;return Math.floor(f)}function jH(f){if(typeof f!=="number"||!Number.isFinite(f)||f<0)return;return Math.floor(f)}function XH(f){if(f===null||typeof f!=="object")return JSON.stringify(f??null);if(Array.isArray(f))return`[${f.map((J)=>XH(J)).join(",")}]`;let $=Object.entries(f).filter(([,J])=>J!==void 0);return $.sort(([J],[W])=>J<W?-1:J>W?1:0),`{${$.map(([J,W])=>`${JSON.stringify(J)}:${XH(W)}`).join(",")}}`}function Tj(f,$){let J=uK("sha256");return J.update(XH(f)),J.update(`
234
+ `),J.update($),J.digest("hex")}function oK(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var eK=["schedule","timezone"],fU=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],$U=["cwd"];function Uj(f,$,J,W,H){return{externalId:f,relativePath:f,triggerKind:$,body:J,contentHash:Tj(W,J),error:H}}function ef(f,$,J,W,H,Q){return{externalId:f,relativePath:$,triggerKind:J,body:W,contentHash:H,error:Q}}function hj(f){let $=f.relativePath.replace(/\\/g,"/"),J=dK($),{frontmatter:W,body:H}=rK(f.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let K=cK.parse(W);if(K&&typeof K==="object"&&!Array.isArray(K))Q=K;else if(K!==null&&K!==void 0)return Uj($,J,H,{},"frontmatter must be a YAML mapping")}catch(K){return Uj($,J,H,{},K instanceof Error?`failed to parse frontmatter: ${K.message}`:"failed to parse frontmatter")}let Z=Tj(Q,H),j=wf(Q.id),P=j??$;if(J!=="schedule"){for(let K of eK)if(Q[K]!==void 0)return ef(P,$,J,H,Z,`field "${K}" is only allowed on *.cron.md specs`)}for(let K of $U)if(Q[K]!==void 0)return ef(P,$,J,H,Z,`field "${K}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let K of fU)if(Q[K]!==void 0)return ef(P,$,J,H,Z,`field "${K}" is only allowed on .event.md specs`)}let X=wf(Q.prompt),V=H.trim(),Y=X??(V.length>0?V:void 0);if(!Y)return ef(P,$,J,H,Z,"prompt is required (frontmatter `prompt` or markdown body)");let B=wf(Q.workspaceRoot);if(!B)return ef(P,$,J,H,Z,"workspaceRoot is required");let A,R;try{A=aK(Q.tools),R=sK(Q.extensions)}catch(K){return ef(P,$,J,H,Z,K instanceof Error?K.message:String(K))}let U=iK(Q.mode);if(Q.mode!==void 0&&U===void 0)return ef(P,$,J,H,Z,"mode must be one of: act, plan, yolo");let y={id:j,title:wf(Q.title)??j??oK($),prompt:Y,workspaceRoot:B,mode:U??"yolo",systemPrompt:wf(Q.systemPrompt),modelSelection:pK(Q.modelSelection),maxIterations:ZH(Q.maxIterations),timeoutSeconds:ZH(Q.timeoutSeconds),tools:A,notesDirectory:wf(Q.notesDirectory),extensions:R,source:wf(Q.source)??"user",tags:lK(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:PH(Q.metadata)},F;if(J==="schedule"){let K=wf(Q.schedule);if(!K)return ef(P,$,J,H,Z,"schedule is required for *.cron.md specs");let M=wf(Q.timezone);try{Fj(K,M)}catch(G){return ef(P,$,J,H,Z,G instanceof Error?G.message:String(G))}F={...y,triggerKind:"schedule",schedule:K,timezone:M}}else if(J==="event"){let K=wf(Q.event);if(!K)return ef(P,$,J,H,Z,"event is required for .event.md specs");F={...y,triggerKind:"event",event:K,filters:PH(Q.filters),debounceSeconds:jH(Q.debounceSeconds),dedupeWindowSeconds:jH(Q.dedupeWindowSeconds),cooldownSeconds:jH(Q.cooldownSeconds),maxParallel:ZH(Q.maxParallel)}}else F={...y,triggerKind:"one_off"};return{externalId:P,relativePath:$,triggerKind:J,body:H,contentHash:Z,spec:F}}function PU(f,$){return ZU(f,$).replace(/\\/g,"/")}function XU(f){if(!JU(f))return[];let $=[],J=[f];while(J.length>0){let W=J.pop();if(!W)continue;let H;try{H=WU(W,{withFileTypes:!0})}catch{continue}for(let Q of H){let Z=`${W}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(Z);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;$.push(Z)}}return $}class VH{store;cronDir;constructor(f){this.store=f.store,this.cronDir=jU(f.specs??(f.workspaceRoot?{scope:"workspace",workspaceRoot:f.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let f={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},$=XU(this.cronDir),J=new Set;for(let H of $){let Q=PU(this.cronDir,H);J.add(Q),f.scanned+=1;let Z=await this.reconcileFile(Q,H);if(Z){if(f.changes.push(Z),f.upserted+=1,Z.parse.error)f.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let H of W)if(!J.has(H.sourcePath))this.handleFileDeleted(H),f.removed+=1;return this.refreshScheduleNextRunAt(),f}async reconcileFile(f,$){let J=this.store.getSpecBySourcePath(f),W,H;try{W=HU($,"utf8"),H=QU($).mtimeMs}catch{return}let Z=hj({relativePath:f,raw:W}),j=this.store.upsertSpec({externalId:Z.externalId,sourcePath:f,triggerKind:Z.triggerKind,sourceMtimeMs:H,sourceHash:Z.contentHash,parseStatus:Z.error?"invalid":"valid",parseError:Z.error,spec:Z.spec});if(!Z.error&&Z.triggerKind==="schedule"&&j.record.enabled)this.applyScheduleNextRunAt(j.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==j.record.scheduleExpr||J.timezone!==j.record.timezone});return{relativePath:f,result:j,parse:Z}}handleFileDeleted(f){this.store.markSpecRemoved(f.specId),this.store.cancelQueuedRunsForSpec(f.specId)}refreshScheduleNextRunAt(){let f=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let $ of f)this.applyScheduleNextRunAt($,{forceReset:!1})}applyScheduleNextRunAt(f,$){if(!f.scheduleExpr)return;if(!$.forceReset&&f.nextRunAt)return;try{let J=Date.now(),W=f.lastRunAt?Math.max(J,new Date(f.lastRunAt).getTime()):J,H=m$(f.scheduleExpr,W,f.timezone),Q=new Date(H).toISOString();if(f.nextRunAt!==Q)this.store.updateSpecNextRunAt(f.specId,Q)}catch{}}}import{existsSync as VU,mkdirSync as YU,watch as BU}from"node:fs";import{relative as AU,resolve as RU}from"node:path";var FU=250;class YH{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor(f){this.reconciler=f.reconciler,this.debounceMs=Math.max(0,f.debounceMs??FU),this.onError=f.onError??(()=>{}),this.onReconciled=f.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let f=this.reconciler.getCronDir();try{YU(f,{recursive:!0}),this.watcher=BU(f,{recursive:!0},($,J)=>{if(!J)return;let W=String(J).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch($){this.onError($)}}stop(){for(let f of this.pending.values())clearTimeout(f);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile(f){let $=this.pending.get(f);if($)clearTimeout($);let J=setTimeout(()=>{this.pending.delete(f),this.reconcileNow(f)},this.debounceMs);this.pending.set(f,J)}async reconcileNow(f){try{let $=RU(this.reconciler.getCronDir(),f);if(!VU($)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=AU(this.reconciler.getCronDir(),$).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,$),await this.onReconciled()}catch($){this.onError($)}}}import{randomUUID as p8}from"node:crypto";import{asOptionalString as S,asString as n,loadSqliteDb as KU,nowIso as Yf}from"@cline/shared/db";import{resolveCronDbPath as UU}from"@cline/shared/storage";var yU=[`CREATE TABLE IF NOT EXISTS cron_specs (
235
+ spec_id TEXT PRIMARY KEY,
236
+ external_id TEXT NOT NULL,
237
+ source_path TEXT NOT NULL UNIQUE,
238
+ trigger_kind TEXT NOT NULL CHECK (trigger_kind IN ('one_off', 'schedule', 'event')),
239
+ source_mtime_ms INTEGER,
240
+ source_hash TEXT,
241
+ parse_status TEXT NOT NULL CHECK (parse_status IN ('valid', 'invalid')),
242
+ parse_error TEXT,
243
+ enabled INTEGER NOT NULL DEFAULT 1,
244
+ removed INTEGER NOT NULL DEFAULT 0,
245
+ title TEXT NOT NULL,
246
+ prompt TEXT,
247
+ workspace_root TEXT,
248
+ schedule_expr TEXT,
249
+ timezone TEXT,
250
+ event_type TEXT,
251
+ filters_json TEXT,
252
+ debounce_seconds INTEGER,
253
+ dedupe_window_seconds INTEGER,
254
+ cooldown_seconds INTEGER,
255
+ mode TEXT,
256
+ system_prompt TEXT,
257
+ provider_id TEXT,
258
+ model_id TEXT,
259
+ max_iterations INTEGER,
260
+ timeout_seconds INTEGER,
261
+ max_parallel INTEGER,
262
+ tools_json TEXT,
263
+ notes_directory TEXT,
264
+ extensions_json TEXT,
265
+ source TEXT,
266
+ tags_json TEXT,
267
+ metadata_json TEXT,
268
+ revision INTEGER NOT NULL DEFAULT 1,
269
+ last_materialized_run_id TEXT,
270
+ last_run_at TEXT,
271
+ next_run_at TEXT,
272
+ created_at TEXT NOT NULL,
273
+ updated_at TEXT NOT NULL
274
+ );`,`CREATE TABLE IF NOT EXISTS cron_runs (
275
+ run_id TEXT PRIMARY KEY,
276
+ spec_id TEXT NOT NULL REFERENCES cron_specs(spec_id) ON DELETE CASCADE,
277
+ spec_revision INTEGER NOT NULL,
278
+ trigger_kind TEXT NOT NULL CHECK (trigger_kind IN ('one_off', 'schedule', 'event', 'manual', 'retry')),
279
+ status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'done', 'failed', 'cancelled')),
280
+ claim_token TEXT,
281
+ claim_started_at TEXT,
282
+ claim_until_at TEXT,
283
+ scheduled_for TEXT,
284
+ trigger_event_id TEXT,
285
+ started_at TEXT,
286
+ completed_at TEXT,
287
+ session_id TEXT,
288
+ report_path TEXT,
289
+ error TEXT,
290
+ attempt_count INTEGER NOT NULL DEFAULT 0,
291
+ created_at TEXT NOT NULL,
292
+ updated_at TEXT NOT NULL
293
+ );`,`CREATE TABLE IF NOT EXISTS cron_event_log (
294
+ event_id TEXT PRIMARY KEY,
295
+ event_type TEXT NOT NULL,
296
+ source TEXT NOT NULL,
297
+ subject TEXT,
298
+ occurred_at TEXT NOT NULL,
299
+ received_at TEXT NOT NULL,
300
+ workspace_root TEXT,
301
+ dedupe_key TEXT,
302
+ payload_json TEXT,
303
+ attributes_json TEXT,
304
+ processing_status TEXT NOT NULL DEFAULT 'received'
305
+ CHECK (processing_status IN ('received', 'unmatched', 'queued', 'suppressed', 'failed')),
306
+ matched_spec_count INTEGER NOT NULL DEFAULT 0,
307
+ queued_run_count INTEGER NOT NULL DEFAULT 0,
308
+ suppressed_count INTEGER NOT NULL DEFAULT 0,
309
+ error TEXT,
310
+ created_at TEXT NOT NULL,
311
+ updated_at TEXT NOT NULL
312
+ );`,"DROP INDEX IF EXISTS cron_runs_one_off_active_idx;",`CREATE UNIQUE INDEX IF NOT EXISTS cron_runs_one_off_active_idx
313
+ ON cron_runs(spec_id, spec_revision)
314
+ WHERE trigger_kind = 'one_off';`,`CREATE INDEX IF NOT EXISTS cron_runs_claimable_idx
315
+ ON cron_runs(status, scheduled_for, claim_until_at);`,`CREATE INDEX IF NOT EXISTS cron_runs_spec_idx
316
+ ON cron_runs(spec_id, created_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_runs_trigger_event_idx
317
+ ON cron_runs(trigger_event_id);`,`CREATE INDEX IF NOT EXISTS cron_runs_event_spec_status_idx
318
+ ON cron_runs(spec_id, trigger_kind, status, scheduled_for);`,`CREATE INDEX IF NOT EXISTS cron_event_log_type_idx
319
+ ON cron_event_log(event_type, received_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_event_log_received_idx
320
+ ON cron_event_log(received_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_event_log_dedupe_idx
321
+ ON cron_event_log(event_type, source, dedupe_key, received_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_next_run_idx
322
+ ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
323
+ ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
324
+ ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
325
+ ON cron_specs(source_path);`];function Dj(f){f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec("PRAGMA foreign_keys = ON;");for(let $ of yU)f.exec($)}function YJ(f){if(!f)return;try{let $=JSON.parse(f);if($&&typeof $==="object"&&!Array.isArray($))return $}catch{}return}function BH(f,$={}){if(!f)return;try{let J=JSON.parse(f);if(!Array.isArray(J))return;let W=J.map((H)=>typeof H==="string"?H.trim():"").filter((H)=>H.length>0);if($.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function I$(f){if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="bigint")return Number(f);return}function $$(f){return{specId:n(f.spec_id),externalId:n(f.external_id),sourcePath:n(f.source_path),triggerKind:n(f.trigger_kind),sourceMtimeMs:I$(f.source_mtime_ms),sourceHash:S(f.source_hash),parseStatus:n(f.parse_status)==="invalid"?"invalid":"valid",parseError:S(f.parse_error),enabled:Number(f.enabled??0)===1,removed:Number(f.removed??0)===1,title:n(f.title),prompt:S(f.prompt),workspaceRoot:S(f.workspace_root),scheduleExpr:S(f.schedule_expr),timezone:S(f.timezone),eventType:S(f.event_type),filters:YJ(S(f.filters_json)),debounceSeconds:I$(f.debounce_seconds),dedupeWindowSeconds:I$(f.dedupe_window_seconds),cooldownSeconds:I$(f.cooldown_seconds),mode:S(f.mode),systemPrompt:S(f.system_prompt),providerId:S(f.provider_id),modelId:S(f.model_id),maxIterations:I$(f.max_iterations),timeoutSeconds:I$(f.timeout_seconds),maxParallel:I$(f.max_parallel),tools:BH(S(f.tools_json),{preserveEmpty:!0}),notesDirectory:S(f.notes_directory),extensions:BH(S(f.extensions_json),{preserveEmpty:!0}),source:S(f.source),tags:BH(S(f.tags_json)),metadata:YJ(S(f.metadata_json)),revision:Number(f.revision??1),lastMaterializedRunId:S(f.last_materialized_run_id),lastRunAt:S(f.last_run_at),nextRunAt:S(f.next_run_at),createdAt:n(f.created_at),updatedAt:n(f.updated_at)}}function AH(f){return{runId:n(f.run_id),specId:n(f.spec_id),specRevision:Number(f.spec_revision??1),triggerKind:n(f.trigger_kind),status:n(f.status),claimToken:S(f.claim_token),claimStartedAt:S(f.claim_started_at),claimUntilAt:S(f.claim_until_at),scheduledFor:S(f.scheduled_for),triggerEventId:S(f.trigger_event_id),startedAt:S(f.started_at),completedAt:S(f.completed_at),sessionId:S(f.session_id),reportPath:S(f.report_path),error:S(f.error),attemptCount:Number(f.attempt_count??0),createdAt:n(f.created_at),updatedAt:n(f.updated_at)}}function Mj(f){return{eventId:n(f.event_id),eventType:n(f.event_type),source:n(f.source),subject:S(f.subject),occurredAt:n(f.occurred_at),receivedAt:n(f.received_at),workspaceRoot:S(f.workspace_root),dedupeKey:S(f.dedupe_key),payload:YJ(S(f.payload_json)),attributes:YJ(S(f.attributes_json)),processingStatus:n(f.processing_status),matchedSpecCount:Number(f.matched_spec_count??0),queuedRunCount:Number(f.queued_run_count??0),suppressedCount:Number(f.suppressed_count??0),error:S(f.error),createdAt:n(f.created_at),updatedAt:n(f.updated_at)}}function _j(f){return f?JSON.stringify(f):null}var GU=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function Lj(f){if(f===void 0)return null;if(f&&typeof f==="object")return JSON.stringify(f);return f}function TU(f,$,J,W){for(let H of GU){let Q=f[H],Z=$[H];if(Lj(Q)!==Lj(Z))return!0}if(J===!1&&W===!0)return!0;return!1}function hU(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function DU(f){return`hub/schedules/${f}.cron.md`}function MU(f){let $={...f.metadata??{},...f.createdBy?{__hubScheduleCreatedBy:f.createdBy}:{},...f.cwd?{__hubScheduleCwd:f.cwd}:{},...f.runtimeOptions?{__hubRuntimeOptions:f.runtimeOptions}:{}};return Object.keys($).length>0?$:void 0}function RH(f){return{triggerKind:"schedule",title:f.name.trim(),prompt:f.prompt,workspaceRoot:f.workspaceRoot.trim(),schedule:f.cronPattern.trim(),mode:f.mode??"act",systemPrompt:f.systemPrompt,modelSelection:f.modelSelection?JSON.parse(JSON.stringify(f.modelSelection)):void 0,maxIterations:typeof f.maxIterations==="number"?Math.floor(f.maxIterations):void 0,timeoutSeconds:typeof f.timeoutSeconds==="number"?Math.floor(f.timeoutSeconds):void 0,maxParallel:typeof f.maxParallel==="number"?Math.max(1,Math.floor(f.maxParallel)):1,source:"hub-schedule",tags:f.tags?.filter(($)=>$.trim().length>0),enabled:f.enabled!==!1,metadata:MU(f)}}function zj(f){return JSON.stringify(RH(f))}function _U(f,$){let J=f.metadata?{...f.metadata}:{},W=$.createdBy===null?void 0:$.createdBy!==void 0?$.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,H=$.cwd!==void 0?$.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=$.runtimeOptions!==void 0?$.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:$.name??f.title,cronPattern:$.cronPattern??f.scheduleExpr??"",prompt:$.prompt??f.prompt??"",workspaceRoot:$.workspaceRoot??f.workspaceRoot??"",cwd:H,modelSelection:$.modelSelection!==void 0?$.modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:$.enabled??f.enabled,mode:$.mode??(f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"),systemPrompt:$.systemPrompt===null?void 0:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,maxIterations:$.maxIterations===null?void 0:$.maxIterations!==void 0?$.maxIterations:f.maxIterations,timeoutSeconds:$.timeoutSeconds===null?void 0:$.timeoutSeconds!==void 0?$.timeoutSeconds:f.timeoutSeconds,maxParallel:$.maxParallel??f.maxParallel??1,createdBy:W,tags:$.tags??f.tags,runtimeOptions:Q,metadata:$.metadata!==void 0?$.metadata:Object.keys(J).length>0?J:void 0}}class i8{db;constructor(f={}){let $=f.dbPath??UU();this.db=KU($),Dj(this.db)}close(){this.db.close?.()}getSpecBySourcePath(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get(f);return $?$$($):void 0}getSpec(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f);return $?$$($):void 0}getSpecByExternalId(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get(f);return $?$$($):void 0}listSpecs(f={}){let $=[],J=[];if(f.triggerKind)$.push("trigger_kind = ?"),J.push(f.triggerKind);if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.parseStatus)$.push("parse_status = ?"),J.push(f.parseStatus);if(!f.includeRemoved)$.push("removed = 0");let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,H).map((Z)=>$$(Z))}createHubSchedule(f){let $=`sched_${p8()}`,J=this.upsertSpec({externalId:$,sourcePath:DU($),triggerKind:"schedule",sourceHash:zj(f),parseStatus:"valid",spec:RH(f)});this.initializeScheduleNextRun(J.record.specId);let W=this.getSpec(J.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule(f){let $=this.db.prepare(`SELECT * FROM cron_specs
326
+ WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
327
+ ORDER BY created_at ASC LIMIT 1`).get(f);return $?$$($):void 0}listHubSchedules(f={}){let $=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.tags&&f.tags.length>0)for(let Q of f.tags)$.push("tags_json LIKE ?"),J.push(`%"${Q.trim()}"%`);let W=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
328
+ WHERE ${$.join(" AND ")}
329
+ ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>$$(Q))}updateHubSchedule(f,$){let J=this.getHubSchedule(f);if(!J)return;let W=_U(J,$),H=this.upsertSpec({externalId:f,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:zj(W),parseStatus:"valid",spec:RH(W)});if($.cronPattern!==void 0||$.enabled!==void 0)this.initializeScheduleNextRun(H.record.specId);return this.getSpec(H.record.specId)}deleteHubSchedule(f){let $=this.getHubSchedule(f);if(!$)return!1;return this.markSpecRemoved($.specId),this.cancelQueuedRunsForSpec($.specId),!0}enqueueHubScheduleRun(f,$="manual"){let J=this.getHubSchedule(f);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:$,scheduledFor:Yf()})}listEventSpecsForType(f){return this.db.prepare(`SELECT * FROM cron_specs
330
+ WHERE trigger_kind = 'event'
331
+ AND event_type = ?
332
+ AND enabled = 1
333
+ AND removed = 0
334
+ AND parse_status = 'valid'
335
+ ORDER BY created_at ASC`).all(f).map((J)=>$$(J))}upsertSpec(f){let $=Yf(),J=this.getSpecBySourcePath(f.sourcePath),W=f.spec,H={title:W?.title??J?.title??hU(f.sourcePath),prompt:W?.prompt,workspaceRoot:W?.workspaceRoot,scheduleExpr:W?.triggerKind==="schedule"?W.schedule:void 0,timezone:W?.triggerKind==="schedule"?W.timezone:void 0,eventType:W?.triggerKind==="event"?W.event:void 0,filters:W?.triggerKind==="event"?W.filters:void 0,debounceSeconds:W?.triggerKind==="event"?W.debounceSeconds:void 0,dedupeWindowSeconds:W?.triggerKind==="event"?W.dedupeWindowSeconds:void 0,cooldownSeconds:W?.triggerKind==="event"?W.cooldownSeconds:void 0,mode:W?.mode,systemPrompt:W?.systemPrompt,providerId:W?.modelSelection?.providerId,modelId:W?.modelSelection?.modelId,maxIterations:W?.maxIterations,timeoutSeconds:W?.timeoutSeconds,maxParallel:W&&"maxParallel"in W?W.maxParallel:void 0,tools:W?.tools,notesDirectory:W?.notesDirectory,extensions:W?.extensions,source:W?.source},Q=f.parseStatus==="valid"&&(W?.enabled??!0);if(!J){let V=`cspec_${p8()}`;this.insertSpecRow(V,f,H,Q,$);let Y=this.getSpec(V);if(!Y)throw Error("failed to insert cron_spec row");return{record:Y,created:!0,revisionChanged:!0}}let j=J.sourceHash!==f.sourceHash&&TU(J,H,J.enabled,Q),P=j?J.revision+1:J.revision;this.updateSpecRow(J.specId,f,H,Q,P,$);let X=this.getSpec(J.specId);if(!X)throw Error("failed to reload cron_spec after update");return{record:X,created:!1,revisionChanged:j}}insertSpecRow(f,$,J,W,H){let Q=$.spec;this.db.prepare(`INSERT INTO cron_specs (
336
+ spec_id, external_id, source_path, trigger_kind,
337
+ source_mtime_ms, source_hash, parse_status, parse_error,
338
+ enabled, removed, title, prompt, workspace_root,
339
+ schedule_expr, timezone, event_type, filters_json,
340
+ debounce_seconds, dedupe_window_seconds, cooldown_seconds,
341
+ mode, system_prompt, provider_id, model_id,
342
+ max_iterations, timeout_seconds, max_parallel,
343
+ tools_json, notes_directory, extensions_json, source,
344
+ tags_json, metadata_json, revision,
345
+ created_at, updated_at
346
+ ) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run(f,$.externalId,$.sourcePath,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,W?1:0,0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Q?.tags?JSON.stringify(Q.tags):null,Q?.metadata?JSON.stringify(Q.metadata):null,1,H,H)}updateSpecRow(f,$,J,W,H,Q){let Z=$.spec;this.db.prepare(`UPDATE cron_specs SET
347
+ external_id = ?, trigger_kind = ?,
348
+ source_mtime_ms = ?, source_hash = ?, parse_status = ?, parse_error = ?,
349
+ enabled = ?, removed = 0, title = ?, prompt = ?,
350
+ workspace_root = ?, schedule_expr = ?, timezone = ?,
351
+ event_type = ?, filters_json = ?,
352
+ debounce_seconds = ?, dedupe_window_seconds = ?, cooldown_seconds = ?,
353
+ mode = ?, system_prompt = ?, provider_id = ?, model_id = ?,
354
+ max_iterations = ?, timeout_seconds = ?, max_parallel = ?,
355
+ tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
356
+ tags_json = ?, metadata_json = ?,
357
+ revision = ?, updated_at = ?
358
+ WHERE spec_id = ?`).run($.externalId,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,W?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Z?.tags?JSON.stringify(Z.tags):null,Z?.metadata?JSON.stringify(Z.metadata):null,H,Q,f)}markSpecRemoved(f){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(Yf(),f)}updateSpecNextRunAt(f,$){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run($??null,Yf(),f)}updateSpecLastRunAt(f,$){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run($,Yf(),f)}updateLastMaterializedRunId(f,$){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run($,Yf(),f)}initializeScheduleNextRun(f){let $=this.getSpec(f);if(!$||$.triggerKind!=="schedule"||!$.enabled||!$.scheduleExpr){this.updateSpecNextRunAt(f,void 0);return}let J=new Date(m$($.scheduleExpr,Date.now(),$.timezone)).toISOString();this.updateSpecNextRunAt(f,J)}materializeDueScheduleRun(f){let $=f.nowMs,J=new Date($).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f.specId);if(!W)return this.db.exec("COMMIT;"),{queued:!1};let H=$$(W);if(H.triggerKind!=="schedule"||!H.enabled||H.removed||H.parseStatus!=="valid"||!H.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let Q=H.nextRunAt;if(!Q){let P=new Date(m$(H.scheduleExpr,$,H.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(P,J,H.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:P}}if(new Date(Q).getTime()>$)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Q};let Z=`crun_${p8()}`,j;try{j=new Date(m$(H.scheduleExpr,$,H.timezone)).toISOString()}catch{j=void 0}return this.db.prepare(`INSERT INTO cron_runs (
359
+ run_id, spec_id, spec_revision, trigger_kind, status,
360
+ scheduled_for, trigger_event_id, attempt_count,
361
+ created_at, updated_at
362
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(Z,H.specId,H.revision,"schedule","queued",Q,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
363
+ last_materialized_run_id = ?,
364
+ last_run_at = ?,
365
+ next_run_at = ?,
366
+ updated_at = ?
367
+ WHERE spec_id = ?`).run(Z,J,j??null,J,H.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(Z),nextRunAt:j}}catch(W){throw this.db.exec("ROLLBACK;"),W}}getRun(f){let $=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get(f);return $?AH($):void 0}insertEventLog(f,$={}){let J=Yf(),W=$.receivedAtIso??J,H=f.eventId.trim();if(!H)throw Error("automation event requires eventId");let Q=f.eventType.trim();if(!Q)throw Error("automation event requires eventType");let Z=f.source.trim();if(!Z)throw Error("automation event requires source");let j=f.occurredAt.trim()||W,P=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
368
+ event_id, event_type, source, subject,
369
+ occurred_at, received_at, workspace_root, dedupe_key,
370
+ payload_json, attributes_json, processing_status,
371
+ matched_spec_count, queued_run_count, suppressed_count,
372
+ error, created_at, updated_at
373
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(H,Q,Z,f.subject?.trim()||null,j,W,f.workspaceRoot?.trim()||null,f.dedupeKey?.trim()||null,_j(f.payload),_j(f.attributes),"received",0,0,0,null,J,J).changes??0,X=this.getEventLog(H);if(!X)throw Error("failed to insert cron_event_log row");return{record:X,created:P===1}}getEventLog(f){let $=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get(f);return $?Mj($):void 0}listEventLogs(f={}){let $=[],J=[];if(f.eventType)$.push("event_type = ?"),J.push(f.eventType);if(f.source)$.push("source = ?"),J.push(f.source);if(f.processingStatus)$.push("processing_status = ?"),J.push(f.processingStatus);let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${W}
374
+ ORDER BY received_at DESC, created_at DESC
375
+ LIMIT ?`).all(...J,H).map((Z)=>Mj(Z))}updateEventLogProcessing(f,$){return(this.db.prepare(`UPDATE cron_event_log SET
376
+ processing_status = ?,
377
+ matched_spec_count = COALESCE(?, matched_spec_count),
378
+ queued_run_count = COALESCE(?, queued_run_count),
379
+ suppressed_count = COALESCE(?, suppressed_count),
380
+ error = ?,
381
+ updated_at = ?
382
+ WHERE event_id = ?`).run($.status,$.matchedSpecCount??null,$.queuedRunCount??null,$.suppressedCount??null,$.error??null,Yf(),f).changes??0)===1}listRuns(f={}){let $=[],J=[];if(f.specId)$.push("spec_id = ?"),J.push(f.specId);if(f.status){let Z=Array.isArray(f.status)?f.status:[f.status];if(Z.length>0){let j=Z.map(()=>"?").join(",");$.push(`status IN (${j})`);for(let P of Z)J.push(P)}}let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,H).map((Z)=>AH(Z))}hasRecentEventRunForDedupe(f){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
383
+ INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
384
+ WHERE r.spec_id = ?
385
+ AND r.trigger_kind = 'event'
386
+ AND e.dedupe_key = ?
387
+ AND e.received_at >= ?
388
+ LIMIT 1`).get(f.specId,f.dedupeKey,f.sinceIso)}hasRecentEventRunForSpec(f){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
389
+ INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
390
+ WHERE r.spec_id = ?
391
+ AND r.trigger_kind = 'event'
392
+ AND e.received_at >= ?
393
+ LIMIT 1`).get(f.specId,f.sinceIso)}findQueuedEventRunForDedupe(f){let $=this.db.prepare(`SELECT r.* FROM cron_runs r
394
+ INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
395
+ WHERE r.spec_id = ?
396
+ AND r.trigger_kind = 'event'
397
+ AND r.status = 'queued'
398
+ AND e.dedupe_key = ?
399
+ ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
400
+ LIMIT 1`).get(f.specId,f.dedupeKey);return $?AH($):void 0}updateQueuedEventRunForDebounce(f){let $=Yf();if((this.db.prepare(`UPDATE cron_runs SET
401
+ trigger_event_id = ?,
402
+ scheduled_for = ?,
403
+ updated_at = ?
404
+ WHERE run_id = ?
405
+ AND trigger_kind = 'event'
406
+ AND status = 'queued'`).run(f.triggerEventId,f.scheduledFor,$,f.runId).changes??0)!==1)return;return this.getRun(f.runId)}hasOneOffRunForRevision(f,$){return!!this.db.prepare(`SELECT run_id FROM cron_runs
407
+ WHERE spec_id = ? AND spec_revision = ?
408
+ AND trigger_kind = 'one_off'
409
+ LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${p8()}`,J=Yf();this.db.prepare(`INSERT INTO cron_runs (
410
+ run_id, spec_id, spec_revision, trigger_kind, status,
411
+ scheduled_for, trigger_event_id, attempt_count,
412
+ created_at, updated_at
413
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run($,f.specId,f.specRevision,f.triggerKind,"queued",f.scheduledFor??null,f.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId(f.specId,$);let W=this.getRun($);if(!W)throw Error("failed to insert cron_run row");return W}cancelQueuedRunsForSpec(f){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
414
+ WHERE spec_id = ? AND status = 'queued'`).run(Yf(),f).changes??0}claimDueRuns(f){let $=f.nowIso,J=Math.max(1000,Math.floor(f.leaseMs)),W=new Date(new Date($).getTime()+J).toISOString(),H=Math.max(1,Math.floor(f.limit??25)),Q=[];this.db.exec("BEGIN IMMEDIATE;");try{let Z=this.db.prepare(`SELECT * FROM cron_runs
415
+ WHERE (
416
+ status = 'queued'
417
+ OR (
418
+ status = 'running'
419
+ AND claim_until_at IS NOT NULL
420
+ AND claim_until_at <= ?
421
+ AND completed_at IS NULL
422
+ )
423
+ )
424
+ AND (scheduled_for IS NULL OR scheduled_for <= ?)
425
+ ORDER BY COALESCE(scheduled_for, created_at) ASC
426
+ LIMIT ?`).all($,$,H);for(let j of Z){let P=n(j.run_id);if(!P)continue;let X=`cclaim_${p8()}`;if((this.db.prepare(`UPDATE cron_runs SET
427
+ status = 'running',
428
+ claim_token = ?,
429
+ claim_started_at = ?,
430
+ claim_until_at = ?,
431
+ started_at = ?,
432
+ completed_at = NULL,
433
+ session_id = NULL,
434
+ report_path = NULL,
435
+ error = NULL,
436
+ attempt_count = attempt_count + 1,
437
+ updated_at = ?
438
+ WHERE run_id = ?
439
+ AND (
440
+ status = 'queued'
441
+ OR (
442
+ status = 'running'
443
+ AND claim_until_at IS NOT NULL
444
+ AND claim_until_at <= ?
445
+ AND completed_at IS NULL
446
+ )
447
+ )`).run(X,$,W,$,$,P,$).changes??0)!==1)continue;let Y=this.getRun(P);if(!Y)continue;Q.push({run:Y,claimToken:X,claimUntilAt:W})}this.db.exec("COMMIT;")}catch(Z){throw this.db.exec("ROLLBACK;"),Z}return Q}renewClaim(f,$,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
448
+ WHERE run_id = ? AND claim_token = ?`).run(J,Yf(),f,$).changes??0)===1}completeRun(f,$){let J=$.completedAtIso??Yf(),W=$.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
449
+ status = ?,
450
+ session_id = COALESCE(?, session_id),
451
+ report_path = COALESCE(?, report_path),
452
+ error = ?,
453
+ completed_at = ?,
454
+ claim_started_at = NULL,
455
+ claim_token = NULL,
456
+ claim_until_at = NULL,
457
+ updated_at = ?
458
+ ${W}`).run($.status,$.sessionId??null,$.reportPath??null,$.error??null,J,J,f,...$.claimToken?[$.claimToken]:[]).changes??0)>0}requeueRun(f){let $=Yf();return(this.db.prepare(`UPDATE cron_runs SET
459
+ status = 'queued',
460
+ claim_started_at = NULL,
461
+ claim_token = NULL,
462
+ claim_until_at = NULL,
463
+ started_at = NULL,
464
+ completed_at = NULL,
465
+ session_id = NULL,
466
+ report_path = NULL,
467
+ error = ?,
468
+ scheduled_for = COALESCE(?, scheduled_for),
469
+ updated_at = ?
470
+ WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,Yf(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,Yf(),f)}}class n8{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new i8({dbPath:f.dbPath});let $=f.specs;this.reconciler=new VH({store:this.store,specs:$}),this.materializer=new c8({store:this.store}),this.eventIngress=new e5({store:this.store,logger:f.logger}),this.runner=new d8({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:f.workspaceRoot,specs:$,logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency}),this.watcher=new YH({reconciler:this.reconciler,debounceMs:f.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=f.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs(f){return this.store.listSpecs(f)}getSpec(f){return this.store.getSpec(f)}listRuns(f){return this.store.listRuns(f)}getRun(f){return this.store.getRun(f)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns(f=20){return this.store.listRuns({status:"queued",limit:f})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent(f){return this.eventIngress.ingestEvent(f)}listEventLogs(f){return this.store.listEventLogs(f)}getEventLog(f){return this.store.getEventLog(f)}}var mj={};N(mj,{manifestToSessionRecord:()=>RJ,listSessionHistoryFromBackend:()=>KH,listSessionHistory:()=>FJ,hydrateSessionHistory:()=>kj});import{readdir as NU,readFile as Cj}from"node:fs/promises";import{join as Ej}from"node:path";import{formatDisplayUserInput as qU,normalizeUserInput as bU}from"@cline/shared";import{resolveSessionDataDir as Sj}from"@cline/shared/storage";import{existsSync as LU}from"node:fs";import{readFile as zU}from"node:fs/promises";import{formatDisplayUserInput as Oj}from"@cline/shared";class a8{listeners=new Set;subscribe(f,$){let J={listener:f,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit(f){let $=f.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$)continue;J.listener(f)}}get size(){return this.listeners.size}}async function x$(f){let $=f?.trim();if(!$||!LU($))return[];try{let J=(await zU($,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return Nj(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let H=W.messages;if(Array.isArray(H))return Nj(H)}return[]}catch{return[]}}function OU(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:Oj(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:Oj($.text)}})}}function Nj(f){return f.map(OU)}function qj(f){return f?{...f}:void 0}async function bj(f,$){if(!(f.hookName==="tool_call"||!!f.parent_agent_id))return;await $.queueSpawnRequest(f);let W=await $.upsertSubagentSessionFromHook(f);if(!W)return;await $.appendSubagentHookAudit(W,f),await $.applySubagentStatus(W,f)}function BJ(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function Cf(f){let $=BJ(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function AJ(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function wU(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function yH(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function CU(f){let $=f.match(/\d{13,}/g);if(!$||$.length===0)return 0;let J=0;for(let W of $){let H=Number.parseInt(W,10);if(Number.isFinite(H)&&H>J)J=H}return J}function RJ(f){return{sessionId:f.session_id,source:f.source,pid:f.pid,startedAt:f.started_at,endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspace_root,teamName:f.team_name,enableTools:f.enable_tools,enableSpawn:f.enable_spawn,enableTeams:f.enable_teams,isSubagent:!1,prompt:f.prompt,metadata:f.metadata,messagesPath:f.messages_path,updatedAt:f.ended_at??f.started_at}}async function EU(f){let $=yH(f);if($===0)return[];let J=Sj(),H=(await NU(J,{withFileTypes:!0}).catch(()=>[])).filter((Z)=>Z.isDirectory()).map((Z)=>({entry:Z,recency:CU(Z.name.trim())})).sort((Z,j)=>j.recency-Z.recency||j.entry.name.localeCompare(Z.entry.name));return(await Promise.all(H.map(async({entry:Z})=>{let j=Z.name.trim();if(!j)return;let P=Ej(J,j,`${j}.json`),X=await Cj(P,"utf8").catch(()=>{return});if(!X)return;let V;try{V=JSON.parse(X)}catch{return}let Y=Uf.safeParse(V);if(!Y.success)return;return RJ(Y.data)}))).filter((Z)=>Boolean(Z)).sort((Z,j)=>j.startedAt.localeCompare(Z.startedAt)).slice(0,$)}async function SU(f,$){let J=yH($);if(J===0)return await f.listSessions(0),[];return(await f.listSessions(J)).slice(0,J)}function kU(f){if(typeof f==="string")return f.trim();let $=[];for(let J of f){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let H=W.text?.trim();if(H)$.push(H)}return $.join(`
471
+ `).trim()}function wj(f){return f.replace(/\s+/g," ").trim()}function mU(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function IU(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let W=wj(kU(J.content));if(!W)continue;let H=$==="user"?wj(qU(W)):W,Q=bU(H.split(`
472
+ `)[0]??H);return mU(Q,50)}return}function xU(f){let $=0;for(let J of f)$+=AJ(J.metrics?.cost)??0;return $}function gU(f){let $,J;for(let W=f.length-1;W>=0;W-=1){let H=f[W];if(!$)$=Cf(H.modelInfo?.provider);if(!J)J=Cf(H.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function vU(f){return Cf(f?.provider)??Cf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function uU(f){return Cf(f?.model)??Cf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function FH(f,$){let J=wU(f.metadata),W=BJ($?.title)??BJ(J?.title),H=AJ($?.totalCost)??AJ(J?.totalCost),Q=J||W!==void 0||H!==void 0?{...J??{},...W!==void 0?{title:W}:{},...H!==void 0?{totalCost:H}:{}}:void 0;return{...f,provider:Cf($?.provider)??Cf(f.provider)??vU(J)??"",model:Cf($?.model)??Cf(f.model)??uU(J)??"",metadata:Q}}async function kj(f,$){return await Promise.all($.map(async(J)=>{let W=FH(J),H=Boolean(BJ(W.metadata?.title)),Q=Boolean(Cf(W.provider)),Z=Boolean(Cf(W.model)),j=AJ(W.metadata?.totalCost),P=j!==void 0&&j>0;if(H&&Q&&Z&&P)return W;let X=await f.readSessionMessages(J.sessionId);if(X.length===0)return W;let V=gU(X),Y=xU(X);return FH(J,{title:H?void 0:IU(X),provider:Q?void 0:V.provider,model:Z?void 0:V.model,totalCost:P||Y<=0?void 0:Y})}))}async function FJ(f,$={}){let J=yH($.limit),W=await SU(f,J),H=$.includeManifestFallback===!0&&W.length<J?await EU(Math.min(Math.max(J*2,100),500)):[],Q=new Map;for(let j of[...W,...H]){if(Q.has(j.sessionId))continue;Q.set(j.sessionId,j)}let Z=H.length===0?W:Array.from(Q.values()).sort((j,P)=>P.startedAt.localeCompare(j.startedAt)).slice(0,J);if($.hydrate===!1)return Z.map((j)=>FH(j));return await kj(f,Z)}async function cU(f){let $=f.trim();if(!$)return;let J=Ej(Sj(),$,`${$}.json`),W=await Cj(J,"utf8").catch(()=>{return});if(!W)return;try{let H=Uf.safeParse(JSON.parse(W));return H.success?H.data.messages_path:void 0}catch{return}}async function KH(f,$={}){let J=new Map;return await FJ({listSessions:async(H)=>{let Q=await f.listSessions(H);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(r2)},readSessionMessages:async(H)=>{let Q=J.get(H)?.messagesPath??await cU(H);return await x$(Q)}},$)}var IP={};N(IP,{resolveSessionBackend:()=>sH,createRuntimeHost:()=>a1});import{createSessionId as bG,resolveHubCommandTimeoutMs as wG}from"@cline/shared";import{spawn as VG}from"node:child_process";import{closeSync as YG,mkdirSync as BG,openSync as AG}from"node:fs";import{basename as RG,dirname as FG,join as yG}from"node:path";import{fileURLToPath as KG}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as UG,isHubDaemonProcess as tj,withResolvedClineBuildEnv as GG}from"@cline/shared";import{createHash as dU,randomBytes as rU}from"node:crypto";import{existsSync as lU}from"node:fs";import{chmod as pU,mkdir as UH,readFile as cj,rm as GH,writeFile as dj}from"node:fs/promises";import{dirname as rj,join as TH}from"node:path";import{resolveClineDataDir as t8,resolveClineDir as lj}from"@cline/shared/storage";var xj="0.0.38-nightly.1778113663";var gj={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:xj,repository:{type:"git",url:"https://github.com/cline/sdk",directory:"packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{development:"./src/index.ts",types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{development:"./src/hub/index.ts",types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{development:"./src/hub/daemon/entry.ts",types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{development:"./src/services/telemetry/index.ts",types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"rm -rf dist && bun run ./bun.mts && bun tsc -p tsconfig.build.json",clean:"rm -rf dist node_modules",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var iU="CLINE_HUB_DISCOVERY_PATH",nU="CLINE_HUB_BUILD_ID",vj=30000,aU=15000,tU=100;function sU(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function oU(f){return dU("sha256").update(f).digest("hex").slice(0,12)}function eU(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function yJ(){return rU(32).toString("hex")}function fG(f){return new Promise(($)=>setTimeout($,f))}function $G(f){return`${f}.lock`}async function JG(f){try{let $=JSON.parse(await cj(TH(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function uj(f){await GH(f,{recursive:!0,force:!0}).catch(()=>{return})}function J$(){return process.env[nU]?.trim()||String(gj.version)}function M0(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${oU(f)}`,J=process.env[iU]?.trim()||TH(t8(),"locks","hub","owners",`${sU($)}.json`);return{ownerId:$,discoveryPath:J}}function pj(f=`hub-${Date.now().toString(36)}`){return M0(f)}async function Zf(f){try{let $=JSON.parse(await cj(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function KJ(f,$){await UH(rj(f),{recursive:!0}),await GH(f,{force:!0}).catch(()=>{return}),await dj(f,`${JSON.stringify($,null,2)}
473
+ `,{encoding:"utf8",mode:384}),await pU(f,384)}async function Ef(f){await GH(f,{force:!0}).catch(()=>{return})}async function UJ(f,$){let J=$G(f);await UH(rj(J),{recursive:!0});let W=Date.now()+aU;while(!0)try{await UH(J,{recursive:!1}),await dj(TH(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
474
+ `,"utf8");try{return await $()}finally{await uj(J)}}catch(H){if((H instanceof Error&&"code"in H?String(H.code):"")!=="EEXIST")throw H;let Z=await JG(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):vj+1;if(!Z||!eU(Z.pid)||j>vj){await uj(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await fG(tU)}}async function Bf(f){try{let $=await fetch(hH(f));if(!$.ok)return;return await $.json()}catch{return}}function lf(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function hH(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function ij(f){return lU(f)}import{CLINE_HUB_DEV_PORT as WG,CLINE_HUB_PORT as HG,resolveClineBuildEnv as QG}from"@cline/shared";var ZG="CLINE_HUB_HOST",jG="CLINE_HUB_PORT",PG="CLINE_HUB_PATHNAME",DH="127.0.0.1",MH=HG,_H="/hub";function nj(f){return QG(f)==="development"?WG:MH}function LH(f={}){return(f.env??process.env)[ZG]?.trim()||DH}function v1(f={}){let J=(f.env??process.env)[jG]?.trim();if(!J)return nj(f);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return nj(f);return W}function zH(f={}){return(f.env??process.env)[PG]?.trim()||_H}function Sf(f={},$={}){return{host:f.host??LH($),port:f.port??v1($),pathname:f.pathname??zH($)}}var XG="shared:cline";function aj(f){let $=D0(f.trim());return M0(`workspace:${$||f.trim()}`)}function Qf(f=XG){return M0(f)}var TG=8000,hG=200,DG=3000,MG=100,_G="--cline-hub-daemon";function LG(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function zG(){try{let f=yG(t8(),"logs","hub-daemon.log");return BG(FG(f),{recursive:!0}),{fd:AG(f,"a"),logPath:f}}catch{return}}function s8(f){let $=f.buildId?.trim();return!!$&&$===J$()}async function OG(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Bf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,MG))}return!1}async function o8(f,$){if(s8(f))return;if(await e8(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await OG(f.url,DG),await Ef($).catch(()=>{return})}function NG(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return KG(new URL(`./entry.${f}`,import.meta.url))}function qG(f,$){let J=NG(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let H=RG(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=H&&J.toLowerCase().endsWith(".ts"),j=Q?[_G]:[...Z?["--conditions=development"]:[],J];return{launcher:W,args:[...j,"--cwd",f,...LG($)],cwd:f,env:{...GG(process.env),CLINE_NO_INTERACTIVE:"1",[UG]:"1"}}}function u1(f,$={}){if(tj())return;let J=qG(f,$),W=zG();try{VG(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)YG(W.fd)}}function GJ(f,$={}){if(tj())return;let J=Qf(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=Sf($),Q=lf(H.host,H.port,H.pathname);Zf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let V=await Bf(Z.url);if(V?.url&&s8(V)&&await f0(V.url,{authToken:Z.authToken}))return;if(V?.url)await o8({...V,authToken:Z.authToken},J.discoveryPath);else await Ef(J.discoveryPath).catch(()=>{return})}let j=await Bf(Q);if(j?.url)await o8(j,J.discoveryPath);let X=!W&&H.port!==0?{...H,port:0}:H;u1(f,X)}).catch(()=>{})}async function sj(f,$={}){let J=Qf(),W=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=Sf($),Z=lf(Q.host,Q.port,Q.pathname),j=(A)=>{if(!W)W$(A.url,A.authToken);return A},P=await Zf(J.discoveryPath);if(P?.url){let A=await Bf(P.url);if(A?.url&&s8(A)&&await f0(A.url,{authToken:P.authToken}))return j({url:A.url,authToken:P.authToken});if(A?.url)await o8({...A,authToken:P.authToken},J.discoveryPath);else await Ef(J.discoveryPath).catch(()=>{return})}let X=await Bf(Z);if(X?.url)await o8(X,J.discoveryPath);let Y=!H&&Q.port!==0?{...Q,port:0}:Q;u1(f,Y);let B=Date.now()+TG;while(Date.now()<B){let A=await Zf(J.discoveryPath);if(A?.url){let U=await Bf(A.url);if(U?.url&&s8(U)&&await f0(U.url,{authToken:A.authToken}))return j({url:U.url,authToken:A.authToken})}let R=await Bf(Z);if(R?.url&&!s8(R))await o8(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,hG))}throw Error("Timed out waiting for detached hub startup.")}function CG(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function JP(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return JP(f.data);return String(f)}function EG(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function oj(f){let $=f,J=EG($.reason);return new yf("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:OH,{closeCode:$.code,closeReason:J||void 0})}function SG(f,$){if(f instanceof yf)return f;if(f instanceof Error)return new yf("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new yf("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new yf("hub_connect_failed",J);let W=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new yf("hub_connect_failed",W?`Failed to connect to hub at ${$.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var kG=8000,mG=200,ej="*",fP=8000,IG="cline-hub-auth.",WP=new Map,HP=new Set,xG=3000,gG=3000,vG=100,OH="Hub connection closed",uG=250,cG=5000,$P=0.5;class yf extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function bH(f){return f instanceof yf}class c1 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function TJ(f,$){return f instanceof c1&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function QP(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=wH(f.toString());return J?WP.get(J):void 0}function dG(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function wH(f){if(!dG(f))return;let $=new URL(H$(f));return $.search="",$.hash="",$.toString()}function NH(f){let $=wH(f);return!!$&&HP.has($)}function W$(f,$){let J=wH(f);if(J){if(HP.add(J),$?.trim())WP.set(J,$)}return f}class pf{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new yf("hub_connection_closed",OH);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||QP(f);f.hash="";let W=new(CG())(f.toString(),$?[`${IG}${$}`]:void 0);this.socket=W;let H=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,P=setTimeout(()=>{if(j)return;j=!0,H=!0,this.lastCloseError=new yf("hub_connect_timeout",`Timed out connecting to hub after ${fP}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}Z(this.lastCloseError)},fP);W.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(P),Q()}),W.addEventListener("error",(X)=>{if(j)return;j=!0,clearTimeout(P),this.lastCloseError=SG(X,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),W.addEventListener("close",(X)=>{if(j)return;if(j=!0,clearTimeout(P),!H)this.lastCloseError=oj(X),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(JP(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!H)this.lastCloseError=oj(Q),this.sawSocketClose=!0;this.registered=!1;for(let Z of this.pendingReplies.values())Z.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,W={listener:f,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,W){let H=0,Q=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,W)}catch(Z){if(!Q||H>=1||!await this.recoverLocalHubTransport(Z))throw Z;H+=1}}async commandOnce(f,$,J,W){await this.connect();let H=bG("hubreq_"),Q=wG(f,W?.timeoutMs),Z=new Promise((P,X)=>{let V=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(H))return;X(new c1(f,"hub_command_timeout",`Hub command ${f} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${H}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(H,{resolve:(Y)=>{if(V)clearTimeout(V);P(Y)},reject:(Y)=>{if(V)clearTimeout(V);X(Y)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:H,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(P){throw this.pendingReplies.delete(H),P}let j=await Z;if(!j.ok)throw new c1(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!NH(this.currentUrl)||!bH(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await g$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let f=Math.min(uG*2**this.reconnectAttempt,cG),$=Math.round(f*(1-$P)+Math.random()*f*$P);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!NH(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await g$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new yf("hub_connection_closed",OH),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new yf("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),W=(this.subscriptionCounts.get(J)??0)+$;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,W),$>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??ej}subscriptionSessionIdFromKey(f){return f===ej?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function H$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function f0(f,$){let J=new pf({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function qH(f,$){let J=H$(f),W=await Bf(J);if(!W)return{status:"unreachable",url:J};let H=J$(),Q=W.buildId?.trim();if(!Q||Q!==H)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await f0(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function rG(f){let $=Date.now()+kG;while(Date.now()<$){let J=await Zf(f.discoveryPath);if(J?.url){let W=await qH(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return W$(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,mG))}return}async function lG(f){let $=Date.now()+gG;while(Date.now()<$){if(!(await Bf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,vG))}return!1}function pG(f,$){try{return H$(f)===H$($)}catch{return!1}}function iG(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function nG(f,$,J){let W=new pf({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let H=await W.command("session.list",{limit:500},void 0,{timeoutMs:xG});return!iG(H.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function f4(f={}){if(f.endpoint?.trim()){let H=await qH(f.endpoint);return H.status==="compatible"?H.url:void 0}let $=Qf(),J=await Zf($.discoveryPath);if(!J?.url)return;let W=await qH(J.url);if(W.status==="compatible")return W$(W.url,J.authToken);if(W.status==="build_mismatch")await Ef($.discoveryPath).catch(()=>{return});return}async function g$(f={}){let $=await f4(f);if($&&await f0($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Qf();return u1(f.workspaceRoot??process.cwd()),await rG(J)}async function e8(f,$){let J=new URL(f),W=$?.trim()||QP(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function CH(){let f=Qf(),$=await Zf(f.discoveryPath);if(!$?.url)return!1;try{if(await e8($.url,$.authToken))return!0}catch{}return!1}async function hJ(f){if(!NH(f.url))return;let $=Qf(),J=await Zf($.discoveryPath);if(!J?.url||!pG(J.url,f.url))return;if(!await nG(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await CH())return;if(!await lG(J.url))return;return await Ef($.discoveryPath).catch(()=>{return}),await g$({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}var FP={};N(FP,{HubRuntimeHost:()=>_0});import{createSessionId as jP,HUB_CHECKPOINT_CAPABILITY as oG,HUB_COMPACTION_CAPABILITY as eG,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as fT,HUB_HOOK_CAPABILITY_PREFIX as $T,HUB_MISTAKE_LIMIT_CAPABILITY as JT,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as WT,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as HT,isHubToolExecutorName as QT}from"@cline/shared";var ZP={};N(ZP,{createCoreSessionSnapshot:()=>$0,coreSessionSnapshotToRecord:()=>DJ});function aG(f){return f?JSON.parse(JSON.stringify(f)):void 0}function tG(f){return f?JSON.parse(JSON.stringify(f)):void 0}function sG(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,W=(Array.isArray($?.history)?$.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let j=typeof Z.ref==="string"?Z.ref.trim():"",P=Number(Z.createdAt),X=Number(Z.runCount);if(!j||!Number.isFinite(P)||!Number.isInteger(X))return[];return[{ref:j,createdAt:P,runCount:X,...Z.kind==="stash"||Z.kind==="commit"?{kind:Z.kind}:{}}]}),H=W.at(-1),Q=f?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...H?{latest:H}:{},history:W}}function $0(f){let{session:$}=f,J=aG($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:tG(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...(()=>{let W=sG(J);return W?{checkpoint:W}:{}})()}}function DJ(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function d1(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var ZT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function PP(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function XP(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function VP(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function v$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function YP(f,$){let J={manifest:[],handlers:new Map};for(let H of Object.keys($.toolExecutors??{}).filter(QT)){let Q=$.toolExecutors?.[H];if(typeof Q!=="function")continue;v$(J,{kind:"toolExecutor",executor:H,capabilityName:`${WT}${H}`},async({payload:Z,abortSignal:j})=>{let P=Array.isArray(Z.args)?[...Z.args]:[],X={...VP(Z.context),signal:j};return{result:await Q(...P,X)}})}for(let H of f?.extraTools??[])v$(J,{kind:"tool",name:H.name,description:H.description,inputSchema:d1(H.inputSchema)??{},...H.lifecycle?{lifecycle:d1(H.lifecycle)}:{},capabilityName:`${fT}${H.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let P={...VP(Q.context),signal:Z};return{result:await H.execute(Q.input,{...P,emitUpdate:(V)=>{j({update:V})}})}});let W=f?.hooks;if(W)for(let H of ZT){let Q=W[H];if(typeof Q!=="function")continue;v$(J,{kind:"hook",name:H,capabilityName:`${$T}${H}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let H=f.compaction.compact;v$(J,{kind:"compaction",capabilityName:eG,config:PP(f.compaction)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let H=f.checkpoint.createCheckpoint;v$(J,{kind:"checkpoint",capabilityName:oG,config:PP(f.checkpoint)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let H=f.onConsecutiveMistakeLimitReached;v$(J,{kind:"mistakeLimit",capabilityName:JT},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.userInstructionService){let H=f.userInstructionService;v$(J,{kind:"userInstructionService",capabilityName:HT},async()=>{return await H.start().catch(()=>{}),{snapshot:{records:{skill:H.listRecords("skill"),rule:H.listRecords("rule"),workflow:H.listRecords("workflow")},runtimeCommands:H.listRuntimeCommands()}}})}return J}function jT(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return"Capability request was cancelled."}function PT(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function XT(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function VT(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,W=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function YT(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,W=XT(J)?J:J==="failed"?"error":"completed",H=VT(f?.usage??$?.usage);return{type:"done",reason:W,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:H}}function EH(f,$){return f.error?.message??`hub command failed: ${$}`}function $4(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function RP(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:Pf.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:$4(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:$4(f.status)==="completed"?0:$4(f.status)==="failed"?1:void 0,status:$4(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function u$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function BT(f){let $=u$(f?.snapshot);if($)return DJ($);let J=f?.session;return J?RP(J):void 0}function BP(f,$,J){let W=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return Uf.parse({version:1,session_id:f,source:$.source??Pf.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:$4(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:W,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function AP(f,$){return Uf.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class _0{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new a8;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=Vf(f.capabilities)??{},this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new pf({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!TJ(f,"session.create"))return!1;let $=await hJ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=YP(f.localRuntime,$),W=f.config.sessionId?.trim()||jP(),H=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:d1({...f.config,sessionId:W}),metadata:{...f.sessionMetadata??{},source:f.source??Pf.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:d1(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(W,$,J.handlers);let Q;try{Q=await H()}catch(X){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(X)){this.registerPlannedSession(W,$,J.handlers);try{Q=await H()}catch(V){throw this.cleanupPlannedSession(W),V}}else throw X}let Z=u$(Q.payload?.snapshot),j=Q.payload?.session,P=(Z?.sessionId??j?.sessionId)?.trim();if(!P)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(P!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(P,$,J.handlers);return{sessionId:P,manifest:Z?AP(Z,f):BP(P,f,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let W=f.start,H=W?this.resolveCapabilities(W):void 0,Q=W?YP(W.localRuntime,H??{}):{manifest:[],handlers:new Map},Z=W?W.config.sessionId?.trim()||jP():void 0;if(Z&&H)this.sessionCapabilities.set(Z,H);if(Z&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Z,Q.handlers),this.ensureSessionSubscription(Z);let j;try{j=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??f.cwd,sessionConfig:d1({...W.config,sessionId:Z}),metadata:{...W.sessionMetadata??{},source:W.source??Pf.CORE,provider:W.config.providerId,model:W.config.modelId,enableTools:W.config.enableTools,enableSpawn:W.config.enableSpawnAgent,enableTeams:W.config.enableAgentTeams,teamName:W.config.teamName,prompt:W.prompt,interactive:W.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:d1(W.toolPolicies)}:{}},$)}catch(A){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw A}if(!j.ok){let A=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error(A)}let P=u$(j.payload?.snapshot),X=j.payload?.session,V=(P?.sessionId??X?.sessionId)?.trim();if(J&&!V){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error("Hub checkpoint restore returned no session id")}if(V&&Z&&V!==Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);if(V&&H)this.sessionCapabilities.set(V,H);if(V&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(V,Q.handlers);if(V)this.ensureSessionSubscription(V);let Y=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,B=j.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:P?AP(P,W??{}):BP(V,W??{},X),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:Y,checkpoint:B}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=u$($.payload?.snapshot);if(J?.usage)return{...J.usage};let W=$.payload?.session;return W?.usage?{...W.usage}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:typeof $==="string"?$:void 0},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $=await this.client.command("session.get",void 0,f);return BT($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((H)=>{let Q=u$(H);return Q?[DJ(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(RP)}async listSettings(f){let $=await this.client.command("settings.list",XP(f));if(!$.ok)throw Error(EH($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",XP(f));if(!$.ok)throw Error(EH($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(EH(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return Vf(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:YT(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f);return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f);return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=u$(f.payload?.snapshot),W=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",W=f.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=u$(f.payload?.snapshot),W=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:$,reason:J,ts:f.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof f.payload?.requestId==="string"?f.payload.requestId:"",H=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get($)?.get(H);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${H} in session ${$}.`},$).catch(()=>{});return}let Z=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(W,j);let P=(X)=>{this.client.command("capability.progress",{requestId:W,payload:X},$)};try{let X=await Q({payload:Z,abortSignal:j.signal,progress:P});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:X},$)}catch(X){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:X instanceof Error?X.message:String(X)},$)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(jT(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",H=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",Q=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!W||!H||!Q)return;let Z=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},j=PT(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(H),this.emitToolCallContentStart({sessionId:$,toolCallId:H,toolName:Q,toolInput:j});let P=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:H,toolName:Q,input:j,policy:Z})).catch((X)=>({approved:!1,reason:X instanceof Error?X.message:`Tool approval request failed: ${String(X)}`}));await this.client.command("approval.respond",{approvalId:W,approved:P.approved,reason:P.reason},$).catch(()=>{})}}var yP={};N(yP,{RemoteRuntimeHost:()=>r1});class r1 extends _0{constructor(f){super({url:H$(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}var KP={};N(KP,{SqliteSessionStore:()=>W0});import{existsSync as AT,mkdirSync as RT}from"node:fs";import{join as FT}from"node:path";import{asBool as J4,asOptionalString as J0,asString as L0,ensureSessionSchema as yT,loadSqliteDb as KT,nowIso as MJ,toBoolInt as W4}from"@cline/shared/db";import{resolveDbDataDir as UT}from"@cline/shared/storage";class W0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??UT()}init(){this.getRawDb()}ensureSessionsDir(){if(!AT(this.sessionsDirPath))RT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return FT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=KT(this.sessionDbPath());return yT(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=MJ();this.run(`INSERT OR REPLACE INTO sessions (
475
+ session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
476
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
477
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
478
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
479
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,0,W4(f.interactive),f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,W4(f.enableTools),W4(f.enableSpawn),W4(f.enableTeams),f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,W4(f.isSubagent),f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"",f.hookPath??"",f.messagesPath??null,$])}update(f){let $=[],J=[];if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(f.metadata?JSON.stringify(f.metadata):null);if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId);if($.length===0)return;$.push("updated_at = ?"),J.push(MJ()),J.push(f.sessionId),this.run(`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`,J)}updateStatus(f,$,J){this.update({sessionId:f,status:$,endedAt:$==="running"?null:MJ(),exitCode:$==="running"?null:J??($==="failed"?1:0)})}get(f){let $=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
480
+ provider, model, cwd, workspace_root, team_name,
481
+ enable_tools, enable_spawn, enable_teams,
482
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
483
+ prompt, metadata_json, hook_path, messages_path, updated_at
484
+ FROM sessions WHERE session_id = ?`,[f]);if(!$)return;return{sessionId:L0($.session_id),source:L0($.source),pid:Number($.pid??0),startedAt:L0($.started_at),endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:L0($.status),interactive:J4($.interactive),provider:L0($.provider),model:L0($.model),cwd:L0($.cwd),workspaceRoot:L0($.workspace_root),teamName:J0($.team_name),enableTools:J4($.enable_tools),enableSpawn:J4($.enable_spawn),enableTeams:J4($.enable_teams),parentSessionId:J0($.parent_session_id),parentAgentId:J0($.parent_agent_id),agentId:J0($.agent_id),conversationId:J0($.conversation_id),isSubagent:J4($.is_subagent),prompt:J0($.prompt),metadata:(()=>{let J=J0($.metadata_json);if(!J)return;try{let W=JSON.parse(J);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:J0($.hook_path),messagesPath:J0($.messages_path),updatedAt:J0($.updated_at)??MJ()}}list(f=200){let $=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[f]),J=[];for(let W of $){let H=this.get(L0(W.session_id));if(H)J.push(H)}return J}delete(f,$=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}}_J();import{existsSync as lH,mkdirSync as aT,readFileSync as NP,renameSync as tT,writeFileSync as sT}from"node:fs";import{join as qP}from"node:path";import{resolveSessionDataDir as oT}from"@cline/shared/storage";import{dirname as iT}from"node:path";import{nanoid as nT}from"nanoid";import{appendFileSync as wT,existsSync as CT,mkdirSync as UP,readFileSync as ET,writeFileSync as GP}from"node:fs";import{dirname as TP,join as ST}from"node:path";import{ensureHookLogDir as kT}from"@cline/shared/storage";class SH{adapter;messagesArtifactUploader;artifacts;constructor(f,$){this.adapter=f;this.messagesArtifactUploader=$;this.artifacts=new q5(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile(f,$,J){e7($,J,lW(f))}writeSessionManifest(f,$){UP(TP(f),{recursive:!0}),GP(f,`${JSON.stringify(Uf.parse($),null,2)}
485
+ `,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!CT($))return{path:$};try{return{path:$,manifest:Uf.parse(JSON.parse(ET($,"utf8")))}}catch{return{path:$}}}async resolveArtifactPath(f,$,J){let H=(await this.adapter.getSession(f))?.[$];return typeof H==="string"&&H.trim().length>0?H:J(f)}async persistSessionMessages(f,$,J){let W=await this.resolveArtifactPath(f,"messagesPath",(Z)=>this.artifacts.sessionMessagesPath(Z)),H=pW({updatedAt:s(),context:lW(f),messages:$,systemPrompt:J}),Q=`${JSON.stringify(H,null,2)}
486
+ `;if(UP(TP(W),{recursive:!0}),GP(W,Q,"utf8"),!this.messagesArtifactUploader)return;try{let Z=await this.adapter.getSession(f);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:f,path:W,contents:Q,row:Z})}catch(Z){console.warn(`Failed to upload persisted session messages for ${f}`,Z)}}appendStaleSessionHookLog(f,$,J,W,H){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??ST(kT(),"hooks.jsonl");wT(Z,`${JSON.stringify({ts:f,hookName:"session_shutdown",reason:W,sessionId:$,pid:J,source:H})}
487
+ `,"utf8")}}import{appendFileSync as mT}from"node:fs";import{join as IT}from"node:path";import{resolveRootSessionId as hP}from"@cline/shared";import{ensureHookLogDir as xT}from"@cline/shared/storage";import{z as kH}from"zod";var gT="subagent",vT=kH.looseObject({task:kH.string().optional(),systemPrompt:kH.string().optional()});class LJ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor(f,$,J,W){this.adapter=f;this.manifestStore=$;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=W}teamTaskQueueKey(f,$){return`${f}::${$}`}activeTeamTaskSessionId(f,$){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey(f,$))?.at(-1)}buildSubsessionRow(f,$){return{sessionId:$.sessionId,source:gT,pid:process.ppid,startedAt:$.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:$.parentSessionId,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId??null,isSubagent:!0,prompt:$.prompt,metadata:l2({prompt:$.prompt}),hookPath:"",messagesPath:$.messagesPath,updatedAt:$.startedAt}}async queueSpawnRequest(f){if(f.hookName!=="tool_call"||f.parent_agent_id!==null)return;if(f.tool_call?.name!=="spawn_agent")return;let $=hP(f.sessionContext);if(!$)return;let J=vT.safeParse(f.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:$,parentAgentId:f.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession(f){let $=f.rootSessionId;if(!$)return;let J=await this.adapter.getSession($);if(!J)return;let W=A1($,f.agentId),H=await this.adapter.getSession(W),Q=s(),Z=this.manifestStore.artifacts.subagentArtifactPaths(W,f.agentId,this.activeTeamTaskSessionId($,f.parentAgentId)),j=f.prompt??H?.prompt??void 0;if(!j)j=await this.adapter.claimSpawnRequest($,f.parentAgentId)??`Subagent run by ${f.parentAgentId}`;if(!H)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:W,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:j,startedAt:Q,...Z})),this.manifestStore.initializeMessagesFile(W,Z.messagesPath,Q),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:H.prompt??j??null,metadata:l2({metadata:H.metadata??void 0,prompt:H.prompt??j??null}),expectedStatusLock:H.statusLock}),W}async upsertSubagentSessionFromHook(f){if(!f.parent_agent_id)return;let $=hP(f.sessionContext);if(!$)return;if(f.hookName==="session_shutdown"){let J=A1($,f.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:f.agent_id,parentAgentId:f.parent_agent_id,conversationId:f.taskId,rootSessionId:$})}async applySubagentStatus(f,$){await this.applySubagentStatusBySessionId(f,c2($))}async applySubagentStatusBySessionId(f,$){let J=await this.adapter.getSession(f);if(!J)return;let W=$==="running"?null:s(),H=$==="running"?null:$==="failed"?1:0;await this.adapter.updateSession({sessionId:f,status:$,endedAt:W,exitCode:H,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions(f,$){if(!f)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:f,status:"running"});for(let W of J)await this.applySubagentStatusBySessionId(W.sessionId,$)}async onTeamTaskStart(f,$,J){let W=await this.adapter.getSession(f);if(!W)return;let H=v2(f,$),Q=s(),{messagesPath:Z}=this.manifestStore.artifacts.subagentArtifactPaths(H,$);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:H,parentSessionId:f,parentAgentId:"lead",agentId:$,prompt:J||`Team task for ${$}`,startedAt:Q,messagesPath:Z})),this.manifestStore.initializeMessagesFile(H,Z,Q);let j=this.teamTaskQueueKey(f,$),P=this.teamTaskSessionsByAgent.get(j)??[];P.push(H),this.teamTaskSessionsByAgent.set(j,P)}async onTeamTaskEnd(f,$,J,W,H,Q){let Z=this.teamTaskQueueKey(f,$),j=this.teamTaskSessionsByAgent.get(Z);if(!j||j.length===0)return;let P=j.shift();if(j.length===0)this.teamTaskSessionsByAgent.delete(Z);if(!P)return;let X=H?.messages??Q,V=this.toPersistedMessages(X,H,Q);if(V)await this.manifestStore.persistSessionMessages(P,V);await this.applySubagentStatusBySessionId(P,J),this.teamTaskLastHeartbeatBySession.delete(P),this.teamTaskLastProgressLineBySession.delete(P)}async onTeamTaskProgress(f,$,J,W){let H=this.teamTaskQueueKey(f,$),Q=this.teamTaskSessionsByAgent.get(H)?.[0];if(!Q)return;let Z=J.trim();if(!Z)return;let j=W?.kind??"progress";if(j==="heartbeat"){let X=Date.now(),V=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(X-V<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,X)}let P=j==="heartbeat"?"[progress] heartbeat":j==="text"?`[progress] text: ${Z}`:`[progress] ${Z}`;if(this.teamTaskLastProgressLineBySession.get(Q)===P)return;this.teamTaskLastProgressLineBySession.set(Q,P)}async handleSubAgentStart(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;if($.error){await this.applySubagentStatusBySessionId(J,"failed");return}let W=$.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,W==="aborted"?"cancelled":"completed")}appendSubagentHookAudit(f){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??IT(xT(),"hooks.jsonl");mT(J,`${JSON.stringify({ts:s(),...f})}
488
+ `,"utf8")}}import{formatUserInputBlock as pT}from"@cline/shared";var OP={};N(OP,{toTeamProgressLifecycleEvent:()=>p1,sanitizeTeamName:()=>I4,reviveTeamStateDates:()=>m4,createWorkerReviewerTeam:()=>zP,createSpawnAgentTool:()=>I0,createDelegatedAgentConfigProvider:()=>X1,createDelegatedAgent:()=>V1,createAgentTeamsTools:()=>U$,createAgentTeam:()=>IH,buildTeamProgressSummary:()=>l1,buildDelegatedAgentConfig:()=>y$,bootstrapAgentTeams:()=>B1,AgentTeamsRuntime:()=>d$,AgentTeam:()=>n1});function H0(){return new Date().toISOString()}function DP(f,$){if($<=0)return 0;return Math.round(f/$*100)}function uT(f,$){let J=new Set;for(let H of $)if(H.status==="reviewed")J.add(`${H.outcomeId}:${H.section}`);let W=new Set;for(let H of f){if(H.status==="finalized")continue;for(let Q of H.requiredSections)if(!J.has(`${H.id}:${Q}`))W.add(`${H.id}:${Q}`)}return[...W].sort((H,Q)=>H.localeCompare(Q))}function l1(f,$){let J={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},H={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},Z={draft:0,reviewed:0,rejected:0},j=0,P=0;for(let y of $.members)if(J[y.status]+=1,y.role==="lead")j+=1;else P+=1;let X=[],V=[],Y=$.tasks.filter((y)=>y.status==="completed").length,B=new Map($.tasks.map((y)=>[y.id,y]));for(let y of $.tasks){if(W[y.status]+=1,y.status==="blocked"){X.push(y.id);continue}if(y.status!=="pending")continue;if(y.dependsOn.every((K)=>{return B.get(K)?.status==="completed"}))V.push(y.id)}let A=[],R,U=0;for(let y of $.runs){if(H[y.status]+=1,y.status==="queued"||y.status==="running")A.push(y.id);let F=y.startedAt.getTime();if(F>=U)U=F,R=y.id}for(let y of $.outcomes)Q[y.status]+=1;for(let y of $.outcomeFragments)Z[y.status]+=1;return{teamName:f,updatedAt:H0(),members:{total:$.members.length,byStatus:J,leadCount:j,teammateCount:P},tasks:{total:$.tasks.length,byStatus:W,blockedTaskIds:X,readyTaskIds:V,completionPct:DP(Y,$.tasks.length)},runs:{total:$.runs.length,byStatus:H,activeRunIds:A,latestRunId:R},outcomes:{total:$.outcomes.length,byStatus:Q,finalizedPct:DP(Q.finalized,$.outcomes.length),missingRequiredSections:uT($.outcomes,$.outcomeFragments)},fragments:{total:$.outcomeFragments.length,byStatus:Z}}}function p1(f){let{event:$}=f;switch($.type){case"team_task_updated":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0(),taskId:$.task.id,agentId:$.task.assignee??$.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.run.error};case"run_progress":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.message};case"outcome_created":case"outcome_finalized":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0(),outcomeId:$.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0(),outcomeId:$.fragment.outcomeId,fragmentId:$.fragment.id,agentId:$.fragment.sourceAgentId};case"team_message":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0(),taskId:$.message.taskId,agentId:$.message.fromAgentId,message:$.message.subject};case"team_mission_log":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0(),taskId:$.entry.taskId,agentId:$.entry.agentId,message:$.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0(),agentId:$.agentId}}return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:H0()}}import{sanitizeFileName as cT,TeamMessageType as w}from"@cline/shared";import{nanoid as dT}from"nanoid";import{TeamMessageType as gE}from"@cline/shared";function mH(f){if(typeof DOMException<"u"&&f instanceof DOMException&&f.name==="AbortError")return!0;if(!(f instanceof Error))return!1;return f.name==="AbortError"||f.message.toLowerCase().includes("aborted")}function MP(f,$){return f?.status==="stopped"&&mH($)}var rT=600000,_P="recovered_queued";function lT(f){return`This is an automatic recovery of interrupted team run ${f.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
489
+
490
+ ${f.message}`}class n1{agents=new Map;configs=new Map;onTeamEvent;constructor(f,$){if(this.onTeamEvent=$,f)for(let[J,W]of Object.entries(f))this.addAgent(J,W)}addAgent(f,$){if(this.agents.has(f))throw Error(`Agent with id "${f}" already exists in the team`);let J={...$,onEvent:(H)=>{$.onEvent?.(H),this.emitEvent({type:w.AgentEvent,agentId:f,event:H})}},W=new m0(J);if(J.onEvent)W.subscribeEvents(J.onEvent);this.agents.set(f,W),this.configs.set(f,$)}removeAgent(f){return this.configs.delete(f),this.agents.delete(f)}getAgent(f){return this.agents.get(f)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:w.TaskStart,agentId:f,message:$});try{let W=await J.run($);return this.emitEvent({type:w.TaskEnd,agentId:f,result:W}),W}catch(W){let H=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:w.TaskEnd,agentId:f,error:H,messages:J.getMessages()}),W}}async continueTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:w.TaskStart,agentId:f,message:$});try{let W=await J.continue($);return this.emitEvent({type:w.TaskEnd,agentId:f,result:W}),W}catch(W){let H=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:w.TaskEnd,agentId:f,error:H,messages:J.getMessages()}),W}}async runParallel(f){let $=f.map(async(J)=>{let W=this.agents.get(J.agentId);if(!W)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:w.TaskStart,agentId:J.agentId,message:J.message});try{let H=await W.run(J.message);return this.emitEvent({type:w.TaskEnd,agentId:J.agentId,result:H}),{agentId:J.agentId,result:H,metadata:J.metadata}}catch(H){let Q=H instanceof Error?H:Error(String(H));return this.emitEvent({type:w.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),{agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata}}});return Promise.all($)}async runSequential(f){let $=[];for(let J of f){let W=this.agents.get(J.agentId);if(!W){$.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:w.TaskStart,agentId:J.agentId,message:J.message});try{let H=await W.run(J.message);this.emitEvent({type:w.TaskEnd,agentId:J.agentId,result:H}),$.push({agentId:J.agentId,result:H,metadata:J.metadata})}catch(H){let Q=H instanceof Error?H:Error(String(H));this.emitEvent({type:w.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),$.push({agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata})}}return $}async runPipeline(f,$,J){let W=[],H=$;for(let Q of f){let Z=this.agents.get(Q);if(!Z){W.push({agentId:Q,result:void 0,error:Error(`Agent "${Q}" not found in team`)});break}this.emitEvent({type:w.TaskStart,agentId:Q,message:H});try{let j=await Z.run(H);this.emitEvent({type:w.TaskEnd,agentId:Q,result:j}),W.push({agentId:Q,result:j});let P=f.indexOf(Q)+1;if(P<f.length){let X=f[P];H=J?J(j,X):`Previous agent output:
491
+ ${j.text}
492
+
493
+ Please continue from here.`}}catch(j){let P=j instanceof Error?j:Error(String(j));this.emitEvent({type:w.TaskEnd,agentId:Q,error:P,messages:Z.getMessages()}),W.push({agentId:Q,result:void 0,error:P});break}}return W}abortAll(){for(let f of this.agents.values())f.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function IH(f,$){return new n1(f,$)}function zP(f){let $=IH({worker:f.worker,reviewer:f.reviewer}),J=$;return J.doAndReview=async(W)=>{let H=await $.routeTo("worker",W),Q=await $.routeTo("reviewer",`Please review this work:
494
+
495
+ ${H.text}`);return{workerResult:H,reviewResult:Q}},J}class d${teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor(f){this.teamName=f.teamName,this.teamId=`t_${cT(dT(10))}`,this.onTeamEvent=f.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,f.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,f.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,f.maxConcurrentRuns??2);let $=f.leadAgentId??"lead";this.members.set($,{agentId:$,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole(f){return this.members.get(f)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter((f)=>f.role==="teammate").map((f)=>f.agentId)}getTask(f){return this.tasks.get(f)}listTasks(){return Array.from(this.tasks.values())}listTaskItems(f){return Array.from(this.tasks.values()).map(($)=>{let J=this.getUnresolvedDependencies($);return{...$,blockedBy:J,isReady:$.status==="pending"&&!$.assignee&&J.length===0}}).filter(($)=>{if(f?.status&&$.status!==f.status)return!1;if(f?.assignee&&$.assignee!==f.assignee)return!1;return!0})}listMissionLog(f){if(!f||f<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-f))}listMailbox(f,$){let J=$?.unreadOnly??!0,W=$?.markRead??!0,H=$?.limit,Q=this.mailbox.filter((j)=>j.toAgentId===f&&(!J||!j.readAt)),Z=typeof H==="number"&&H>0?Q.slice(Math.max(0,Q.length-H)):Q;if(W){let j=new Date;for(let P of Z)if(!P.readAt)P.readAt=j}return Z.map((j)=>({...j}))}getSnapshot(){let f={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())f[J.status]++;let $={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())$[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:f,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:$}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((f)=>({agentId:f.agentId,role:f.role,description:f.description,status:f.status})),tasks:Array.from(this.tasks.values()).map((f)=>({...f})),mailbox:this.mailbox.map((f)=>({...f})),missionLog:this.missionLog.map((f)=>({...f})),runs:Array.from(this.runs.values()).map((f)=>({...f})),outcomes:Array.from(this.outcomes.values()).map((f)=>({...f})),outcomeFragments:Array.from(this.outcomeFragments.values()).map((f)=>({...f}))}}hydrateState(f){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of f.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...f.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...f.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of f.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of f.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of f.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let $=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of $)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of f.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,i1(f.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,i1(f.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,i1(f.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,i1((f.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,i1((f.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,i1((f.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive(f){let $=this.members.get(f);return!!$&&$.role==="teammate"&&!!$.agent}spawnTeammate({agentId:f,config:$}){let J=this.members.get(f);if(J&&J.role!=="teammate")throw Error(`Team member "${f}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${f}" is currently running and cannot be respawned`);let W={...$,apiTimeoutMs:rT,consumePendingUserMessage:()=>{let Z=this.members.get(f);if(!Z||!Z.pendingSteerMessage)return;let j=Z.pendingSteerMessage;return Z.pendingSteerMessage=void 0,j},onEvent:(Z)=>{$.onEvent?.(Z),this.emitEvent({type:w.AgentEvent,agentId:f,event:Z}),this.trackMeaningfulEvent(f,Z)}},H=new m0(W);if(W.onEvent)H.subscribeEvents(W.onEvent);let Q={agentId:f,role:"teammate",description:$.role,status:"idle",agent:H,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set(f,Q),this.emitEvent({type:w.TeammateSpawned,agentId:f,role:$.role,teammate:{rolePrompt:$.systemPrompt,modelId:$.modelId,maxIterations:$.maxIterations,runtimeAgentId:H.getAgentId(),conversationId:H.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate(f,$){let J=this.members.get(f);if(!J||J.role!=="teammate")throw Error(`Teammate "${f}" was not found`);try{J.agent?.abort()}catch(W){if(!mH(W))throw W}J.status="stopped",this.emitEvent({type:w.TeammateShutdown,agentId:f,reason:$})}updateTeammateConnections(f){for(let $ of this.members.values()){if($.role!=="teammate"||!$.agent)continue;$.agent.updateConnection(f)}}createTask(f){let $=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,W={id:$,title:f.title,description:f.description,status:f.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:f.createdBy,assignee:f.assignee,dependsOn:f.dependsOn??[]};return this.tasks.set($,W),this.emitEvent({type:w.TeamTaskUpdated,task:{...W}}),{...W}}claimTask(f,$){let J=this.requireTask(f);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=$,J.updatedAt=new Date,this.emitEvent({type:w.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:$,taskId:f,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask(f,$,J){let W=this.requireTask(f);return W.status="blocked",W.updatedAt=new Date,W.summary=J,this.emitEvent({type:w.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:$,taskId:f,kind:"blocked",summary:J}),{...W}}completeTask(f,$,J){let W=this.requireTask(f);if(W.status="completed",W.updatedAt=new Date,W.summary=J,!W.assignee)W.assignee=$;return this.emitEvent({type:w.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:$,taskId:f,kind:"done",summary:J}),{...W}}async routeToTeammate(f,$,J){let W=this.members.get(f);if(!W||W.role!=="teammate"||!W.agent)throw Error(`Teammate "${f}" was not found`);if(!W.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");W.runningCount++,W.status="running",this.emitEvent({type:w.TaskStart,agentId:f,message:$});try{let H=this.listMailbox(f,{unreadOnly:!0,markRead:!0}),Q=H.length>0?`${this.buildMailboxNotification(H)}
496
+
497
+ ${$}`:$,Z=J?.continueConversation?await W.agent.continue(Q):await W.agent.run(Q);return this.emitEvent({type:w.TaskEnd,agentId:f,result:Z}),this.recordProgressStep(f,`Completed a delegated run (${Z.iterations} iterations)`,J?.taskId,!0),Z}catch(H){let Q=H instanceof Error?H:Error(String(H));if(this.emitEvent({type:w.TaskEnd,agentId:f,error:Q,messages:W.agent.getMessages()}),!MP(W,Q))this.appendMissionLog({agentId:f,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get(f)?.status!=="stopped")W.status="idle"}}startTeammateRun(f,$,J){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,H={id:W,agentId:f,taskId:J?.taskId,status:"queued",message:$,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,H),this.runQueue.push(W),this.emitEvent({type:w.RunQueued,run:{...H}}),this.dispatchQueuedRuns(),{...H}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let f;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let $=this.selectNextDispatchableQueuedRun();f=$.nextDelayedAttemptAt;let J=$.index;if(J<0){this.scheduleQueuedRunDispatch(f);return}let[W]=this.runQueue.splice(J,1),H=W?this.runs.get(W):void 0;if(!H||H.status!=="queued")continue;this.executeQueuedRun(H)}this.scheduleQueuedRunDispatch(f)}selectNextDispatchableQueuedRun(){let f=-1,$=Number.NEGATIVE_INFINITY,J,W=Date.now();for(let H=0;H<this.runQueue.length;H++){let Q=this.runs.get(this.runQueue[H]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>W){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>$)$=Q.priority,f=H}return{index:f,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch(f){if(!f)return;let $=Math.max(0,f.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},$)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let f=0;for(let $ of this.runs.values())if($.status==="running")f++;return f}async executeQueuedRun(f){let $=f.currentActivity===_P;f.nextAttemptAt=void 0,f.status="running",f.startedAt=new Date,f.heartbeatAt=new Date,f.currentActivity="run_started",this.emitEvent({type:w.RunStarted,run:{...f}});let J=setInterval(()=>{if(f.status!=="running")return;this.recordRunProgress(f,"heartbeat")},2000);try{let W=$?lT(f):f.message,H=await this.routeToTeammate(f.agentId,W,{taskId:f.taskId,continueConversation:f.continueConversation});f.status="completed",f.result=H,f.endedAt=new Date,f.currentActivity="completed",this.emitEvent({type:w.RunCompleted,run:{...f}})}catch(W){let H=W instanceof Error?W.message:String(W??"Unknown error");f.error=H,f.endedAt=new Date;let Q=this.members.get(f.agentId);if(MP(Q,W))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:w.RunCancelled,run:{...f},reason:H});else if(f.retryCount<f.maxRetries)f.retryCount++,f.status="queued",f.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**f.retryCount)),this.runQueue.push(f.id),this.recordRunProgress(f,`retry_scheduled_${f.retryCount}`);else f.status="failed",f.currentActivity="failed",this.emitEvent({type:w.RunFailed,run:{...f}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns(f){let $=f?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!$&&!["running","queued"].includes(J.status))return!1;if(f?.status&&J.status!==f.status)return!1;if(f?.agentId&&J.agentId!==f.agentId)return!1;return!0}).map((J)=>({...J}))}getRun(f){let $=this.runs.get(f);return $?{...$}:void 0}async awaitRun(f,$=250){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);while(J.status==="queued"||J.status==="running")await LP($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await LP(f);return this.listRuns()}cancelRun(f,$){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=$,J.endedAt=new Date,J.currentActivity="cancelled";let W=this.runQueue.indexOf(f);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:w.RunCancelled,run:{...J},reason:$}),{...J}}recoverActiveRuns(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let W=this.members.get(J.agentId);if(!W||W.role!=="teammate"||!W.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:w.RunInterrupted,run:{...J},reason:J.error});continue}let H=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=H,J.lastProgressAt=H,J.lastProgressMessage=f,J.currentActivity=_P,!this.runQueue.includes(J.id))this.runQueue.push(J.id);$.push({...J}),this.emitEvent({type:w.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),$}markStaleRunsInterrupted(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=f,J.endedAt=new Date,J.currentActivity="interrupted",$.push({...J}),this.emitEvent({type:w.RunInterrupted,run:{...J},reason:f})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),$}sendMessage(f,$,J,W,H){if(!this.members.has(f))throw Error(`Unknown sender "${f}"`);let Q=this.members.get($);if(!Q)throw Error(`Unknown recipient "${$}"`);let Z={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:f,toAgentId:$,subject:J,body:W,taskId:H,sentAt:new Date};if(this.mailbox.push(Z),this.emitEvent({type:w.TeamMessage,message:{...Z}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${f}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...Z}}broadcast(f,$,J,W){let H=[];for(let Q of this.members.values()){if(Q.agentId===f)continue;if(Q.role==="lead")continue;H.push(this.sendMessage(f,Q.agentId,$,J,W?.taskId))}return H}appendMissionLog(f){if(!this.members.has(f.agentId))throw Error(`Unknown team member "${f.agentId}"`);let $={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:f.agentId,taskId:f.taskId,kind:f.kind,summary:f.summary,evidence:f.evidence,nextAction:f.nextAction};this.missionLog.push($);let J=this.members.get(f.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:w.TeamMissionLog,entry:{...$}}),{...$}}createOutcome(f){let $={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:f.title,status:"draft",requiredSections:[...new Set(f.requiredSections)],createdBy:f.createdBy,createdAt:new Date};return this.outcomes.set($.id,$),this.emitEvent({type:w.OutcomeCreated,outcome:{...$}}),{...$}}listOutcomes(){return Array.from(this.outcomes.values()).map((f)=>({...f}))}attachOutcomeFragment(f){let $=this.outcomes.get(f.outcomeId);if(!$)throw Error(`Outcome "${f.outcomeId}" was not found`);if(!$.requiredSections.includes(f.section))throw Error(`Section "${f.section}" is not part of outcome "${f.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:f.outcomeId,section:f.section,sourceAgentId:f.sourceAgentId,sourceRunId:f.sourceRunId,content:f.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),$.status==="draft")$.status="in_review";return this.emitEvent({type:w.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment(f){let $=this.outcomeFragments.get(f.fragmentId);if(!$)throw Error(`Fragment "${f.fragmentId}" was not found`);return $.status=f.approved?"reviewed":"rejected",$.reviewedBy=f.reviewedBy,$.reviewedAt=new Date,this.emitEvent({type:w.OutcomeFragmentReviewed,fragment:{...$}}),{...$}}listOutcomeFragments(f){return Array.from(this.outcomeFragments.values()).filter(($)=>$.outcomeId===f).map(($)=>({...$}))}finalizeOutcome(f){let $=this.outcomes.get(f);if(!$)throw Error(`Outcome "${f}" was not found`);let J=this.listOutcomeFragments(f);for(let W of $.requiredSections)if(!J.some((Q)=>Q.section===W&&Q.status==="reviewed"))throw Error(`Outcome "${f}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return $.status="finalized",$.finalizedAt=new Date,this.emitEvent({type:w.OutcomeFinalized,outcome:{...$}}),{...$}}cleanup(){for(let f of this.members.values())if(f.role==="teammate"&&f.runningCount>0)throw Error(`Cannot cleanup team while teammate "${f.agentId}" is still running`);if(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let f of this.members.values())if(f.role==="teammate")try{f.agent?.abort()}catch($){if(!mH($))throw $}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[f,$]of this.members.entries())if($.role==="teammate")this.members.delete(f)}requireTask(f){let $=this.tasks.get(f);if(!$)throw Error(`Task "${f}" was not found`);return $}assertDependenciesResolved(f){let $=this.getUnresolvedDependencies(f);if($.length>0)throw Error(`Task "${f.id}" is blocked by "${$[0]}"`)}getUnresolvedDependencies(f){return f.dependsOn.filter(($)=>{let J=this.tasks.get($);return!J||J.status!=="completed"})}trackMeaningfulEvent(f,$){if(this.recordRunActivityFromAgentEvent(f,$),$.type==="iteration_end"&&$.hadToolCalls){this.recordProgressStep(f,`Completed iteration ${$.iteration} with ${$.toolCallCount} tool call(s)`);return}if($.type==="content_end"&&$.contentType==="tool"&&!$.error){this.recordProgressStep(f,`Finished tool "${$.toolName??"unknown"}"`);return}if($.type==="done"){this.appendMissionLog({agentId:f,kind:"done",summary:`Completed a delegated run (${$.iterations} iterations)`});return}if($.type==="error")this.appendMissionLog({agentId:f,kind:"error",summary:$.error.message})}recordRunActivityFromAgentEvent(f,$){let J;switch($.type){case"iteration_start":J=`iteration_${$.iteration}_started`;break;case"content_start":if($.contentType==="tool")J=`running_tool_${$.toolName??"unknown"}`;break;case"content_end":if($.contentType==="tool")J=$.error?this.formatProgressErrorActivity(`tool_${$.toolName??"unknown"}_error`,$.error):`finished_tool_${$.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",$.error.message);break;default:break}if(!J)return;for(let W of this.runs.values()){if(W.agentId!==f||W.status!=="running")continue;this.recordRunProgress(W,J)}}recordRunProgress(f,$){let J=new Date;f.heartbeatAt=J,f.lastProgressAt=J,f.lastProgressMessage=$,f.currentActivity=$,this.emitEvent({type:w.RunProgress,run:{...f},message:$})}formatProgressErrorActivity(f,$){let J=$.replace(/\s+/g," ").trim();if(J.length===0)return f;let W=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${f}: ${W}`}recordProgressStep(f,$,J,W=!1){this.missionStepCounter++;let H=this.members.get(f);if(!H)return;let Q=this.missionStepCounter-H.lastMissionStep,Z=Date.now()-H.lastMissionAt;if(!W&&Q<this.missionLogIntervalSteps&&Z<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:f,taskId:J,kind:"progress",summary:$})}buildMailboxNotification(f){if(f.length===0)return"";let $=[`[MAILBOX] You have ${f.length} unread message(s):`];for(let J of f)$.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),$.push(J.body);return $.push("---"),$.join(`
498
+ `)}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function LP(f){return new Promise(($)=>setTimeout($,f))}function i1(f,$){let J=0;for(let W of f){if(!W.startsWith($))continue;let H=Number.parseInt(W.slice($.length),10);if(Number.isFinite(H))J=Math.max(J,H)}return J}function xH(f,$){switch($.type){case"run_queued":case"run_started":f.activeTeamRunIds.add($.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if($.type==="run_failed")J=$.run.error;else if($.type==="run_cancelled"||$.type==="run_interrupted")J=$.run.error??$.reason;f.activeTeamRunIds.delete($.run.id),f.pendingTeamRunUpdates.push({runId:$.run.id,agentId:$.run.agentId,taskId:$.run.taskId,status:$.type.replace("run_",""),error:J,iterations:$.run.result?.iterations}),zJ(f);break}default:break}}async function gH(f,$,J){switch($.type){case"run_progress":await J("onTeamTaskProgress",f,$.run.agentId,$.message,{kind:$.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if($.event.type==="content_start"&&$.event.contentType==="text"&&typeof $.event.text==="string"){let W=$.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await J("onTeamTaskProgress",f,$.agentId,W,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",f,$.agentId,$.message);break;case"task_end":{if($.error)await J("onTeamTaskEnd",f,$.agentId,"failed",`[error] ${$.error.message}`,void 0,$.messages);else if($.result?.finishReason==="aborted")await J("onTeamTaskEnd",f,$.agentId,"cancelled","[done] aborted",$.result,$.result.messages);else await J("onTeamTaskEnd",f,$.agentId,"completed",`[done] ${$.result?.finishReason??"completed"}`,$.result,$.result?.messages);break}default:break}}function vH(f,$,J,W){if(!f.runtime.teamRuntime)return;let H=f.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:$,teamName:H,lifecycle:p1({teamName:H,sessionId:$,event:J}),summary:l1(H,f.runtime.teamRuntime.exportState())}})}function H4(f){return f.activeTeamRunIds.size>0||f.pendingTeamRunUpdates.length>0}function uH(f,$){if(f.aborting)return!1;if(!($==="completed"||$==="max_iterations"))return!1;return f.config.enableAgentTeams===!0&&H4(f)}function zJ(f){let $=f.teamRunWaiters.splice(0);for(let J of $)J()}async function cH(f){while(!0){if(f.aborting)return[];if(f.pendingTeamRunUpdates.length>0){let $=[...f.pendingTeamRunUpdates];return f.pendingTeamRunUpdates.length=0,$}if(f.activeTeamRunIds.size===0)return[];await new Promise(($)=>{f.teamRunWaiters.push($)})}}function dH(f,$){let J=$.map((Q)=>{let Z=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)Z.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")Z.push(` iterations=${Q.iterations}`);if(Q.error)Z.push(` error=${Q.error}`);return Z.join("")}),W=f.activeTeamRunIds.size,H=W>0?`There are still ${W} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return Q4(`System-delivered teammate async run updates:
499
+ ${J.join(`
500
+ `)}
501
+
502
+ ${H}`,f.config.mode)}function Q4(f,$){return pT(f,$==="plan"?"plan":$==="yolo"?"yolo":"act")}var rH=4;class z0{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor(f,$={}){this.adapter=f;this.manifestStore=new SH(f,$.messagesArtifactUploader),this.teamChildren=new LJ(f,this.manifestStore,(J,W,H)=>this.toPersistedMessages(J,W,H),z0.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages(f,$,J){if(!f)return;return $?c4($.messages,$,J):u4(f)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest(f,$){this.manifestStore.writeSessionManifest(f,$)}readSessionManifest(f){return this.manifestStore.readSessionManifest(f)}async createRootSessionWithArtifacts(f){let $=f.startedAt??s(),J=f.sessionId.trim(),W=J.length>0?J:`${Date.now()}_${nT(5)}`,H=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),Z=l2({metadata:f.metadata,prompt:f.prompt}),j={version:1,session_id:W,source:f.source,pid:f.pid,started_at:$,status:"running",interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt?.trim()||void 0,metadata:Z,messages_path:H};return await this.adapter.upsertSession({sessionId:W,source:f.source,pid:f.pid,startedAt:$,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:j.prompt??null,metadata:x0(j.metadata),hookPath:"",messagesPath:H,updatedAt:s()}),this.manifestStore.initializeMessagesFile(W,H,$),this.manifestStore.writeSessionManifest(Q,j),{manifestPath:Q,messagesPath:H,manifest:j}}async updateSessionStatus(f,$,J){let W;if((await $Q(()=>this.adapter.getSession(f),async(Q)=>{return W=$==="running"?void 0:s(),this.adapter.updateSession({sessionId:f,status:$,endedAt:W??null,exitCode:$==="running"?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},rH)).updated){if($==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions(f,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession(f){for(let $=0;$<rH;$++){let J=await this.adapter.getSession(f.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,H=f.metadata!==void 0?x0(f.metadata)??{}:x0(W)??{},Q=D$(typeof W?.title==="string"?W.title:void 0),Z=f.title!==void 0?D$(f.title):Q??rW(f.prompt);if(Z)H.title=Z;else delete H.title;let j=f.metadata!==void 0||f.prompt!==void 0||f.title!==void 0;if(!(await this.adapter.updateSession({sessionId:f.sessionId,prompt:f.prompt,metadata:j?Object.keys(H).length>0?H:null:void 0,title:Z,expectedStatusLock:J.statusLock})).updated)continue;let{path:X,manifest:V}=this.manifestStore.readManifestFile(f.sessionId);if(V){if(f.prompt!==void 0)V.prompt=f.prompt??void 0;let Y=f.metadata!==void 0?x0(f.metadata)??{}:x0(V.metadata)??{};if(Z)Y.title=Z;V.metadata=Object.keys(Y).length>0?Y:void 0,this.manifestStore.writeSessionManifest(X,V)}return{updated:!0}}return{updated:!1}}queueSpawnRequest(f){return this.teamChildren.queueSpawnRequest(f)}upsertSubagentSession(f){return this.teamChildren.upsertSubagentSession(f)}upsertSubagentSessionFromHook(f){return this.teamChildren.upsertSubagentSessionFromHook(f)}appendSubagentHookAudit(f,$){return this.teamChildren.appendSubagentHookAudit($),Promise.resolve()}persistSessionMessages(f,$,J){let W=u4($);return this.manifestStore.persistSessionMessages(f,W,J)}applySubagentStatus(f,$){return this.teamChildren.applySubagentStatus(f,$)}applySubagentStatusBySessionId(f,$){return this.teamChildren.applySubagentStatusBySessionId(f,$)}applyStatusToRunningChildSessions(f,$){return this.teamChildren.applyStatusToRunningChildSessions(f,$)}onTeamTaskStart(f,$,J){return this.teamChildren.onTeamTaskStart(f,$,J)}onTeamTaskEnd(f,$,J,W,H,Q){return this.teamChildren.onTeamTaskEnd(f,$,J,W,H,Q)}onTeamTaskProgress(f,$,J,W){return this.teamChildren.onTeamTaskProgress(f,$,J,W)}handleSubAgentStart(f,$){return this.teamChildren.handleSubAgentStart(f,$)}handleSubAgentEnd(f,$){return this.teamChildren.handleSubAgentEnd(f,$)}isPidAlive(f){if(!Number.isFinite(f)||f<=0)return!1;try{return process.kill(Math.floor(f),0),!0}catch($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="EPERM"}}async reconcileDeadRunningSession(f){if(f.status!=="running"||this.isPidAlive(f.pid))return f;let $=s(),J=z0.STALE_REASON;for(let W=0;W<rH;W++){let H=await this.adapter.getSession(f.sessionId);if(!H)return;if(H.status!=="running")return H;let Q={...H.metadata??{},terminal_marker:J,terminal_marker_at:$,terminal_marker_pid:H.pid,terminal_marker_source:z0.STALE_SOURCE},Z=await this.adapter.updateSession({sessionId:H.sessionId,status:"failed",endedAt:$,exitCode:1,metadata:Q,expectedStatusLock:H.statusLock});if(!Z.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(H.sessionId,"failed");let j=fQ(H,{status:"failed",endedAt:$,exitCode:1,metadata:Q}),{path:P}=this.manifestStore.readManifestFile(H.sessionId);return this.manifestStore.writeSessionManifest(P,j),this.manifestStore.appendStaleSessionHookLog($,H.sessionId,H.pid,J,z0.STALE_SOURCE),{...H,status:"failed",endedAt:$,exitCode:1,metadata:Q,statusLock:Z.statusLock,updatedAt:$}}return await this.adapter.getSession(f.sessionId)}async listSessions(f=200){let $=Math.max(1,Math.floor(f)),J=Math.min($*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,$).map((H)=>{let Q=x0(H.metadata??void 0),Z=this.manifestStore.readSessionManifest(H.sessionId),j=D$(typeof Z?.metadata?.title==="string"?Z.metadata.title:void 0),P=j?{...Q??{},title:j}:Q;return{...H,metadata:P}})}async reconcileDeadSessions(f=2000){let $=await this.adapter.listSessions({limit:Math.max(1,Math.floor(f)),status:"running"}),J=0;for(let W of $){let H=await this.reconcileDeadRunningSession(W);if(H&&H.status!==W.status)J++}return J}async deleteSession(f){let $=f.trim();if(!$)throw Error("session id is required");let J=await this.adapter.getSession($);if(!J)return{deleted:!1};if(await this.adapter.deleteSession($,!1),!J.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:$});await this.adapter.deleteSession($,!0),await Promise.allSettled(W.map(async(H)=>{await Z5(H.cwd,H.sessionId),K8(H.messagesPath),K8(this.manifestStore.artifacts.sessionManifestPath(H.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(H.sessionId)}))}if(await Z5(J.cwd,$),K8(J.messagesPath),K8(this.manifestStore.artifacts.sessionManifestPath($,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty($);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir($)]);for(let H of[J.messagesPath])if(typeof H==="string"&&H.trim().length>0)W.add(iT(H));for(let H of W)this.manifestStore.artifacts.removeDir(H)}return{deleted:!0}}}function pH(){return new Date().toISOString()}function bP(f,$){let J=`${f}.tmp`;sT(J,`${JSON.stringify($,null,2)}
503
+ `,"utf8"),tT(J,f)}class wP{sessionsDirPath;constructor(f=oT()){this.sessionsDirPath=f}ensureSessionsDir(){if(!lH(this.sessionsDirPath))aT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return qP(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return qP(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let f=this.indexPath();if(!lH(f))return{version:1,sessions:{}};try{let $=JSON.parse(NP(f,"utf8"));if($?.version===1&&$.sessions)return $}catch{}return{version:1,sessions:{}}}writeIndex(f){bP(this.indexPath(),f)}readQueue(){let f=this.spawnQueuePath();if(!lH(f))return{version:1,nextId:1,requests:[]};try{let $=JSON.parse(NP(f,"utf8"));if($?.version===1&&typeof $.nextId==="number"&&Array.isArray($.requests))return $}catch{}return{version:1,nextId:1,requests:[]}}writeQueue(f){bP(this.spawnQueuePath(),f)}async upsertSession(f){let $=this.readIndex();$.sessions[f.sessionId]=f,this.writeIndex($)}async getSession(f){return this.readIndex().sessions[f]}async listSessions(f){return Object.values(this.readIndex().sessions).filter(($)=>f.parentSessionId!==void 0?$.parentSessionId===f.parentSessionId:!0).filter(($)=>f.status!==void 0?$.status===f.status:!0).sort(($,J)=>J.startedAt.localeCompare($.startedAt)).slice(0,f.limit)}async updateSession(f){let $=this.readIndex(),J=$.sessions[f.sessionId];if(!J)return{updated:!1,statusLock:0};if(f.expectedStatusLock!==void 0&&J.statusLock!==f.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let W=f.expectedStatusLock!==void 0?f.expectedStatusLock+1:J.statusLock,H={...J,status:f.status??J.status,endedAt:f.endedAt!==void 0?f.endedAt:J.endedAt??null,exitCode:f.exitCode!==void 0?f.exitCode:J.exitCode??null,prompt:f.prompt!==void 0?f.prompt:J.prompt??null,metadata:f.metadata!==void 0?f.metadata??null:J.metadata??null,parentSessionId:f.parentSessionId!==void 0?f.parentSessionId??null:J.parentSessionId??null,parentAgentId:f.parentAgentId!==void 0?f.parentAgentId??null:J.parentAgentId??null,agentId:f.agentId!==void 0?f.agentId??null:J.agentId??null,conversationId:f.conversationId!==void 0?f.conversationId??null:J.conversationId??null,statusLock:W,isSubagent:f.setRunning||f.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:pH()};if(f.setRunning)H.status="running",H.endedAt=null,H.exitCode=null;return $.sessions[f.sessionId]=H,this.writeIndex($),{updated:!0,statusLock:H.statusLock}}async deleteSession(f,$){let J=this.readIndex();if(!J.sessions[f])return!1;if(delete J.sessions[f],$){for(let H of Object.values(J.sessions))if(H.parentSessionId===f)delete J.sessions[H.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest(f){let $=this.readQueue();$.requests.push({id:$.nextId,rootSessionId:f.rootSessionId,parentAgentId:f.parentAgentId,task:f.task,systemPrompt:f.systemPrompt,createdAt:pH()}),$.nextId+=1,this.writeQueue($)}async claimSpawnRequest(f,$){let J=this.readQueue(),W=J.requests.find((H)=>H.rootSessionId===f&&H.parentAgentId===$&&!H.consumedAt);if(!W)return;return W.consumedAt=pH(),this.writeQueue(J),W.task}}class iH extends z0{constructor(f,$={}){super(new wP(f),$)}ensureSessionsDir(){return super.ensureSessionsDir()}}var SP={};N(SP,{CoreSessionService:()=>Q0});import{existsSync as eT,mkdirSync as fh}from"node:fs";import{resolveSessionDataDir as $h}from"@cline/shared/storage";var nH=`
504
+ session_id AS sessionId,
505
+ source,
506
+ pid,
507
+ started_at AS startedAt,
508
+ ended_at AS endedAt,
509
+ exit_code AS exitCode,
510
+ status,
511
+ status_lock AS statusLock,
512
+ interactive,
513
+ provider,
514
+ model,
515
+ cwd,
516
+ workspace_root AS workspaceRoot,
517
+ team_name AS teamName,
518
+ enable_tools AS enableTools,
519
+ enable_spawn AS enableSpawn,
520
+ enable_teams AS enableTeams,
521
+ parent_session_id AS parentSessionId,
522
+ parent_agent_id AS parentAgentId,
523
+ agent_id AS agentId,
524
+ conversation_id AS conversationId,
525
+ is_subagent AS isSubagent,
526
+ prompt,
527
+ metadata_json AS metadata,
528
+ hook_path AS hookPath,
529
+ messages_path AS messagesPath,
530
+ updated_at AS updatedAt`;function aH(f){f.interactive=f.interactive===1,f.enableTools=f.enableTools===1,f.enableSpawn=f.enableSpawn===1,f.enableTeams=f.enableTeams===1,f.isSubagent=f.isSubagent===1;let $=f.metadata;if(typeof $==="string"&&$.trim())try{let J=JSON.parse($);f.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{f.metadata=null}else f.metadata=null;return f}function tH(f){if(!f||Object.keys(f).length===0)return null;return JSON.stringify(f)}function CP(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class EP{store;sessionsDirPath;constructor(f,$=$h()){this.store=f;this.sessionsDirPath=$}ensureSessionsDir(){if(!eT(this.sessionsDirPath))fh(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
531
+ session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
532
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
533
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
534
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
535
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,f.statusLock,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.isSubagent?1:0,f.prompt??null,tH(f.metadata),"",f.hookPath??"",f.messagesPath??null,f.updatedAt])}async getSession(f){let $=this.store.queryOne(`SELECT ${nH} FROM sessions WHERE session_id = ?`,[f]);return $?aH($):void 0}async listSessions(f){let $=[],J=[];if(f.parentSessionId)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.status)$.push("status = ?"),J.push(f.status);let W=$.length>0?`WHERE ${$.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${nH}
536
+ FROM sessions
537
+ ${W}
538
+ ORDER BY started_at DESC
539
+ LIMIT ?`,[...J,f.limit]).map(aH)}async updateSession(f){if(f.setRunning){if(f.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
540
+ SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
541
+ parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
542
+ prompt = COALESCE(prompt, ?)
543
+ WHERE session_id = ? AND status_lock = ?`,[s(),f.expectedStatusLock+1,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.prompt??null,f.sessionId,f.expectedStatusLock]).changes??0)>0,statusLock:f.expectedStatusLock+1}}let $=[],J=[];if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt??null);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(tH(f.metadata));if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId??null);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId??null);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId??null);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId??null);if($.length===0){let Z=await this.getSession(f.sessionId);return{updated:!!Z,statusLock:Z?.statusLock??0}}let W=0;if(f.expectedStatusLock!==void 0)W=f.expectedStatusLock+1,$.push("status_lock = ?"),J.push(W);$.push("updated_at = ?"),J.push(s());let H=`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`;if(J.push(f.sessionId),f.expectedStatusLock!==void 0)H+=" AND status_lock = ?",J.push(f.expectedStatusLock);if((this.store.run(H,J).changes??0)===0)return{updated:!1,statusLock:0};if(f.expectedStatusLock===void 0)W=(await this.getSession(f.sessionId))?.statusLock??0;return{updated:!0,statusLock:W}}async deleteSession(f,$){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}async enqueueSpawnRequest(f){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
544
+ VALUES (?, ?, ?, ?, ?, NULL)`,[f.rootSessionId,f.parentAgentId,f.task??null,f.systemPrompt??null,s()])}async claimSpawnRequest(f,$){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
545
+ WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
546
+ ORDER BY id ASC LIMIT 1`,[f,$]);if(!J||typeof J.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[s(),J.id]),J.task??void 0}}class Q0 extends z0{store;constructor(f,$={}){super(new EP(f,$.sessionArtifactsDir),$);this.store=f}createRootSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
547
+ session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
548
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
549
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
550
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
551
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,null,null,"running",0,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,null,null,null,null,0,f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"","",f.messagesPath,s()])}}function Jh(f){if(f.backendMode)return f.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let $=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if($==="local"||$==="hub"||$==="remote")return $;return"auto"}var Z4,j4;function Wh(f,$){if(f!=="auto"&&f!=="hub")return;if($.hub?.endpoint?.trim())return;GJ($.hub?.workspaceRoot?.trim()||$.hub?.cwd?.trim()||process.cwd())}async function Hh(f){await f.reconcileDeadSessions?.().catch(()=>{})}function mP(f){try{let $=new W0;return $.init(),new Q0($,{messagesArtifactUploader:f.messagesArtifactUploader})}catch{return f.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new iH(void 0,{messagesArtifactUploader:f.messagesArtifactUploader})}}function kP(f,$,J){return new Z0({sessionService:J??f.sessionService??mP(f),capabilities:f.capabilities,telemetry:f.telemetry,toolPolicies:f.toolPolicies,distinctId:$,fetch:f.fetch})}async function sH(f){if(Z4)return Z4;if(j4)return await j4;return j4=(async()=>{return Z4=mP(f),await Hh(Z4),Z4})().finally(()=>{j4=void 0}),await j4}async function a1(f){let $=c$(f.distinctId);f.telemetry?.setDistinctId($);let J=Jh(f);if(Wh(J,f),J==="remote"){let W=f.remote?.endpoint?.trim();if(!W)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return f.logger?.log("Using remote runtime host",{endpoint:W}),new r1({endpoint:W,authToken:f.remote?.authToken,clientType:f.remote?.clientType,displayName:f.remote?.displayName,workspaceRoot:f.remote?.workspaceRoot,cwd:f.remote?.cwd,capabilities:f.capabilities})}if(J==="hub"){let W=f.hub?.endpoint?.trim(),H=W||await g$({strategy:f.hub?.strategy??"require-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(!H)throw Error("No compatible hub runtime is available.");return f.logger?.log("Using hub runtime host",{url:H,explicitEndpoint:W||void 0}),new _0({url:H,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd})}if(J==="auto"){let W=await f4({endpoint:f.hub?.endpoint,strategy:f.hub?.strategy??"prefer-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(W){f.logger?.log("Using discovered local hub runtime host",{url:W});let H=new _0({url:W,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});try{return await H.connect(),H}catch(Q){f.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q})}}return f.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),kP(f,$)}return kP(f,$)}class P4{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor(f,$,J,W,H,Q,Z,j,P){this.clientName=$,this.runtimeAddress=J,this.host=f,this.prepare=W,this.capabilities=H,this.logger=Q,this.telemetry=Z,this.distinctId=j,this.settings=Hj(f),this.pendingPrompts=Qj(f),this.automation=new u5(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=P?new n8({workspaceRoot:P.workspaceRoot??process.cwd(),specs:{cronSpecsDir:P.cronSpecsDir??P.cronDir,scope:SZ(P.cronScope),workspaceRoot:P.workspaceRoot},runtimeHandlers:kZ({host:f,getExtensionContext:()=>$J({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:P.dbPath,logger:P.logger,pollIntervalMs:P.pollIntervalMs,claimLeaseSeconds:P.claimLeaseSeconds,globalMaxConcurrency:P.globalMaxConcurrency,watcherDebounceMs:P.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((X)=>{if(X.type!=="ended")return;this.disposeSessionBootstrap(X.payload.sessionId)})}static async create(f={}){let $=Vf(f.capabilities),J=await a1({...f,capabilities:$}),W=EZ(f.automation),H=new P4(J,f.clientName,J.runtimeAddress,f.prepare,$,f.logger,f.telemetry,f.distinctId,W?{...W,logger:f.logger}:void 0);if(W&&W.autoStart!==!1)await H.automation.start();return H}async disposeSessionBootstrap(f){let $=this.activeSessionBootstraps.get(f);if(!$)return;this.activeSessionBootstraps.delete(f),await Promise.resolve($.dispose?.())}async start(f){let $=jj(f),J=await this.prepare?.($);try{let W=J?await J.applyToStartSessionInput($):$,H=await this.host.startSession(t5(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>$J({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(H.sessionId))this.activeSessionBootstraps.set(H.sessionId,J);else await Promise.resolve(J.dispose?.());return Pj({input:W,sessionId:H.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),H}catch(W){throw await Promise.resolve(J?.dispose?.()),W}}send=(...f)=>this.host.runTurn(...f);getAccumulatedUsage=(...f)=>{return this.host.getAccumulatedUsage?.(...f)??Promise.resolve(void 0)};abort=(...f)=>this.host.abort(...f);stop=async(f)=>{await this.host.stopSession(f),await this.disposeSessionBootstrap(f)};dispose=async(...f)=>{try{await this.automationService?.dispose(),await this.host.dispose(...f)}finally{this.unsubscribeBootstrapCleanup();let $=[...this.activeSessionBootstraps.keys()];await Promise.allSettled($.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...f)=>this.host.getSession(...f);listHistory=async(f={})=>await FJ(this.host,f);list=async(f=200,$={})=>await this.listHistory({...$,limit:f});delete=async(f)=>{let $=await this.host.deleteSession(f);if($)await this.disposeSessionBootstrap(f);return $};update=(...f)=>this.host.updateSession(...f);readMessages=(...f)=>this.host.readSessionMessages(...f);async restore(f){let $=f.start?t5(f.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>$J({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:f.sessionId,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restore:f.restore,start:$})}ingestHookEvent=(...f)=>this.host.dispatchHookEvent(...f);subscribe(f,$){return this.host.subscribe(f,$)}updateSessionModel=(...f)=>{return this.host.updateSessionModel?.(...f)??Promise.resolve()}}var gP={};N(gP,{resolvePluginConfigSearchPaths:()=>f8,resolveAndLoadAgentPlugins:()=>h1,resolveAgentPluginPaths:()=>O$,loadAgentPluginsFromPathsWithDiagnostics:()=>T0,loadAgentPluginsFromPaths:()=>B6,loadAgentPluginFromPath:()=>e2,discoverPluginModulePaths:()=>$8});var aP={};N(aP,{resolveMcpServerRegistrations:()=>Y4,resolveDefaultMcpSettingsPath:()=>Q$,registerMcpServersFromSettingsFile:()=>o1,loadMcpSettingsFile:()=>V4,hasMcpSettingsFile:()=>s1,createMcpTools:()=>e1,createDisabledMcpToolPolicy:()=>B4,createDisabledMcpToolPolicies:()=>NJ,createDefaultMcpServerClientFactory:()=>t1,InMemoryMcpManager:()=>r$});import{spawn as Qh}from"node:child_process";import{StringDecoder as dP}from"node:string_decoder";var Zh="2024-11-05",jh=5000,Ph=1500;function vP(f){return f instanceof Error?f.message:String(f)}function uP(f){let $=Buffer.from(JSON.stringify(f),"utf8"),J=Buffer.from(`Content-Length: ${$.byteLength}\r
552
+ \r
553
+ `,"utf8");return Buffer.concat([J,$])}function cP(f){return Buffer.from(`${JSON.stringify(f)}
554
+ `,"utf8")}class oH{buffer="";decoder=new dP("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`\r
555
+ \r
556
+ `);if(J<0)break;let H=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!H)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let Q=Number.parseInt(H[1],10),Z=J+4,j=Z+Q;if(this.buffer.length<j)break;$.push(this.buffer.slice(Z,j)),this.buffer=this.buffer.slice(j)}return $}}class eH{buffer="";decoder=new dP("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`
557
+ `);if(J<0)break;let W=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),W.length>0)$.push(W)}return $}}class rP{registration;process;nextRequestId=1;pending=new Map;framedParser=new oH;newlineParser=new eH;stderrBuffer="";connected=!1;protocolMode="newline";constructor(f){this.registration=f}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let f=["newline","framed"],$;for(let J of f){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:Zh,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},Ph),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(W){$=W instanceof Error?W:Error(String(W))}}throw $??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let f=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!f)return;f.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter(($)=>typeof $?.name==="string"&&typeof $.inputSchema==="object"&&$.inputSchema!==null).map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}async callTool(f){return this.request("tools/call",{name:f.name,arguments:f.arguments??{}})}spawnProcess(f){let $=this.registration.transport;if($.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${$.type}`);this.framedParser=new oH,this.newlineParser=new eH,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=Qh($.command,$.args??[],{cwd:$.cwd,env:{...process.env,...$.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=W,W.stdout.on("data",(H)=>this.handleStdout(H)),W.stderr.on("data",(H)=>{if(this.process!==W)return;if(this.stderrBuffer+=H.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(H)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${vP(H)}`))}),W.once("exit",(H,Q)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${H??"null"}, signal=${Q??"null"}).${Z}`))})}handleStdout(f){try{let $=this.protocolMode==="framed"?this.framedParser.push(f):this.newlineParser.push(f);for(let J of $){let W=JSON.parse(J);if(typeof W.id!=="number")continue;let H=this.pending.get(W.id);if(!H)continue;if(this.pending.delete(W.id),clearTimeout(H.timeout),W.error){let Q=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;H.reject(Error(Q));continue}H.resolve(W.result)}}catch($){this.handleProtocolFailure($)}}handleProtocolFailure(f){let $=this.process;if(!$)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${vP(f)}.${J}`)),$.kill()}async request(f,$,J=jh){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let H=this.nextRequestId++,Q={jsonrpc:"2.0",id:H,method:f,...$?{params:$}:{}},Z=new Promise((j,P)=>{let X=setTimeout(()=>{this.pending.delete(H),P(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(H,{resolve:j,reject:P,timeout:X})});try{W.stdin.write(this.protocolMode==="framed"?uP(Q):cP(Q))}catch(j){let P=this.pending.get(H);if(P)clearTimeout(P.timeout),this.pending.delete(H);throw j}return Z}notify(f,$){let J=this.process;if(!J?.stdin.writable)return;let W={jsonrpc:"2.0",method:f,...$?{params:$}:{}};J.stdin.write(this.protocolMode==="framed"?uP(W):cP(W))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}function t1(){return(f)=>new rP(f)}import{existsSync as Xh,readFileSync as Vh}from"node:fs";import{resolveMcpSettingsPath as Yh}from"@cline/shared/storage";import{z as k}from"zod";var X4=k.record(k.string(),k.string()),lP=k.record(k.string(),k.unknown()),Bh=k.object({type:k.literal("stdio"),command:k.string().min(1),args:k.array(k.string()).optional(),cwd:k.string().min(1).optional(),env:X4.optional()}),Ah=k.object({type:k.literal("sse"),url:k.string().url(),headers:X4.optional()}),Rh=k.object({type:k.literal("streamableHttp"),url:k.string().url(),headers:X4.optional()}),Fh=k.discriminatedUnion("type",[Bh,Ah,Rh]),yh=k.object({transport:Fh,disabled:k.boolean().optional(),metadata:lP.optional()}),Kh=k.enum(["stdio","sse","http","streamableHttp"]).optional(),pP=k.object({type:k.enum(["stdio","sse","streamableHttp"]).optional(),transportType:Kh,disabled:k.boolean().optional(),metadata:lP.optional()});function f9(f){if(!f)return;if(f==="http")return"streamableHttp";return f}var Uh=pP.extend({command:k.string().min(1),args:k.array(k.string()).optional(),cwd:k.string().min(1).optional(),env:X4.optional()}).superRefine((f,$)=>{let J=f.type??f9(f.transportType);if(J&&J!=="stdio")$.addIssue({code:k.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((f)=>({transport:{type:"stdio",command:f.command,args:f.args,cwd:f.cwd,env:f.env},disabled:f.disabled,metadata:f.metadata})),Gh=pP.extend({url:k.string().url(),headers:X4.optional()}).superRefine((f,$)=>{let J=f.type??f9(f.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")$.addIssue({code:k.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((f)=>{if((f.type??f9(f.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata};return{transport:{type:"sse",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata}}),Th=k.union([yh,Uh,Gh]),hh=k.object({mcpServers:k.record(k.string(),Th)}).strict();function Q$(){return Yh()}function V4(f={}){let $=f.filePath??Q$(),J=Vh($,"utf8"),W;try{W=JSON.parse(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}let H=hh.safeParse(W);if(!H.success){let Q=H.error.issues.map((Z)=>{let j=Z.path.join(".");return j?`${j}: ${Z.message}`:Z.message}).join("; ");throw Error(`Invalid MCP settings at "${$}": ${Q}`)}return H.data}function s1(f={}){let $=f.filePath??Q$();return Xh($)}function Y4(f={}){let $=V4(f);return Object.entries($.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata}))}async function o1(f,$={}){let J=Y4($);for(let W of J)await f.registerServer(W);return J}function kf(){return Date.now()}function Dh(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class r${toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(f){this.clientFactory=f.clientFactory,this.toolsCacheTtlMs=f.toolsCacheTtlMs??5000}async registerServer(f){await this.runExclusive(f.name,async()=>{let $=this.servers.get(f.name);if(!$){this.servers.set(f.name,{registration:{...f},status:"disconnected",updatedAt:kf()});return}let J=JSON.stringify($.registration.transport)!==JSON.stringify(f.transport);if($.registration={...f},$.updatedAt=kf(),J)await this.disconnectState($),$.client=void 0,$.toolCache=void 0,$.toolCacheUpdatedAt=void 0})}async unregisterServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($),this.servers.delete(f)})}async connectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.connectState($)})}async disconnectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($)})}async setServerDisabled(f,$){await this.runExclusive(f,async()=>{let J=this.requireServer(f);if(J.registration={...J.registration,disabled:$},J.updatedAt=kf(),$)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map((f)=>({name:f.registration.name,status:f.status,disabled:f.registration.disabled===!0,lastError:f.lastError,toolCount:f.toolCache?.length??0,updatedAt:f.updatedAt,metadata:f.registration.metadata})).sort((f,$)=>f.name.localeCompare($.name))}async listTools(f){let $=this.requireServer(f),J=$.toolCacheUpdatedAt??0;if($.toolCache&&kf()-J<=this.toolsCacheTtlMs)return $.toolCache;return this.refreshTools(f)}async refreshTools(f){return this.runExclusive(f,async()=>{let $=this.requireServer(f),W=await(await this.ensureConnectedClient($)).listTools(),H=Dh(W);return $.toolCache=H,$.toolCacheUpdatedAt=kf(),$.updatedAt=kf(),H})}async callTool(f){return this.runExclusive(f.serverName,async()=>{let $=this.requireServer(f.serverName),J=await this.ensureConnectedClient($);return $.updatedAt=kf(),J.callTool({name:f.toolName,arguments:f.arguments,context:f.context})})}async dispose(){let f=[...this.servers.keys()];for(let $ of f)await this.unregisterServer($)}async ensureConnectedClient(f){if(await this.connectState(f),!f.client)throw Error(`MCP server "${f.registration.name}" does not have an initialized client.`);return f.client}async connectState(f){if(f.registration.disabled)throw Error(`MCP server "${f.registration.name}" is disabled and cannot be connected.`);if(f.status==="connected"&&f.client)return;f.status="connecting",f.updatedAt=kf();try{let $=f.client??await this.clientFactory(f.registration);await $.connect(),f.client=$,f.status="connected",f.lastError=void 0,f.updatedAt=kf()}catch($){throw f.status="disconnected",f.lastError=$ instanceof Error?$.message:String($),f.updatedAt=kf(),$}}async disconnectState(f){if(!f.client){f.status="disconnected",f.updatedAt=kf();return}try{await f.client.disconnect()}finally{f.status="disconnected",f.updatedAt=kf()}}requireServer(f){let $=this.servers.get(f);if(!$)throw Error(`Unknown MCP server: ${f}`);return $}async runExclusive(f,$){let J=this.operationLocks.get(f)??Promise.resolve(),W,H=new Promise((Z)=>{W=Z}),Q=J.catch(()=>{return}).then(()=>H);this.operationLocks.set(f,Q),await J.catch(()=>{return});try{return await $()}finally{if(W?.(),this.operationLocks.get(f)===Q)this.operationLocks.delete(f)}}}import{createHash as Mh}from"node:crypto";var iP=128,_h=/[^a-zA-Z0-9_-]+/g,nP=8,Lh=1,zh="mcp_tool";function Oh(f){return Mh("sha1").update(f).digest("hex").slice(0,nP)}function Nh(f){return f.replace(_h,"_")}var OJ=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,W=Nh(J);if(W===J&&J.length<=iP)return J;let H=Oh(J),Q=iP-Lh-nP;return`${W.slice(0,Q)||zh}_${H}`};function B4(f){return{[(f.nameTransform??OJ)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function NJ(f){let $={};for(let J of f.toolNames)Object.assign($,B4({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as qh}from"@cline/shared";function bh(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function e1(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??OJ;return $.map((W)=>{let H=J({serverName:f.serverName,toolName:W.name});return qh({name:H,description:bh(f.serverName,W),inputSchema:W.inputSchema,timeoutMs:f.timeoutMs,retryable:f.retryable,maxRetries:f.maxRetries,execute:async(Q,Z)=>f.provider.callTool({serverName:f.serverName,toolName:W.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:Z})})})}var oP={};N(oP,{toHookConfigFileName:()=>H8,runSubprocessEvent:()=>f2,runHook:()=>J2,resolveHooksConfigSearchPaths:()=>J8,parseHookEventPayload:()=>$2,mergeAgentHooks:()=>w$,listHookConfigFiles:()=>l0,createSubprocessHooks:()=>wJ,createHookConfigFileHooks:()=>Q8,createHookConfigFileExtension:()=>L1,createHookAuditHooks:()=>_1,createAgentHooksExtension:()=>D1,HookEventPayloadSchema:()=>bJ,HookEventNameSchema:()=>qJ,HookConfigFileName:()=>M1,HOOK_CONFIG_FILE_EVENT_MAP:()=>W8,HOOKS_CONFIG_DIRECTORY_NAME:()=>F6});import{HookEventNameSchema as qJ,HookEventPayloadSchema as bJ,parseHookEventPayload as $2,resolveHookSessionContext as Ih}from"@cline/shared";import{z as l$}from"zod";import{spawn as wh}from"node:child_process";import{augmentNodeCommandForDebug as Ch,withResolvedClineBuildEnv as Eh}from"@cline/shared";function Sh(f){let $=f.trim();if(!$)return{};let W=$.split(`
558
+ `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),H=W.length>0?W[W.length-1]:$;try{return{parsedJson:JSON.parse(H)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function kh(f,$){let J=f instanceof Error?f:Error(String(f)),W=J,H=$.join(" ");if(W.code==="EACCES")return Error(`Failed to execute hook command "${H}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${H}": ${J.message}`)}async function mh(f,$){let J=f.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,H)=>{let Q=(Z)=>{J.off("error",Q);let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}H(Z)};J.once("error",Q),J.end($,(Z)=>{if(J.off("error",Q),Z){let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}H(Z);return}W()})})}async function f2(f,$){let J=Ch($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!$.detached,H=wh(J[0],J.slice(1),{cwd:$.cwd,env:Eh($.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((B)=>{H.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:H.pid??void 0,detached:W})}catch{}B()})}),Z=new Promise((B,A)=>{H.once("error",(R)=>{A(kh(R,J))})});if(await mh(H,JSON.stringify(f)),W){await Promise.race([Q,Z]),H.unref();return}if(!H.stdout||!H.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let j="",P="",X=!1,V;H.stdout.on("data",(B)=>{j+=B.toString()}),H.stderr.on("data",(B)=>{P+=B.toString()});let Y=new Promise((B)=>{if(($.timeoutMs??0)>0)V=setTimeout(()=>{X=!0,H.kill("SIGKILL")},$.timeoutMs);H.once("close",(A)=>{if(V)clearTimeout(V);let{parsedJson:R,parseError:U}=Sh(j);B({exitCode:A,stdout:j,stderr:P,parsedJson:R,parseError:U,timedOut:X})})});return await Promise.race([Y,Z])}var xh=l$.object({contextModification:l$.string().optional(),cancel:l$.boolean().optional(),review:l$.boolean().optional(),errorMessage:l$.string().optional(),context:l$.string().optional(),overrideInput:l$.unknown().optional()}).passthrough();var gh=["agent","hook"];async function J2(f,$={}){let J=$.command??gh;return await f2(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function sP(f){return f instanceof Error?f:Error(String(f))}function vh(f){if(!f||typeof f!=="object")return;let $=xh.safeParse(f);if(!$.success)return;let J=$.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let H=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:H,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function tP(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,W]of Object.entries(f))if(typeof W==="string")$[J]=W;else $[J]=JSON.stringify(W);return $}function O0(f,$,J){let W=J.env??process.env,H=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:f,timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Ih(J.sessionContext,{hookName:f,conversationId:$.conversationId,agentId:$.agentId,parentAgentId:$.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:H,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function uh(f){return{name:f.name,message:f.message,stack:f.stack}}function ch(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function dh(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function rh(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function lh(f){return{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}function ph(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}async function p$(f,$){try{let J=await J2(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(sP(J),f)}}function wJ(f={}){return{hooks:{beforeRun:async(j)=>{let P=dh(j);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let V={...O0("agent_resume",P,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await p$(V,f)}else{let V={...O0("agent_start",P,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await p$(V,f)}return},beforeTool:async(j)=>{let P={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},X={...O0("tool_call",P,f),hookName:"tool_call",iteration:j.snapshot.iteration,tool_call:{id:j.toolCall.toolCallId,name:j.toolCall.toolName,input:j.input},preToolUse:{toolName:j.toolCall.toolName,parameters:tP(j.input)}};try{let V=await J2(X,{command:f.command,cwd:f.cwd,env:f.env,detached:!1,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn});if(f.onDispatch?.({payload:X,result:V,detached:!1}),V?.timedOut)throw Error("tool_call hook command timed out");if(V?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${V.parseError}`);return ph(vh(V?.parsedJson))}catch(V){f.onDispatchError?.(sP(V),X);return}},afterTool:async(j)=>{let P=lh(j),X={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},V={...O0("tool_result",X,f),hookName:"tool_result",iteration:j.snapshot.iteration,tool_result:P,postToolUse:{toolName:P.name,parameters:tP(P.input),result:typeof P.output==="string"?P.output:JSON.stringify(P.output),success:!P.error,executionTimeMs:P.durationMs}};await p$(V,f);return},afterRun:async({snapshot:j,result:P})=>{let X={agentId:j.agentId,conversationId:j.conversationId??j.runId??j.agentId,parentAgentId:j.parentAgentId??null};if(P.status==="completed"){let B={...O0("agent_end",X,f),hookName:"agent_end",iteration:P.iterations,turn:{outputText:P.outputText,status:P.status},taskComplete:{taskMetadata:{}}};await p$(B,f);return}let V=P.status==="aborted"||ch(P.error?.message)?"agent_abort":"agent_error",Y=V==="agent_error"?{...O0(V,X,f),hookName:V,iteration:P.iterations,error:uh(P.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...O0(V,X,f),hookName:V,reason:P.error?.message,taskCancel:{taskMetadata:{}}};await p$(Y,f)},onEvent:async(j)=>{if(j.type!=="message-added"||j.message.role!=="user")return;let P={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},X={...O0("prompt_submit",P,f),hookName:"prompt_submit",userPromptSubmit:{prompt:rh(j.message.content),attachments:[]}};await p$(X,f)}},shutdown:async({agentId:j,conversationId:P,parentAgentId:X,reason:V})=>{let Y={...O0("session_shutdown",{agentId:j,conversationId:P,parentAgentId:X},f),hookName:"session_shutdown",reason:V};await p$(Y,f)}}}var fV={};N(fV,{writeHubDiscovery:()=>KJ,withHubStartupLock:()=>UJ,verifyHubConnection:()=>f0,truncateNotificationBody:()=>y4,toHubHealthUrl:()=>hH,stopLocalHubServerGracefully:()=>CH,startHubWebSocketServer:()=>t$,startHubServer:()=>oX,spawnDetachedHubServer:()=>u1,sendHubCommand:()=>HX,restartLocalHubIfIdleAfterStartupTimeout:()=>hJ,resolveWorkspaceHubOwnerContext:()=>aj,resolveSharedHubOwnerContext:()=>Qf,resolveHubUrl:()=>H9,resolveHubOwnerContext:()=>M0,resolveHubEndpointOptions:()=>Sf,resolveHubBuildId:()=>J$,resolveDefaultHubPort:()=>v1,resolveDefaultHubPathname:()=>zH,resolveDefaultHubHost:()=>LH,resolveCompatibleLocalHubUrl:()=>f4,resolveClineDir:()=>lj,resolveClineDataDir:()=>t8,requestHubShutdown:()=>e8,rememberRecoverableLocalHubUrl:()=>W$,readHubDiscovery:()=>Zf,probeHubServer:()=>Bf,probeHubConnection:()=>WX,prewarmDetachedHubServer:()=>GJ,normalizeHubWebSocketUrl:()=>H$,isHubReconnectableTransportError:()=>bH,isHubCommandTimeoutError:()=>TJ,isDiscoveryFilePresent:()=>ij,ensureHubWebSocketServer:()=>vJ,ensureHubServer:()=>eX,ensureDetachedHubServer:()=>sj,ensureCompatibleLocalHubUrl:()=>g$,createLocalHubScheduleRuntimeHandlers:()=>uJ,createInMemoryHubOwnerContext:()=>pj,createHubServerUrl:()=>lf,createHubAuthToken:()=>yJ,createConfiguredTelemetryService:()=>i$,createConfiguredTelemetryHandle:()=>j2,connectToHub:()=>kJ,clearHubDiscovery:()=>Ef,NodeHubClient:()=>pf,NativeHubTransportAdapter:()=>h4,HubUIClient:()=>Z9,HubTransportError:()=>yf,HubSessionClient:()=>Q9,HubServerTransport:()=>X2,HubScheduleService:()=>H2,HubScheduleCommandService:()=>W2,HubCommandError:()=>c1,DEFAULT_HUB_PORT:()=>MH,DEFAULT_HUB_PATHNAME:()=>_H,DEFAULT_HUB_HOST:()=>DH,BrowserWebSocketHubAdapter:()=>T4});import{createSessionId as ih}from"@cline/shared";function mf(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function eP(f,$,J){return{version:f.version,requestId:f.requestId??ih("hubreq_"),ok:!1,error:{code:$,message:J}}}class W2{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return mf(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return mf(f,{schedules:this.schedules.listSchedules({enabled:typeof f.payload?.enabled==="boolean"?f.payload.enabled:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0,tags:Array.isArray(f.payload?.tags)?f.payload?.tags:void 0})});case"schedule.get":return mf(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return mf(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return mf(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return mf(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return mf(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return mf(f,{execution:await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return mf(f,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof f.payload?.scheduleId==="string"?f.payload.scheduleId:void 0,status:typeof f.payload?.status==="string"?f.payload.status:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0})});case"schedule.stats":return mf(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return mf(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return mf(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return eP(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return eP(f,"schedule_command_failed",$ instanceof Error?$.message:String($))}}toCreateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider&&f.model?{providerId:String(f.provider),modelId:String(f.model)}:void 0;return{...f,modelSelection:$}}toUpdateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider||f.model?{providerId:typeof f.provider==="string"?f.provider:"",modelId:typeof f.model==="string"?f.model:""}:void 0;return{...f,modelSelection:$}}}function EJ(f){return f?new Date(f).getTime():void 0}function nh(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function CJ(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:EJ(f.nextRunAt),lastRunAt:EJ(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:nh(f)}}function ah(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function fX(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:EJ(f.startedAt),endedAt:EJ(f.completedAt),status:ah(f.status),errorMessage:f.error}}class H2{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new i8({dbPath:f.dbPath}),this.materializer=new c8({store:this.store}),this.runner=new d8({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule(f){if(QH(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return CJ(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?CJ($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>CJ($))}updateSchedule(f,$){if($.cronPattern!==void 0)QH($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let W=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule(f,{...$,scheduleId:f});return Q?CJ(Q):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return fX(J,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((H)=>{let Q=$??this.store.getSpec(H.specId);if(!Q||Q.source!=="hub-schedule")return;return fX(H,Q.externalId)}).filter((H)=>{if(!H)return!1;return!f.status||H.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,W=0,H=0,Q;for(let Z of $){if(Z.status==="success"||Z.status==="completed")J+=1;if(!Q&&Z.status!=="success"&&Z.status!=="completed")Q=Z;if(Z.startedAt&&Z.endedAt)H+=Z.endedAt-Z.startedAt,W+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:W>0?H/W/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,W)=>String(J.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:W})=>({scheduleId:J.externalId,name:J.title,nextRunAt:W}))}}SJ();function UD(f,$){if(f instanceof Error)return f;if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"&&f.message.trim())return Error(f.message.trim());let J=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return Error(J?`Failed to connect to hub at ${$} (${J} event before socket open).`:`Failed to connect to hub at ${$}.`)}var GD="cline-hub-auth.";function TD(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function hD(f,$){let J=new URL(f),W=new URL($);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function DD(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=Qf(),W=await Zf(J.discoveryPath);if(W?.url&&hD(f.toString(),W.url))return W.authToken;return}async function H9(f={}){let $=Sf(f);if(!TD(f)){let J=Qf(),W=await Zf(J.discoveryPath);if(W?.url)return W.url}return lf($.host,$.port,$.pathname)}async function kJ(f){return await new Promise(($,J)=>{(async()=>{let W=new URL(f),H=await DD(W);W.hash="";let Q=new WebSocket(W.toString(),H?[`${GD}${H}`]:void 0),Z=new Map,j=0;Q.addEventListener("open",()=>{$({send(P){let X=P.requestId??`hub-client-${++j}`;return new Promise((V,Y)=>{Z.set(X,{resolve:V,reject:Y});let B={kind:"command",envelope:{...P,requestId:X}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(P)=>{let X=JSON.parse(String(P.data));if(X.kind==="reply"&&X.envelope.requestId){let V=Z.get(X.envelope.requestId);if(V)Z.delete(X.envelope.requestId),V.resolve(X.envelope)}}),Q.addEventListener("close",()=>{for(let P of Z.values())P.reject(Error("Hub connection closed"));Z.clear()}),Q.addEventListener("error",(P)=>{J(UD(P,f))})})().catch(J)})}async function WX(f){try{return(await kJ(f)).close(),!0}catch{return!1}}async function HX(f,$){let J=await H9(f),W=await kJ(J);try{return await W.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{W.close()}}function j0(f){return f?JSON.parse(JSON.stringify(f)):{}}function mJ(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?j0($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function QX(f,$){return f.error?.message??`hub command failed: ${$}`}function MD(f){let $=j0(f);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let J=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...$,error:J.text.trim()};let W=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...$,error:W.message.trim()};return $}function _D(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let J=$;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function LD(f){let $=f.sessionId?.trim();if(!$)return;switch(f.event){case"iteration.started":return{sessionId:$,eventType:"runtime.chat.iteration_start",payload:j0(f.payload)};case"iteration.finished":return{sessionId:$,eventType:"runtime.chat.iteration_end",payload:j0(f.payload)};case"assistant.delta":return{sessionId:$,eventType:"runtime.chat.text_delta",payload:j0(f.payload)};case"tool.started":return{sessionId:$,eventType:"runtime.chat.tool_call_start",payload:j0(f.payload)};case"tool.finished":return{sessionId:$,eventType:"runtime.chat.tool_call_end",payload:j0(f.payload)};case"approval.requested":return{sessionId:$,eventType:"approval.requested",payload:j0(f.payload)};case"run.aborted":return{sessionId:$,eventType:"runtime.chat.aborted",payload:j0(f.payload)};case"run.failed":return{sessionId:$,eventType:"runtime.chat.failed",payload:MD(f.payload)};case"run.completed":return{sessionId:$,eventType:"runtime.chat.completed",payload:j0(f.payload)};default:return}}class Q9{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new pf({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-session-client",displayName:f.displayName??"hub session client",workspaceRoot:f.workspaceRoot,cwd:f.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:f.workspaceRoot,cwd:f.cwd,sessionConfig:{providerId:f.provider,modelId:f.model,apiKey:f.apiKey,cwd:f.cwd??f.workspaceRoot,workspaceRoot:f.workspaceRoot,systemPrompt:f.systemPrompt??"",mode:f.mode??"act",rules:f.rules,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawnAgent:f.enableSpawn!==!1,enableAgentTeams:f.enableTeams!==!1,disableMcpSettingsTools:f.disableMcpSettingsTools,missionLogIntervalSteps:f.missionStepInterval,missionLogIntervalMs:f.missionTimeIntervalMs},metadata:{source:f.source??"cli",provider:f.provider,model:f.model,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,prompt:void 0,interactive:f.interactive!==!1},runtimeOptions:{mode:f.mode,systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,autoApproveTools:f.autoApproveTools,toolExecutors:f.toolExecutors,configExtensions:f.configExtensions},modelSelection:{provider:f.provider,model:f.model,apiKey:f.apiKey},toolPolicies:f.toolPolicies}),J=mJ($.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession(f,$,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:$.prompt,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},f,J)).payload?.result}}async stopRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:f},f),{applied:!0}}async abortRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:f},f),{applied:!0}}async updateSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:f.sessionId,metadata:f.metadata},f.sessionId),{updated:!0}}async getSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.get",void 0,f);return mJ($.payload)}async readMessages(f){let $=f.trim();if(!$)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(QX(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async restore(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=f.config,H=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...W?{workspaceRoot:W.workspaceRoot,cwd:W.cwd,sessionConfig:{providerId:W.provider,modelId:W.model,apiKey:W.apiKey,cwd:W.cwd??W.workspaceRoot,workspaceRoot:W.workspaceRoot,systemPrompt:W.systemPrompt??"",mode:W.mode??"act",rules:W.rules,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawnAgent:W.enableSpawn!==!1,enableAgentTeams:W.enableTeams!==!1,disableMcpSettingsTools:W.disableMcpSettingsTools,missionLogIntervalSteps:W.missionStepInterval,missionLogIntervalMs:W.missionTimeIntervalMs},metadata:{source:W.source??"cli",provider:W.provider,model:W.model,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,prompt:void 0,interactive:W.interactive!==!1},runtimeOptions:{mode:W.mode,systemPrompt:W.systemPrompt,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,autoApproveTools:W.autoApproveTools,configExtensions:W.configExtensions},modelSelection:{provider:W.provider,model:W.model,apiKey:W.apiKey},toolPolicies:W.toolPolicies}:{}},$);if(!H.ok)throw Error(QX(H,"session.restore"));let Q=mJ(H.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let Z=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,j=_D(H.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...Z?{messages:Z}:{},checkpoint:j}}async listSessions(f){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:f?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((W)=>mJ({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession(f,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:f,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(f){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:f.approvalId,approved:f.approved,payload:f.reason?{reason:f.reason}:void 0,responderClientId:f.responderClientId})}streamEvents(f,$){let J=new Set((f.sessionIds??[]).map((H)=>H.trim()).filter(Boolean)),W=this.client.subscribe((H)=>{let Q=LD(H);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;$.onEvent?.(Q)});return this.ensureMetadataApplied().catch((H)=>{$.onError?.(H instanceof Error?H:Error(String(H)))}),W}streamTeamProgress(f,$){let J=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;$.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{$.onError?.(W instanceof Error?W:Error(String(W)))}),J}async createSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",f)).payload?.schedule}async listSchedules(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:f})).payload?.schedule}async updateSchedule(f,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:f,...$})).payload?.schedule}async pauseSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:f})).payload?.schedule}async resumeSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:f})).payload?.schedule}async deleteSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:f})).payload?.deleted===!0}async triggerScheduleNow(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:f})).payload?.execution}async listScheduleExecutions(f,$){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:f,limit:$});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let f=await this.client.command("schedule.active");return Array.isArray(f.payload?.executions)?f.payload?.executions:[]}async getUpcomingScheduledRuns(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:f});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}}class Z9{client;constructor(f){this.client=new pf({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}function zD(f){if(typeof f==="string")return f.trim()||void 0;if(!Array.isArray(f))return;return f.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
559
+ `).trim()||void 0}var ZX=120,j9="...";function y4(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=ZX)return $;let J=ZX-Buffer.byteLength(j9,"utf8");if(J<=0)return j9;let W="";for(let H of $){if(Buffer.byteLength(W+H,"utf8")>J)break;W+=H}return`${W}${j9}`}async function jX(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,H=[...await x$(J)].reverse().find((P)=>P.role==="assistant"),Q=H?zD(H.content):void 0,Z=f?.workspaceRoot?.trim()||"workspace",j=typeof f?.metadata?.prompt==="string"?f.metadata.prompt.trim():Z;return{title:`Task completed (${$})`,body:y4(Q&&Q.length>0?Q:j.length>0?j:Z),severity:"info"}}import{createSessionId as HM}from"@cline/shared";import{createSessionId as bD}from"@cline/shared";import{createSessionId as qD}from"@cline/shared";function OD(f){switch(f){case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function ND(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):{};if(f.parentSessionId?.trim())$.parentSessionId=f.parentSessionId;if(f.parentAgentId?.trim())$.parentAgentId=f.parentAgentId;if(f.agentId?.trim())$.agentId=f.agentId;if(f.conversationId?.trim())$.conversationId=f.conversationId;if(f.messagesPath?.trim())$.messagesPath=f.messagesPath;if(f.prompt?.trim())$.prompt=f.prompt;if(f.provider?.trim())$.provider=f.provider;if(f.model?.trim())$.model=f.model;if(f.source?.trim())$.source=f.source;if(typeof f.pid==="number")$.pid=f.pid;return Object.keys($).length>0?$:void 0}function IJ(f,$){return{sessionId:f.sessionId,workspaceRoot:f.workspaceRoot,cwd:f.cwd,createdAt:Date.parse(f.startedAt),updatedAt:Date.parse(f.updatedAt),createdByClientId:$?.createdByClientId??"hub",status:OD(f.status),participants:$?[...$.participants.values()]:[],metadata:ND(f),runtimeOptions:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,mode:typeof f.metadata?.mode==="string"?f.metadata.mode:void 0,systemPrompt:typeof f.metadata?.systemPrompt==="string"?f.metadata.systemPrompt:void 0},runtimeSession:f.agentId?{agentId:f.agentId,team:f.teamName?{teamId:f.teamName}:void 0}:void 0}}function v(f,$){return{version:f.version,requestId:f.requestId,ok:!0,...$!==void 0?{payload:$}:{}}}function m(f,$,J){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:$,message:J}}}function xJ(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function hf(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function n$(f,$,J){return{version:"v1",event:f,eventId:qD("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function If(f,$){let J=await f.sessionHost.getSession($);if(!J)return;return IJ(J,f.sessionState.get($))}async function xf(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let[W,H]=await Promise.all([typeof f.sessionHost.readSessionMessages==="function"?f.sessionHost.readSessionMessages($):[],f.sessionHost.getAccumulatedUsage?.($)]);return $0({session:J,messages:W,usage:H})}function gJ(f,$,J,W,H={}){let Q=f.sessionState.get($);if(Q){if(H.interactive!==void 0)Q.interactive=H.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:W});return Q}let Z={createdByClientId:J,interactive:H.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:W}]])};return f.sessionState.set($,Z),Z}async function P9(f,$){let J=bD("approval_"),W=$.sessionId;if(f.sessionState.get(W)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((Q)=>{f.pendingApprovals.set(J,{sessionId:W,resolve:Q}),f.publish(f.buildEvent("approval.requested",{approvalId:J,sessionId:$.sessionId,agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:JSON.stringify($.input??null),policy:$.policy},W))})}function X9(f,$,J){let W=f.pendingApprovals.get($);if(!W)return;return f.pendingApprovals.delete($),W.resolve(J),{sessionId:W.sessionId}}function V9(f,$,J){let W=0;for(let[H,Q]of[...f.pendingApprovals.entries()]){if(!$({approvalId:H,sessionId:Q.sessionId}))continue;f.pendingApprovals.delete(H),Q.resolve({approved:!1,reason:J}),f.publish(f.buildEvent("approval.resolved",{approvalId:H,approved:!1,cancelled:!0,reason:J},Q.sessionId)),W+=1}return W}async function PX(f,$){let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"";if(!f.pendingApprovals.get(J))return m($,"approval_not_found",`Unknown approval: ${J}`);let H=typeof $.payload?.reason==="string"?$.payload.reason:$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)&&typeof $.payload.payload.reason==="string"?$.payload.payload.reason:void 0,Q=$.payload?.approved===!0,Z=X9(f,J,{approved:Q,reason:H});if(!Z)return m($,"approval_not_found",`Unknown approval: ${J}`);return f.publish(f.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:H},Z.sessionId)),v($,{approvalId:J,approved:Q})}import{createSessionId as ED}from"@cline/shared";function wD(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var XX={debug:10,info:20,warn:30,error:40,silent:50};function CD(){let f=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if(f==="debug"||f==="info"||f==="warn"||f==="error"||f==="silent")return f;return process.env.VITEST?"error":"info"}function x(f,$,J={}){if(XX[f]<XX[CD()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([H,Q])=>[H,wD(Q)]).filter(([,H])=>H!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function Y9(f,$){let J=$ instanceof Error?$.stack||$.message:String($);x("error",f,{error:J})}async function VX(f,$,J,W,H,Q){let Z=ED("capreq_"),j=performance.now();return x("info","capability.request.start",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H}),await new Promise((P,X)=>{f.pendingCapabilityRequests.set(Z,{sessionId:$,targetClientId:H,capabilityName:J,onProgress:Q,resolve:(V)=>{if(x(V.ok?"info":"warn","capability.request.end",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H,ok:V.ok,error:V.error,durationMs:Math.round(performance.now()-j)}),!V.ok){X(Error(V.error||`Capability ${J} was rejected by ${H}.`));return}P(V.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:Z,targetClientId:H,capabilityName:J,payload:W},$)),x("info","capability.request.published",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H})})}function YX(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",W=f.pendingCapabilityRequests.get(J);if(!W)return m($,"capability_not_found",`Unknown capability request: ${J}`);if(($.clientId?.trim()||"")!==W.targetClientId)return m($,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==W.sessionId)return m($,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{};return W.onProgress?.(Q),v($,{requestId:J})}function Z$(f,$,J){let W=0;for(let[H,Q]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:H,...Q}))continue;f.pendingCapabilityRequests.delete(H),x("warn","capability.request.cancelled",{requestId:H,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),f.publish(f.buildEvent("capability.resolved",{requestId:H,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),W+=1}return W}async function BX(f,$){let J=typeof $.payload?.sessionId==="string"?$.payload.sessionId.trim():$.sessionId?.trim()||"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName.trim():"",H=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId.trim():"";if(!J||!W||!H)return m($,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Z=await f.requestCapability(J,W,Q,H);return v($,Z)}catch(Q){return m($,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function AX(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",W=f.pendingCapabilityRequests.get(J);if(!W)return m($,"capability_not_found",`Unknown capability request: ${J}`);let H=$.clientId?.trim()||"";if(H!==W.targetClientId)return m($,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==W.sessionId)return m($,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);f.pendingCapabilityRequests.delete(J);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:void 0,Z=typeof $.payload?.error==="string"?$.payload.error:void 0,j=$.payload?.ok===!0;return x(j?"info":"warn","capability.respond",{requestId:J,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:H,ok:j,error:Z}),W.resolve({ok:j,payload:Q,error:Z}),f.publish(f.buildEvent("capability.resolved",{requestId:J,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:H,ok:j,payload:Q,error:Z},W.sessionId)),v($,{requestId:J,ok:j})}import{createSessionId as SD}from"@cline/shared";function RX(f,$){let J=$.payload,W=J?.clientId?.trim()||$.clientId?.trim()||SD("client_");return f.clients.set(W,{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),f.publish(f.buildEvent("hub.client.registered",{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),v($,{clientId:W})}function FX(f,$){let J=$.clientId?.trim(),W=J?f.clients.get(J):void 0;if(!J||!W)return m($,"client_not_found","Client is not registered with this hub.");let H=xJ($.payload?.metadata);if(W.lastSeenAt=Date.now(),H)W.metadata=JSON.parse(JSON.stringify(H));return v($)}function yX(f,$,J){let W=$.clientId?.trim();if(W)f.clients.delete(W),J(W),f.publish(f.buildEvent("hub.client.disconnected",{clientId:W}));return v($)}function KX(f,$){return v($,{clients:[...f.clients.values()]})}var kD=30000;function mD(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function ID(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function xD(f){let $=typeof f.timeoutMs==="number"?f.timeoutMs:typeof f.timeout_ms==="number"?f.timeout_ms:void 0;if($&&Number.isFinite($)&&$>0)return Math.floor($);let J=typeof f.timeoutSeconds==="number"?f.timeoutSeconds:typeof f.timeout_seconds==="number"?f.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function gD(f,$,J,W){let H=performance.now(),Q=!1,Z={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J.sessionId,timeoutMs:W},j=setInterval(()=>{if(Q)return;let V=Math.round(performance.now()-H);x("warn","run.heartbeat",{...Z,elapsedMs:V}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:V,...W?{timeoutMs:W}:{}},J.sessionId))},kD),P=f.sessionHost.runTurn(J);P.then((V)=>{if(!Q)return;x("warn","run.late_end",{...Z,elapsedMs:Math.round(performance.now()-H),finishReason:V?.finishReason})},(V)=>{if(!Q)return;x("error","run.late_error",{...Z,elapsedMs:Math.round(performance.now()-H),error:V})});let X;try{if(!W)return await P;return await Promise.race([P,new Promise((V,Y)=>{X=setTimeout(()=>{let B=`Hub run ${$.command} timed out after ${W}ms.`;Q=!0,clearInterval(j),Y(Error(B)),x("error","run.timeout",{...Z,elapsedMs:Math.round(performance.now()-H)}),V9(f,(A)=>A.sessionId===J.sessionId,B),Z$(f,(A)=>A.sessionId===J.sessionId,B),f.sessionHost.abort(J.sessionId,B).catch((A)=>{x("error","run.timeout_abort_failed",{...Z,error:A})})},W)})])}finally{if(Q=!0,clearInterval(j),X)clearTimeout(X)}}async function UX(f,$){let J=hf($),W=$.payload&&typeof $.payload==="object"?$.payload:{},H=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!H.trim())return m($,"invalid_session_input","session input requires a prompt string");f.publish(f.buildEvent("run.started",void 0,J));let Q=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,Z=Array.isArray(Q?.userFiles)?Q.userFiles.filter((V)=>typeof V==="string"):void 0,j=xD(W);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let P;try{P=await gD(f,$,{sessionId:J,prompt:H,delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:Z,timeoutMs:j},j)}catch(V){if(f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J);throw f.publish(f.buildEvent("run.failed",{reason:"error",error:V instanceof Error?V.message:String(V)},J)),V}if(P){let V=await xf(f,J),Y=ID(P);if(f.publish(f.buildEvent(mD(P.finishReason),{reason:P.finishReason,...Y?{error:Y}:{},result:P,...V?{snapshot:V}:{}},J)),f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J)}else f.suppressNextTerminalEventBySession.delete(J);let X=await xf(f,J);return v($,P||X?{...P?{result:P}:{},...X?{snapshot:X}:{}}:void 0)}async function GX(f,$){let J=hf($),W=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";return V9(f,(H)=>H.sessionId===J,W),await f.sessionHost.abort(J,$.payload?.reason),Z$(f,(H)=>H.sessionId===J,W),f.publish(f.buildEvent("run.aborted",{reason:W},J)),v($,{applied:!0})}async function TX(f,$){let J=$2($.payload?.payload);if(!J)return m($,"invalid_hook_payload","session.hook requires a valid hook event payload");return await f.sessionHost.dispatchHookEvent(J),v($,{applied:!0})}async function hX(f,$){switch($.type){case"chunk":return;case"agent_event":vD(f,$);return;case"hook":if($.payload.hookEventName==="tool_call")f.publish(f.buildEvent("tool.started",{toolName:$.payload.toolName},$.payload.sessionId));else if($.payload.hookEventName==="tool_result")f.publish(f.buildEvent("tool.finished",{toolName:$.payload.toolName},$.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:$.payload.sessionId,summary:$.payload.summary,lastEvent:$.payload.lifecycle};f.publish(f.buildEvent("team.progress",J,$.payload.sessionId));return}case"pending_prompts":f.publish(f.buildEvent("session.pending_prompts",{sessionId:$.payload.sessionId,prompts:$.payload.prompts},$.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:$.payload.id,prompt:$.payload.prompt,delivery:$.payload.delivery,attachmentCount:$.payload.attachmentCount};f.publish(f.buildEvent("session.pending_prompt_submitted",{sessionId:$.payload.sessionId,prompt:J},$.payload.sessionId));return}case"session_snapshot":f.publish(f.buildEvent("session.updated",{sessionId:$.payload.sessionId,snapshot:$.payload.snapshot},$.payload.sessionId));return;case"status":{let[J,W]=await Promise.all([If(f,$.payload.sessionId),xf(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...W?{snapshot:W}:{}},$.payload.sessionId));return}case"ended":await uD(f,$);return;default:return}}function vD(f,$){let{sessionId:J,event:W}=$.payload;if(W.type==="iteration_start"){f.publish(f.buildEvent("iteration.started",{iteration:W.iteration},J));return}if(W.type==="iteration_end"){f.publish(f.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},J));return}if(W.type==="content_start"){if(W.contentType==="text"&&typeof W.text==="string"&&W.text.length>0){f.publish(f.buildEvent("assistant.delta",{text:W.text},J));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){f.publish(f.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)f.publish(f.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},J));return}if(W.contentType==="tool"){f.publish(f.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},J));return}}if(W.type==="content_end"){switch(W.contentType){case"text":f.publish(f.buildEvent("assistant.finished",{text:W.text},J));break;case"reasoning":f.publish(f.buildEvent("reasoning.finished",{reasoning:W.reasoning},J));break;case"tool":f.publish(f.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},J));break}return}if(W.type==="done")f.publish(f.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},J))}async function uD(f,$){let J=f.suppressNextTerminalEventBySession.get($.payload.sessionId),W=J===$.payload.reason||J==="run.start.reply";if(W)f.suppressNextTerminalEventBySession.delete($.payload.sessionId);let[H,Q]=await Promise.all([If(f,$.payload.sessionId),xf(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let Z=await jX(H);f.publish(f.buildEvent("ui.notify",Z,$.payload.sessionId))}if(W)return;f.publish(f.buildEvent($.payload.reason==="aborted"?"run.aborted":$.payload.reason==="error"||$.payload.reason==="failed"?"run.failed":"run.completed",{reason:$.payload.reason,...Q?{snapshot:Q}:{}},$.payload.sessionId))}import{createSessionId as OX,parseRuntimeConfigExtensions as NX}from"@cline/shared";var LX={};N(LX,{SessionVersioningService:()=>j$,SessionVersioningError:()=>Df});var _X={};N(_X,{trimMessagesToCheckpoint:()=>MX,trimMessagesBeforeCheckpoint:()=>A9,readSessionCheckpointHistory:()=>K4,createRestoredCheckpointMetadata:()=>B9,createCheckpointRestorePlan:()=>R9,applyCheckpointToWorktree:()=>F9});import{execFile as cD}from"node:child_process";import{promisify as dD}from"node:util";var P2=dD(cD);function K4(f){let $=f?.metadata?.checkpoint&&typeof f.metadata.checkpoint==="object"&&!Array.isArray(f.metadata.checkpoint)?f.metadata.checkpoint:void 0;return(Array.isArray($?.history)?$.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let H=String(W.ref??"").trim(),Q=Number(W.createdAt??0),Z=Number(W.runCount??0);if(H.length===0||!Number.isFinite(Q)||!Number.isInteger(Z)||Z<1)return[];let j=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:H,createdAt:Q,runCount:Z,...j?{kind:j}:{}}]})}function B9(f,$){let J=K4(f).filter((H)=>H.runCount<=$),W=J.at(-1);return W?{latest:W,history:J}:void 0}function rD(f,$){return f.reduce((J,W)=>{if(W.runCount>$)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function DX(f,$){let J=0;for(let W=0;W<f.length;W+=1){let H=f[W];if(H?.role!=="user")continue;if(("metadata"in H&&H.metadata&&typeof H.metadata==="object"?H.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===$)return W}throw Error(`Could not find user message for checkpoint run ${$}`)}function MX(f,$){let J=DX(f,$);return f.slice(0,J+1)}function A9(f,$){let J=DX(f,$);return f.slice(0,J)}function R9(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=rD(K4(f.session),$);if(!J)throw Error(`No checkpoint found at or before run ${$} in session ${f.session.sessionId}`);let W=(f.cwd?.trim()||f.session.cwd||f.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:W,...f.restoreMessages!==!1?{messages:MX(f.messages??[],$)}:{}}}async function F9(f,$){if((await P2("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await P2("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await P2("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await P2("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await P2("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await P2("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}class Df extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function lD(f){let $=f.sessionId.trim();if(!$)throw new Df("invalid_restore","sessionId is required");if(!f.restoreMessages&&!f.restoreWorkspace)throw new Df("invalid_restore","restore.messages or restore.workspace must be true");if(f.restoreMessages&&f.requiresStart)throw new Df("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(f.checkpointRunCount)||f.checkpointRunCount<1)throw new Df("invalid_restore","checkpointRunCount must be a positive integer");return $}class j${async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,W=lD({sessionId:f.sessionId,restoreMessages:$,restoreWorkspace:J,requiresStart:f.start===void 0,checkpointRunCount:f.checkpointRunCount}),H=await f.getSession(W);if(!H)throw new Df("session_not_found",`Session ${W} not found`);let Q=$?await f.readMessages(W):void 0;if($&&Q?.length===0)throw new Df("session_messages_not_found",`No messages found for session ${W}`);let Z=R9({session:H,messages:Q,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??F9)(Z.cwd,Z.checkpoint);let j=$0({session:H,messages:Q});if(!$)return{checkpoint:Z.checkpoint,sourceSnapshot:j};let P=B9(H,f.checkpointRunCount),X=f.restore?.omitCheckpointMessageFromSession?A9(Q??[],f.checkpointRunCount):Z.messages??[],V={sourceSession:H,sourceMessages:Q,sourceSnapshot:j,plan:Z,restoredCheckpointMetadata:P,initialMessages:X,restoreMessages:$,restoreWorkspace:J,checkpointRunCount:f.checkpointRunCount};if(!f.start||!f.startSession)throw new Df("invalid_restore","start is required when restore.messages is true");let Y=f.buildStartInput?await f.buildStartInput(V,f.start):f.start,B=await f.startSession(Y),A=f.getStartedSessionId?.(B);if(A)await(f.retainCheckpointRefs??SQ)(Z.cwd,A,P?.history??[]);let R=A&&f.readRestoredSession?await f.readRestoredSession(A):void 0;return{sessionId:A,startResult:B,messages:Z.messages,checkpoint:Z.checkpoint,sourceSnapshot:j,...R?{restoredSnapshot:$0({session:R,messages:X})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as qm,HUB_COMPACTION_CAPABILITY as bm,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as wm,HUB_HOOK_CAPABILITY_PREFIX as Cm,HUB_MISTAKE_LIMIT_CAPABILITY as Em,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Sm,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as km,isHubToolExecutorName as pD}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as vm,HUB_COMPACTION_CAPABILITY as um,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as cm,HUB_HOOK_CAPABILITY_PREFIX as dm,HUB_MISTAKE_LIMIT_CAPABILITY as rm,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as lm,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as pm}from"@cline/shared";var iD=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function a$(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function nD(f,$){let J=typeof f.name==="string"?f.name.trim():"",W=typeof f.description==="string"?f.description:"",H=typeof f.capabilityName==="string"?f.capabilityName.trim():"",Q=a$(f.inputSchema);if(!J||!W||!Q||!H||$.has(H))return;return $.add(H),{kind:"tool",capabilityName:H,name:J,description:W,inputSchema:Q,...a$(f.lifecycle)?{lifecycle:a$(f.lifecycle)}:{}}}function K9(f){if(!Array.isArray(f))return[];let $=[],J=new Set;for(let W of f){if(!W||typeof W!=="object"||Array.isArray(W))continue;let H=W,Q=H.kind,Z=typeof H.capabilityName==="string"?H.capabilityName.trim():"";if(!Z||J.has(Z))continue;if(Q==="tool"){let j=nD(H,J);if(j)$.push(j);continue}if(Q==="toolExecutor"){let j=H.executor;if(!pD(j))continue;J.add(Z),$.push({kind:"toolExecutor",capabilityName:Z,executor:j});continue}if(Q==="hook"){let j=typeof H.name==="string"?H.name.trim():"";if(!j)continue;J.add(Z),$.push({kind:"hook",capabilityName:Z,name:j});continue}if(Q==="compaction"){J.add(Z),$.push({kind:"compaction",capabilityName:Z,...a$(H.config)?{config:a$(H.config)}:{}});continue}if(Q==="checkpoint"){J.add(Z),$.push({kind:"checkpoint",capabilityName:Z,...a$(H.config)?{config:a$(H.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(Z),$.push({kind:"mistakeLimit",capabilityName:Z});continue}if(Q==="userInstructionService")J.add(Z),$.push({kind:"userInstructionService",capabilityName:Z})}return $}function zX(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function aD(f){return Object.hasOwn(f,"update")?f.update:f}function U4(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function tD(f){let $=(f??[]).map(U4).filter(Boolean);return $.length>0?new Set($):void 0}function sD(f,$,J){if(!J)return!0;let W=U4(f),H=U4($),Q=W.includes(":")?W.split(":").at(-1)??W:W,Z=H.includes(":")?H.split(":").at(-1)??H:H;return J.has(W)||J.has(H)||J.has(Q)||J.has(Z)}function y9(f,$){let J=tD($);return f.records.skill.map((W)=>({id:W.id,name:W.item.name,description:"description"in W.item&&typeof W.item.description==="string"?W.item.description:void 0,disabled:W.item.disabled===!0,skill:W.item})).filter((W)=>sD(W.id,W.name,J))}function oD(f,$){let J=async(W,H)=>{let Q=U4(W),j=y9(f,$).filter((B)=>B.id===Q||U4(B.name)===Q||B.id.endsWith(`:${Q}`)).filter((B)=>!B.disabled);if(j.length!==1)return j.length>1?`Skill "${W}" is ambiguous. Use one of: ${j.map((B)=>B.id).join(", ")}`:`Skill "${W}" not found.`;let P=j[0].skill,X=H?.trim(),V=X?`
560
+ <command-args>${X}</command-args>`:"",Y=P.description?.trim()?`Description: ${P.description.trim()}
561
+
562
+ `:"";return`<command-name>${P.name}</command-name>${V}
563
+ <command-instructions>
564
+ ${Y}${P.instructions}
565
+ </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>y9(f,$).map(({skill:W,...H})=>H),enumerable:!0}),J}function eD(f,$,J,W){let H={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},Q=async()=>{let Z=await W(f,J.capabilityName,{},$);if(Z?.snapshot)H=Z.snapshot};return{start:Q,stop:()=>{},refreshType:async()=>{await Q()},listRecords:(Z)=>[...H.records[Z]],listRuntimeCommands:()=>[...H.runtimeCommands],resolveRuntimeSlashCommand:(Z)=>{if(!Z.startsWith("/")||Z.length<2)return Z;let P=Z.match(/^\/(\S+)/)?.[1];if(!P)return Z;let X=H.runtimeCommands.find((V)=>V.name===P);return X?`${X.instructions}${Z.slice(P.length+1)}`:Z},hasConfiguredSkills:(Z)=>y9(H,Z).some((j)=>!j.disabled),createExtension:(Z)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[Z.includeRules?"rules":void 0,Z.registerSkillsTool?"tools":void 0,Z.includeSkills||Z.includeWorkflows?"commands":void 0].filter((j)=>Boolean(j))},setup(j){if(Z.includeRules)j.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>x1(H.records.rule.map((P)=>P.item).filter((P)=>P.disabled!==!0))});if(Z.registerSkillsTool)j.registerTool(B$(oD(H,Z.allowedSkillNames)));for(let P of H.runtimeCommands.filter((X)=>X.kind==="skill"&&Z.includeSkills||X.kind==="workflow"&&Z.includeWorkflows))j.registerCommand({name:P.name,description:P.description,handler:(X)=>{let V=X.trim();return V?`${P.instructions}
566
+
567
+ ${V}`:P.instructions}})}})}}function fM(f,$,J,W){let H=J.map((Q)=>[Q.executor,async(...Z)=>{let j=Z.at(-1),P=Z.slice(0,-1);return(await W(f,Q.capabilityName,{executor:Q.executor,args:P,context:zX(j)},$))?.result}]);return H.length>0?Object.fromEntries(H):void 0}function $M(f,$,J,W){if(J.length===0)return;return J.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,lifecycle:H.lifecycle,async execute(Q,Z){return(await W(f,H.capabilityName,{toolName:H.name,input:Q,context:zX(Z)},$,Z.emitUpdate?(P)=>{Z.emitUpdate?.(aD(P))}:void 0))?.result}}))}function JM(f,$,J,W){let H=new Map(J.map((Z)=>[Z.name,Z])),Q={};for(let Z of iD){let j=H.get(Z);if(!j)continue;Q[Z]=async(P)=>{return(await W(f,j.capabilityName,{context:P},$))?.control}}return Object.keys(Q).length>0?Q:void 0}function U9(f){let $=f.contributions.filter((P)=>P.kind==="toolExecutor"),J=f.contributions.filter((P)=>P.kind==="tool"),W=f.contributions.filter((P)=>P.kind==="hook"),H=f.contributions.find((P)=>P.kind==="compaction"),Q=f.contributions.find((P)=>P.kind==="checkpoint"),Z=f.contributions.find((P)=>P.kind==="mistakeLimit"),j=f.contributions.find((P)=>P.kind==="userInstructionService");return{hasClientContributions:f.contributions.length>0,toolExecutors:fM(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...W.length>0?{hooks:JM(f.sessionId,f.targetClientId,W,f.requestCapability)}:{},...J.length>0?{extraTools:$M(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...H?{compaction:{...f.sessionConfig?.compaction??{},...H.config,compact:async(P)=>{return(await f.requestCapability(f.sessionId,H.capabilityName,{context:P},f.targetClientId))?.result}}}:{},...Q?{checkpoint:{...f.sessionConfig?.checkpoint??{},...Q.config,createCheckpoint:async(P)=>{return(await f.requestCapability(f.sessionId,Q.capabilityName,{context:P},f.targetClientId))?.result}}}:{},...Z?{onConsecutiveMistakeLimitReached:async(P)=>{return(await f.requestCapability(f.sessionId,Z.capabilityName,{context:P},f.targetClientId))?.result}}:{},...j?{userInstructionService:eD(f.sessionId,f.targetClientId,j,f.requestCapability)}:{}}}}var qX="hubCapabilityOwnerClientId";function bX(f,$){f[qX]=$}function WM(f){let $=f?.[qX];return typeof $==="string"&&$.trim()?$.trim():void 0}async function wX(f,$,J){let W=performance.now(),H={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};x("info","session.create.begin",H);let Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{},j=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0,P=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{};if(typeof j?.mode==="string")Z.mode=j.mode;else if(typeof P.mode==="string")Z.mode=P.mode;if(typeof j?.systemPrompt==="string")Z.systemPrompt=j.systemPrompt;else if(typeof P.systemPrompt==="string")Z.systemPrompt=P.systemPrompt;if(j?.checkpoint?.enabled===!0)Z.checkpointEnabled=!0;else if(P.checkpointEnabled===!0)Z.checkpointEnabled=!0;let X=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},V=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():"";if(!V)return x("warn","session.create.invalid",{...H,reason:"missing_workspace_root"}),m($,"invalid_session_create","session.create requires workspaceRoot or cwd");let Y=$.clientId?.trim()||"hub-client",B=K9(P.clientContributions);if(x("info","session.create.contributions_parsed",{...H,clientId:Y,workspaceRoot:V,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:B.length}),B.length>0)bX(Z,Y);let R=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||OX(),U=NX(P.configExtensions);x("info","session.create.runtime_build.begin",{...H,sessionId:R,configExtensionCount:U?.length??0});let y=U9({sessionId:R,targetClientId:Y,contributions:B,sessionConfig:j,requestCapability:f.requestCapability});x("info","session.create.start_session.begin",{...H,sessionId:R,provider:j?.providerId??(typeof X.provider==="string"?X.provider:typeof Z.provider==="string"?Z.provider:"hub"),model:j?.modelId??(typeof X.model==="string"?X.model:typeof Z.model==="string"?Z.model:"hub")});let F=await f.sessionHost.startSession({source:typeof Z.source==="string"?Z.source:void 0,interactive:Z.interactive!==!1,sessionMetadata:Object.keys(Z).length>0?Z:void 0,initialMessages:Array.isArray(Q.initialMessages)?Q.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...y.localRuntime},capabilities:{toolExecutors:y.toolExecutors,requestToolApproval:J},config:{...j??{},sessionId:R,providerId:j?.providerId??(typeof X.provider==="string"?X.provider:typeof Z.provider==="string"?Z.provider:"hub"),modelId:j?.modelId??(typeof X.model==="string"?X.model:typeof Z.model==="string"?Z.model:"hub"),apiKey:j?.apiKey??(typeof X.apiKey==="string"?X.apiKey:void 0),cwd:j?.cwd??(typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():V),workspaceRoot:j?.workspaceRoot??V,systemPrompt:j?.systemPrompt??(typeof P.systemPrompt==="string"?P.systemPrompt:""),mode:j?.mode??(P.mode==="plan"||P.mode==="yolo"?P.mode:"act"),maxIterations:j?.maxIterations??(typeof P.maxIterations==="number"?P.maxIterations:void 0),enableTools:j?.enableTools??P.enableTools!==!1,enableSpawnAgent:j?.enableSpawnAgent??P.enableSpawn!==!1,enableAgentTeams:j?.enableAgentTeams??P.enableTeams!==!1,checkpoint:j?.checkpoint??(P.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:j?.teamName??(typeof Z.teamName==="string"?Z.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):P.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});x("info","session.create.start_session.end",{...H,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!F.result}),gJ(f,F.sessionId,Y,"creator",{interactive:Z.interactive!==!1}),x("info","session.create.read_records.begin",{...H,sessionId:F.sessionId});let[K,M]=await Promise.all([If(f,F.sessionId),xf(f,F.sessionId)]);if(x("info","session.create.read_records.end",{...H,sessionId:F.sessionId,hasSession:!!K,hasSnapshot:!!M,elapsedMs:Math.round(performance.now()-W)}),K)f.publish(f.buildEvent("session.created",{session:K,...M?{snapshot:M}:{}},F.sessionId));return x("info","session.create.reply",{...H,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W)}),v($,{session:K,...M?{snapshot:M}:{}})}async function CX(f,$,J){let W=$.payload&&typeof $.payload==="object"?$.payload:{},H=typeof W.sessionId==="string"?W.sessionId.trim():$.sessionId?.trim()||"",Q=W.checkpointRunCount;if(!H)return m($,"invalid_restore","session.restore requires a session id");let Z=W.restore&&typeof W.restore==="object"?W.restore:{},j=Z.messages!==!1;if(typeof Q!=="number")return m($,"invalid_restore","checkpointRunCount must be a positive integer");try{let P=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(j&&!P)return m($,"invalid_restore","sessionConfig is required when restore.messages is true");let X=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},V=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{};if(typeof P?.mode==="string")V.mode=P.mode;else if(typeof X.mode==="string")V.mode=X.mode;if(typeof P?.systemPrompt==="string")V.systemPrompt=P.systemPrompt;else if(typeof X.systemPrompt==="string")V.systemPrompt=X.systemPrompt;if(P?.checkpoint?.enabled===!0)V.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)V.checkpointEnabled=!0;let Y=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},B=$.clientId?.trim()||"hub-client",A=K9(X.clientContributions);if(A.length>0)bX(V,B);let U=(typeof P?.sessionId==="string"?P.sessionId.trim():"")||OX(),y=NX(X.configExtensions),F=U9({sessionId:U,targetClientId:B,contributions:A,sessionConfig:P,requestCapability:f.requestCapability}),M=await new j$().restoreCheckpoint({sessionId:H,checkpointRunCount:Q,restore:{messages:Z.messages,workspace:Z.workspace,omitCheckpointMessageFromSession:Z.omitCheckpointMessageFromSession===!0},start:P,cwd:typeof P?.cwd==="string"&&P.cwd.trim()||typeof P?.workspaceRoot==="string"&&P.workspaceRoot.trim()||void 0,getSession:(z)=>f.sessionHost.getSession(z),readMessages:(z)=>f.sessionHost.readSessionMessages(z),buildStartInput:(z)=>{if(z.restoredCheckpointMetadata)V.checkpoint=z.restoredCheckpointMetadata;let u=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():z.sourceSession.workspaceRoot||z.sourceSession.cwd;return{source:typeof V.source==="string"?V.source:void 0,interactive:V.interactive!==!1,sessionMetadata:{...V,restoredFromSessionId:H,restoredCheckpointRunCount:Q},initialMessages:z.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:y,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...P??{},sessionId:U,providerId:P?.providerId??(typeof Y.provider==="string"?Y.provider:z.sourceSession.provider),modelId:P?.modelId??(typeof Y.model==="string"?Y.model:z.sourceSession.model),apiKey:P?.apiKey??(typeof Y.apiKey==="string"?Y.apiKey:""),cwd:P?.cwd??z.plan.cwd,workspaceRoot:P?.workspaceRoot??u,systemPrompt:P?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:P?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:P?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:P?.enableTools??X.enableTools!==!1,enableSpawnAgent:P?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:P?.enableAgentTeams??X.enableTeams!==!1,checkpoint:P?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:P?.teamName??(typeof V.teamName==="string"?V.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(z)=>f.sessionHost.startSession(z),getStartedSessionId:(z)=>z.sessionId,readRestoredSession:(z)=>f.sessionHost.getSession(z)});if(!j)return v($,{checkpoint:M.checkpoint});let h=M.startResult;if(!h)return m($,"restore_failed","Checkpoint restore did not start a session");gJ(f,h.sessionId,B,"creator",{interactive:V.interactive!==!1});let[G,T]=await Promise.all([If(f,h.sessionId),xf(f,h.sessionId)]);if(G)f.publish(f.buildEvent("session.created",{session:G,...T?{snapshot:T}:{}},h.sessionId));return v($,{session:G,...T?{snapshot:T}:{},messages:M.messages??[],checkpoint:M.checkpoint})}catch(P){if(P instanceof Df)return m($,P.code,P.code==="session_not_found"?`Unknown session: ${H}`:P.message);return m($,"restore_failed",P instanceof Error?P.message:String(P))}}async function EX(f,$){let J=hf($);if(!J)return m($,"invalid_session_attach","session.attach requires a session id");gJ(f,J,$.clientId?.trim()||"hub-client","participant");let W=await If(f,J);if(W)f.publish(f.buildEvent("session.attached",{session:W},J));return W?v($,{session:W}):m($,"session_not_found",`Unknown session: ${J}`)}async function SX(f,$){let J=hf($);if(!J)return m($,"invalid_session_detach","session.detach requires a session id");let W=$.clientId?.trim()||"hub-client",[H]=await Promise.all([If(f,J)]),Q=WM(H?.metadata)??W,Z=f.sessionState.get(J);if(Z){if(Z.participants.delete(W),Z.createdByClientId===W)Z.createdByClientId=Q;if(Z.participants.size===0)f.sessionState.delete(J)}Z$(f,(X)=>X.sessionId===J&&X.targetClientId===W,`Capability owner client ${W} detached before request was resolved.`);let[j,P]=await Promise.all([If(f,J),xf(f,J)]);return f.publish(f.buildEvent("session.detached",j?{session:j,...P?{snapshot:P}:{},clientId:W}:{clientId:W},J)),v($)}async function kX(f,$){let J=hf($),W=$.payload?.includeSnapshot===!0,[H,Q]=await Promise.all([If(f,J),W?xf(f,J):Promise.resolve(void 0)]);return H?v($,{session:H,...Q?{snapshot:Q}:{}}):m($,"session_not_found",`Unknown session: ${J}`)}async function mX(f,$){let J=hf($);if(!J)return m($,"invalid_session_id","session.messages requires a session id");if(!await If(f,J))return m($,"session_not_found",`Unknown session: ${J}`);let H=await f.sessionHost.readSessionMessages(J);return v($,{sessionId:J,messages:H})}async function IX(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,H=(await f.sessionHost.listSessions(J)).map((Q)=>IJ(Q,f.sessionState.get(Q.sessionId)));return v($,{sessions:H})}async function xX(f,$){let J=hf($),W=xJ($.payload?.metadata),H=await f.sessionHost.updateSession(J,{metadata:W}),[Q,Z]=await Promise.all([If(f,J),xf(f,J)]);if(Q)f.publish(f.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J));return{version:$.version,requestId:$.requestId,ok:H.updated,payload:{updated:H.updated,session:Q,...Z?{snapshot:Z}:{}}}}async function gX(f,$){let J=hf($),W=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),v($,{deleted:W})}async function vX(f,$){let J=hf($),W=f.sessionHost.pendingPrompts;if(!W)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let H=await W.list({sessionId:J});return v($,{sessionId:J,prompts:H})}async function uX(f,$){let J=hf($),W=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",H=typeof $.payload?.prompt==="string"?$.payload.prompt:void 0,Q=$.payload?.delivery==="queue"||$.payload?.delivery==="steer"?$.payload.delivery:void 0,Z=f.sessionHost.pendingPrompts;if(!Z)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await Z.update({sessionId:J,promptId:W,prompt:H,delivery:Q});return v($,j)}async function cX(f,$){let J=hf($),W=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",H=f.sessionHost.pendingPrompts;if(!H)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let Q=await H.delete({sessionId:J,promptId:W});return v($,Q)}function dX(f){switch(f){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var QM=new Set(["skills","workflows","rules","tools"]);function G9(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function G4(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function ZM(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function rX(f){if(f===void 0)return{};if(!G9(f))throw Error("settings.list payload must be an object.");return{cwd:G4(f,"cwd"),workspaceRoot:G4(f,"workspaceRoot"),availabilityContext:G9(f.availabilityContext)?f.availabilityContext:void 0}}function jM(f){if(!G9(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!QM.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools.");return{...rX(f),type:$,id:G4(f,"id"),path:G4(f,"path"),name:G4(f,"name"),enabled:ZM(f,"enabled")}}class X2{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=HM("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new Z0({sessionService:new Q0(new W0),fetch:f.fetch,telemetry:f.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,sessionHost:this.sessionHost,publish:($)=>this.publish($),buildEvent:n$,requestCapability:($,J,W,H,Q)=>VX(this.ctx,$,J,W,H,Q)},this.schedules=new H2({...f.scheduleOptions,runtimeHandlers:f.runtimeHandlers,eventPublisher:($,J)=>{let W=$==="schedule.execution.completed"?"schedule.execution_completed":$==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!W)return;this.publish(n$(W,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new W2(this.schedules),this.settings=f.settingsService??new e0,f.cronOptions)this.cronService=new n8({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{hX(this.ctx,$).catch((J)=>{Y9("session event handling failed",J)})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(f){console.error("[hub] cron service start failed",f)}}async stop(){for(let f of this.pendingApprovals.keys())X9(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(Z$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch(f){console.error("[hub] cron service stop failed",f)}}async handleCommand(f){switch(f.command){case"client.register":return RX(this.ctx,f);case"client.update":return FX(this.ctx,f);case"client.unregister":return yX(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return KX(this.ctx,f);case"session.create":return await wX(this.ctx,f,($)=>P9(this.ctx,$));case"session.restore":return await CX(this.ctx,f,($)=>P9(this.ctx,$));case"session.attach":return await EX(this.ctx,f);case"session.detach":return await SX(this.ctx,f);case"session.get":return await kX(this.ctx,f);case"session.messages":return await mX(this.ctx,f);case"session.list":return await IX(this.ctx,f);case"session.update":return await xX(this.ctx,f);case"session.pending_prompts":return await vX(this.ctx,f);case"session.update_pending_prompt":return await uX(this.ctx,f);case"session.remove_pending_prompt":return await cX(this.ctx,f);case"session.delete":return await gX(this.ctx,f);case"session.hook":return await TX(this.ctx,f);case"run.start":case"session.send_input":return await UX(this.ctx,f);case"run.abort":return await GX(this.ctx,f);case"capability.request":return await BX(this.ctx,f);case"approval.respond":return await PX(this.ctx,f);case"capability.respond":return AX(this.ctx,f);case"capability.progress":return YX(this.ctx,f);case"ui.notify":return this.publish(n$("ui.notify",f.payload??{})),v(f);case"ui.show_window":return this.publish(n$("ui.show_window",f.payload??{})),v(f);case"settings.list":return await this.handleSettingsList(f);case"settings.toggle":return await this.handleSettingsToggle(f);case"settings.get":case"settings.patch":return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"not_implemented",message:`${f.command} is not implemented yet.`}};default:{let $=await this.scheduleCommands.handleCommand(f);if($.ok){let J=dX(f.command);if(J)this.publish(n$(J,$.payload))}return $}}}async handleSettingsList(f){try{let $=await this.settings.list(rX(f.payload));return{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_list_failed",message:$ instanceof Error?$.message:String($)}}}}async handleSettingsToggle(f){try{let $=await this.settings.toggle(jM(f.payload));return this.publish(n$("settings.changed",{types:$.changedTypes,snapshot:$.snapshot})),{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$.snapshot,changedTypes:$.changedTypes}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_toggle_failed",message:$ instanceof Error?$.message:String($)}}}}subscribe(f,$,J){let W=this.listeners.get(f)??new Set,H={sessionId:J?.sessionId,listener:$};return W.add(H),this.listeners.set(f,W),()=>{let Q=this.listeners.get(f);if(!Q)return;if(Q.delete(H),Q.size===0)this.listeners.delete(f)}}detachClientFromSessions(f){for(let[$,J]of this.sessionState.entries())if(J.participants.delete(f),J.participants.size===0)this.sessionState.delete($);Z$(this.ctx,($)=>$.targetClientId===f,`Capability owner client ${f} disconnected before request was resolved.`)}publish(f){for(let $ of this.listeners.values())for(let J of $){if(J.sessionId&&J.sessionId!==f.sessionId)continue;try{J.listener(f)}catch(W){Y9(`listener threw while publishing ${f.event}`,W)}}}}import{timingSafeEqual as YM}from"node:crypto";import BM from"node:http";import AM from"node:net";import{URL as iX}from"node:url";import{WebSocketServer as RM}from"ws";import{HUB_COMMAND_SLOW_LOG_MS as PM,resolveHubCommandTimeoutMs as XM,safeJsonParse as VM}from"@cline/shared";function lX(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function pX(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class T4{transport;constructor(f){this.transport=f}attach(f){let $=new Map,J=new Set,W=!1,H=(P)=>{try{f.send(JSON.stringify(P))}catch(X){console.error(`[hub] failed to send websocket frame: ${X instanceof Error?X.stack||X.message:String(X)}`)}},Q=(P)=>{H({kind:"event",envelope:P})},Z=async(P)=>{try{let X=JSON.parse(P.data);switch(X.kind){case"command":{let V=performance.now(),Y=!1,B=lX(X);x("info","command.start",B);let A=setTimeout(()=>{if(Y)return;x("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-V)})},PM),R=this.transport.command(X.envelope);R.then((h)=>{if(!Y)return;x(h.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-V),ok:h.ok,errorCode:h.error?.code,errorMessage:h.error?.message})},(h)=>{if(!Y)return;x("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-V),error:h})});let U=!1,y,F,K=XM(X.envelope.command,X.envelope.timeoutMs);try{F=K===null?await R:await Promise.race([R,new Promise((h)=>{y=setTimeout(()=>{U=!0,h(pX(X,"hub_command_timeout",`Hub command ${X.envelope.command} did not complete within ${K}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${X.envelope.requestId}.`))},K)})])}catch(h){if(clearTimeout(A),y)clearTimeout(y);throw h}if(Y=U,clearTimeout(A),y)clearTimeout(y);let M=Math.round(performance.now()-V);if(U)x("error","command.timeout",{...B,durationMs:M,timeoutMs:K});else x(F.ok?"info":"warn","command.end",{...B,durationMs:M,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(X.envelope.command==="client.register"&&F.ok){let G=(X.envelope.payload??{}).clientId?.trim()||X.envelope.clientId?.trim();if(G)J.add(G)}else if(X.envelope.command==="client.unregister"&&F.ok){let h=X.envelope.clientId?.trim();if(h)J.delete(h)}H({kind:"reply",envelope:F});break}case"stream.subscribe":{let V=`${X.clientId}:${X.sessionId??"*"}`;if($.has(V))break;let Y=await this.transport.subscribe(X.clientId,Q,{sessionId:X.sessionId});$.set(V,Y);break}case"stream.unsubscribe":{let V=`${X.clientId}:${X.sessionId??"*"}`;$.get(V)?.(),$.delete(V);break}case"reply":case"event":break}}catch(X){let V=typeof P.data==="string"?VM(P.data):void 0;if(!V||V.kind!=="command"){x("error","rejected malformed websocket frame",{error:X});return}x("error","command.error",{...lX(V),error:X}),H({kind:"reply",envelope:pX(V,"command_failed",X instanceof Error?X.message:"Unknown hub error")})}},j=()=>{if(W)return;W=!0;for(let P of $.values())P();$.clear();for(let P of J)this.transport.command({version:"v1",command:"client.unregister",clientId:P});J.clear(),f.removeEventListener("message",Z),f.removeEventListener("close",j)};return f.addEventListener("message",Z),f.addEventListener("close",j),j}}class h4{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function FM(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();return String(f)}function yM(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(W)=>{J({data:FM(W)})});return}f.on("close",J)},removeEventListener(){}}}function KM(f){try{f.write(`HTTP/1.1 400 Bad Request\r
568
+ Connection: close\r
569
+ Content-Length: 0\r
570
+ \r
571
+ `),f.end()}catch{f.destroy()}}function UM(f){try{f.write(`HTTP/1.1 401 Unauthorized\r
572
+ Connection: close\r
573
+ Content-Length: 0\r
574
+ \r
575
+ `),f.end()}catch{f.destroy()}}function nX(f,$){if(!f||!$)return!1;let J=Buffer.from(f,"utf8"),W=Buffer.from($,"utf8");return J.length===W.length&&YM(J,W)}function aX(f,$){let J=f&&typeof f==="object"&&"code"in f&&typeof f.code==="string"?f.code:void 0,W=f instanceof Error?f.message:typeof f==="string"?f:"Unknown startup error",H=`Failed to start hub server on ${$.host}:${$.port}${$.pathname}: ${W}`,Q=Error(J?`${H} (${J})`:H);if(J)f.code=J,Q.code=J;if(f instanceof Error&&f.stack)Q.stack=`${Q.name}: ${Q.message}
576
+ Caused by: ${f.stack}`;return Q}async function GM(f){return await new Promise(($,J)=>{let W=AM.createServer();W.once("error",J),W.listen(0,f,()=>{let H=W.address();if(!H||typeof H==="string"){W.close(()=>J(Error("Failed to resolve free port")));return}let Q=H.port;W.close((Z)=>{if(Z){J(Z);return}$(Q)})})})}function TM(f){return f instanceof Error&&"code"in f&&f.code==="EADDRINUSE"}var T9=new Map,tX="cline-hub-auth.",hM=30000;function sX(f){return Array.isArray(f)?f.join(","):f??""}function DM(f){let $=sX(f).trim();return/^Bearer\s+(.+)$/i.exec($)?.[1]?.trim()||null}function MM(f){for(let $ of sX(f).split(",")){let J=$.trim();if(J.startsWith(tX))return J.slice(tX.length).trim()||null}return null}async function t$(f){let $=f.owner??M0(),J=f.host??"127.0.0.1",W=f.pathname??"/hub",H=f.port??v1(),Q=H===0?await GM(J):H,Z=Q,j=lf(J,Q,W),P=J$(),X=yJ(),V=new X2(f);await V.start();let Y=new T4(new h4(V)),B=new Set,A=new Date().toISOString(),R={protocolVersion:"v1",buildId:P,pid:process.pid,startedAt:A},U=new Set,y,F,K=async()=>{if(F)return F;return F=(async()=>{if(y)clearInterval(y),y=void 0;for(let T of U)T.terminate?.();U.clear();for(let T of B)T();if(B.clear(),await new Promise((T,z)=>{h.close((u)=>{if(u){z(u);return}T()})}),await new Promise((T,z)=>{M.close((u)=>{if(u){z(u);return}T()})}),await V.stop(),(await Zf($.discoveryPath))?.url===j)await Ef($.discoveryPath)})(),F},M=BM.createServer((G,T)=>{if((G.url??"/")==="/health"){let u=JSON.stringify({hubId:V.getHubId(),...R,authToken:"",host:J,port:Z,url:j,updatedAt:new Date().toISOString()});T.statusCode=200,T.setHeader("content-type","application/json"),T.end(u);return}if((G.url??"/")==="/version"){T.statusCode=200,T.setHeader("content-type","application/json"),T.end(JSON.stringify(R));return}if(new iX(G.url??"/",`http://${J}:${Z}`).pathname==="/shutdown"&&G.method==="POST"){if(!nX(DM(G.headers.authorization),X)){T.statusCode=401,T.end("Unauthorized");return}T.statusCode=202,T.setHeader("content-type","application/json"),T.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{K()});return}T.statusCode=404,T.end("Not found")}),h=new RM({noServer:!0});y=setInterval(()=>{for(let G of U){if(G.isAlive===!1){try{G.terminate?.()}catch{}U.delete(G);continue}G.isAlive=!1;try{G.ping?.()}catch{try{G.terminate?.()}catch{}U.delete(G)}}},hM),M.on("upgrade",(G,T,z)=>{if(new iX(G.url??"/",`http://${J}:${Z}`).pathname!==W){T.destroy();return}if(!nX(MM(G.headers["sec-websocket-protocol"]),X)){UM(T);return}try{h.handleUpgrade(G,T,z,(vf)=>{let a=vf;a.isAlive=!0,a.on("pong",()=>{a.isAlive=!0}),U.add(a);let c=Y.attach(yM(vf));B.add(c),vf.once("close",()=>{U.delete(a),c(),B.delete(c)})})}catch{KM(T)}});try{await new Promise((G,T)=>{M.once("error",(z)=>{T(aX(z,{host:J,port:Q,pathname:W}))}),M.listen(Q,J,()=>{let z=M.address();if(!z||typeof z==="string"){T(aX(Error("Failed to resolve hub port"),{host:J,port:Q,pathname:W}));return}Z=z.port,j=lf(J,Z,W),G()})})}catch(G){if(y)clearInterval(y),y=void 0;throw await V.stop().catch(()=>{return}),G}return await KJ($.discoveryPath,{hubId:V.getHubId(),protocolVersion:"v1",buildId:P,authToken:X,host:J,port:Z,url:j,pid:process.pid,startedAt:A,updatedAt:A}),{host:J,port:Z,url:j,authToken:X,close:K}}async function vJ(f){let $=f.owner??M0(),J=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=f.host??"127.0.0.1",H=f.port??v1(),Q=f.pathname??"/hub",Z=lf(W,H,Q),j=$.discoveryPath,P=(V)=>{if(!J)W$(V.url,V.authToken);return V},X=T9.get(j);if(X){let V=await X;if(V.url===Z)return P({server:V,url:V.url,authToken:V.authToken,action:"reuse"})}return await UJ($.discoveryPath,async()=>{let V=await Zf($.discoveryPath);if(V?.url&&(V.url===Z||f.allowPortFallback===!0)){let R=await Bf(V.url);if(R?.url&&await f0(R.url,{authToken:V.authToken}))return P({url:R.url,authToken:V.authToken,action:"reuse"})}if((await Bf(Z))?.url||V?.url)await Ef($.discoveryPath);let A=async(R)=>{let U=t$({...R,owner:$});T9.set(j,U);try{let y=await U;return P({server:y,url:y.url,authToken:y.authToken,action:"started"})}catch(y){throw T9.delete(j),y}};try{return await A(f)}catch(R){if(!f.allowPortFallback||!TM(R))throw R;return await A({...f,port:0})}})}async function oX(f){let $=Sf({host:f.host,port:f.port,pathname:f.pathname});return await t$({...f,...$,owner:Qf()})}async function eX(f){let $=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=Sf({host:f.host,port:f.port,pathname:f.pathname});return await vJ({...f,...J,allowPortFallback:f.allowPortFallback??!$,owner:Qf()})}var PV={};N(PV,{createTeamName:()=>cJ,DefaultRuntimeBuilder:()=>B2});import{hasRuntimeConfigExtension as IM}from"@cline/shared";import{nanoid as xM}from"nanoid";G0();var ZV={};N(ZV,{createLocalTeamStore:()=>_9,SqliteTeamStore:()=>s$,FileTeamStore:()=>D4});import{appendFileSync as _M,existsSync as V2,mkdirSync as $V,readdirSync as LM,readFileSync as JV,renameSync as zM,writeFileSync as OM}from"node:fs";import{join as h9}from"node:path";import{resolveTeamDataDir as NM}from"@cline/shared/storage";function WV(){return new Date().toISOString()}function D9(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function HV(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class D4{teamDirPath;constructor(f={}){this.teamDirPath=f.teamDir??NM()}init(){this.ensureTeamDir()}listTeamNames(){if(!V2(this.teamDirPath))return[];return LM(this.teamDirPath,{withFileTypes:!0}).filter((f)=>f.isDirectory()).filter((f)=>V2(this.statePath(f.name))).map((f)=>f.name).sort()}readState(f){let $=this.readEnvelope(f);return $?.teamState?HV($.teamState):void 0}readHistory(f,$=200){let J=this.historyPath(f);if(!V2(J))return[];return JV(J,"utf8").split(`
577
+ `).map((W)=>W.trim()).filter(Boolean).map((W)=>{try{return JSON.parse(W)}catch{return}}).filter((W)=>W!==void 0).reverse().slice(0,$)}loadRuntime(f){let $=this.readEnvelope(f);return{state:$?.teamState?HV($.teamState):void 0,teammates:$?.teammates??[],interruptedRunIds:[]}}handleTeamEvent(f,$){this.ensureTeamSubdir(f),_M(this.historyPath(f),`${JSON.stringify({ts:WV(),eventType:$.type,payload:$})}
578
+ `,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let W={version:1,updatedAt:WV(),teamState:$,teammates:J},H=this.statePath(f),Q=`${H}.tmp`;OM(Q,`${JSON.stringify(W,null,2)}
579
+ `,"utf8"),zM(Q,H)}markInProgressRunsInterrupted(f,$){let J=this.readEnvelope(f);if(!J?.teamState?.runs?.length)return[];let W=J.teamState.runs.filter((Q)=>Q.status==="queued"||Q.status==="running").map((Q)=>Q.id);if(W.length===0)return[];let H=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((Q)=>Q.status==="queued"||Q.status==="running"?{...Q,status:"interrupted",error:$,endedAt:H}:Q)},this.persistRuntime(f,J.teamState,J.teammates),W}ensureTeamDir(){if(!V2(this.teamDirPath))$V(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(f){let $=h9(this.ensureTeamDir(),D9(f));if(!V2($))$V($,{recursive:!0});return $}statePath(f){return h9(this.ensureTeamDir(),D9(f),"state.json")}historyPath(f){return h9(this.ensureTeamDir(),D9(f),"task-history.jsonl")}readEnvelope(f){let $=this.statePath(f);if(!V2($))return;try{let J=JSON.parse(JV($,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as qM,mkdirSync as bM}from"node:fs";import{join as wM}from"node:path";import{safeJsonParse as QV}from"@cline/shared";import{loadSqliteDb as CM,nowIso as M9}from"@cline/shared/db";import{resolveDbDataDir as EM}from"@cline/shared/storage";function SM(){return EM()}function Y2(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function kM(f){let $=QV(f);if(!Array.isArray($))return[];let J=[];for(let W of $){if(!W||typeof W!=="object")continue;let H=W,Q=H.agentId,Z=H.rolePrompt;if(typeof Q!=="string"||!Q.trim())continue;if(typeof Z!=="string"||!Z.trim())continue;let j={agentId:Q.trim(),rolePrompt:Z};if(typeof H.modelId==="string"&&H.modelId.trim())j.modelId=H.modelId.trim();if(typeof H.maxIterations==="number"&&Number.isFinite(H.maxIterations))j.maxIterations=Math.max(1,Math.floor(H.maxIterations));J.push(j)}return J}function mM(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class s${teamDirPath;db;constructor(f={}){this.teamDirPath=f.teamDir??SM()}init(){this.getRawDb()}ensureTeamDir(){if(!qM(this.teamDirPath))bM(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return wM(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let f=CM(this.dbPath());return this.ensureSchema(f),this.db=f,f}ensureSchema(f){if(f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec(`
580
+ CREATE TABLE IF NOT EXISTS team_store_schema_version (
581
+ lock INTEGER PRIMARY KEY CHECK (lock = 1),
582
+ version INTEGER NOT NULL
583
+ );
584
+ `),!f.prepare("SELECT version FROM team_store_schema_version WHERE lock = 1").get())f.prepare("INSERT INTO team_store_schema_version (lock, version) VALUES (1, 1)").run();f.exec(`
585
+ CREATE TABLE IF NOT EXISTS team_events (
586
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
587
+ team_name TEXT NOT NULL,
588
+ ts TEXT NOT NULL,
589
+ event_type TEXT NOT NULL,
590
+ payload_json TEXT NOT NULL,
591
+ causation_id TEXT,
592
+ correlation_id TEXT
593
+ );
594
+ `),f.exec(`
595
+ CREATE INDEX IF NOT EXISTS idx_team_events_name_ts
596
+ ON team_events(team_name, ts DESC);
597
+ `),f.exec(`
598
+ CREATE TABLE IF NOT EXISTS team_runtime_snapshot (
599
+ team_name TEXT PRIMARY KEY,
600
+ state_json TEXT NOT NULL,
601
+ teammates_json TEXT NOT NULL,
602
+ updated_at TEXT NOT NULL
603
+ );
604
+ `),f.exec(`
605
+ CREATE TABLE IF NOT EXISTS team_tasks (
606
+ team_name TEXT NOT NULL,
607
+ task_id TEXT NOT NULL,
608
+ title TEXT NOT NULL,
609
+ description TEXT NOT NULL,
610
+ status TEXT NOT NULL,
611
+ assignee TEXT,
612
+ depends_on_json TEXT NOT NULL,
613
+ summary TEXT,
614
+ version INTEGER NOT NULL DEFAULT 1,
615
+ updated_at TEXT NOT NULL,
616
+ PRIMARY KEY(team_name, task_id)
617
+ );
618
+ `),f.exec(`
619
+ CREATE TABLE IF NOT EXISTS team_runs (
620
+ team_name TEXT NOT NULL,
621
+ run_id TEXT NOT NULL,
622
+ agent_id TEXT NOT NULL,
623
+ task_id TEXT,
624
+ status TEXT NOT NULL,
625
+ message TEXT NOT NULL,
626
+ started_at TEXT,
627
+ ended_at TEXT,
628
+ error TEXT,
629
+ lease_owner TEXT,
630
+ heartbeat_at TEXT,
631
+ version INTEGER NOT NULL DEFAULT 1,
632
+ PRIMARY KEY(team_name, run_id)
633
+ );
634
+ `),f.exec(`
635
+ CREATE INDEX IF NOT EXISTS idx_team_runs_status
636
+ ON team_runs(team_name, status);
637
+ `),f.exec(`
638
+ CREATE TABLE IF NOT EXISTS team_outcomes (
639
+ team_name TEXT NOT NULL,
640
+ outcome_id TEXT NOT NULL,
641
+ title TEXT NOT NULL,
642
+ status TEXT NOT NULL,
643
+ schema_json TEXT NOT NULL,
644
+ finalized_at TEXT,
645
+ version INTEGER NOT NULL DEFAULT 1,
646
+ PRIMARY KEY(team_name, outcome_id)
647
+ );
648
+ `),f.exec(`
649
+ CREATE TABLE IF NOT EXISTS team_outcome_fragments (
650
+ team_name TEXT NOT NULL,
651
+ outcome_id TEXT NOT NULL,
652
+ fragment_id TEXT NOT NULL,
653
+ section TEXT NOT NULL,
654
+ source_agent_id TEXT NOT NULL,
655
+ source_run_id TEXT,
656
+ content TEXT NOT NULL,
657
+ status TEXT NOT NULL,
658
+ reviewed_by TEXT,
659
+ reviewed_at TEXT,
660
+ version INTEGER NOT NULL DEFAULT 1,
661
+ PRIMARY KEY(team_name, fragment_id)
662
+ );
663
+ `)}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}withTransaction(f){let $=this.getRawDb();$.exec("BEGIN IMMEDIATE;");try{f(),$.exec("COMMIT;")}catch(J){try{$.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((f)=>f.team_name)}readState(f){let $=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Y2(f)]);if(!$)return;let J=QV($.state_json);if(!J)return;try{return mM(J)}catch{return}}readHistory(f,$=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[Y2(f),$]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime(f){let $=Y2(f),J=this.readState($),W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[$]),H=W?kM(W.teammates_json):[];return{state:J,teammates:H,interruptedRunIds:[]}}appendTeamEvent(f,$,J,W){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
664
+ VALUES (?, ?, ?, ?, NULL, ?)`,[Y2(f),M9(),$,JSON.stringify(J),W??null])}persistRuntime(f,$,J){let W=Y2(f),H=M9();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
665
+ VALUES (?, ?, ?, ?)
666
+ ON CONFLICT(team_name) DO UPDATE SET
667
+ state_json = excluded.state_json,
668
+ teammates_json = excluded.teammates_json,
669
+ updated_at = excluded.updated_at`,[W,JSON.stringify($),JSON.stringify(J),H]);for(let Q of $.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
670
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
671
+ ON CONFLICT(team_name, task_id) DO UPDATE SET
672
+ title = excluded.title,
673
+ description = excluded.description,
674
+ status = excluded.status,
675
+ assignee = excluded.assignee,
676
+ depends_on_json = excluded.depends_on_json,
677
+ summary = excluded.summary,
678
+ version = team_tasks.version + 1,
679
+ updated_at = excluded.updated_at`,[W,Q.id,Q.title,Q.description,Q.status,Q.assignee??null,JSON.stringify(Q.dependsOn??[]),Q.summary??null,Q.updatedAt.toISOString()]);for(let Q of $.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
680
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
681
+ ON CONFLICT(team_name, run_id) DO UPDATE SET
682
+ agent_id = excluded.agent_id,
683
+ task_id = excluded.task_id,
684
+ status = excluded.status,
685
+ message = excluded.message,
686
+ started_at = excluded.started_at,
687
+ ended_at = excluded.ended_at,
688
+ error = excluded.error,
689
+ lease_owner = excluded.lease_owner,
690
+ heartbeat_at = excluded.heartbeat_at,
691
+ version = team_runs.version + 1`,[W,Q.id,Q.agentId,Q.taskId??null,Q.status,Q.message,Q.startedAt?Q.startedAt.toISOString():null,Q.endedAt?Q.endedAt.toISOString():null,Q.error??null,Q.leaseOwner??null,Q.heartbeatAt?Q.heartbeatAt.toISOString():null]);for(let Q of $.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
692
+ VALUES (?, ?, ?, ?, ?, ?, 1)
693
+ ON CONFLICT(team_name, outcome_id) DO UPDATE SET
694
+ title = excluded.title,
695
+ status = excluded.status,
696
+ schema_json = excluded.schema_json,
697
+ finalized_at = excluded.finalized_at,
698
+ version = team_outcomes.version + 1`,[W,Q.id,Q.title,Q.status,JSON.stringify({requiredSections:Q.requiredSections}),Q.finalizedAt?Q.finalizedAt.toISOString():null]);for(let Q of $.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
699
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
700
+ ON CONFLICT(team_name, fragment_id) DO UPDATE SET
701
+ outcome_id = excluded.outcome_id,
702
+ section = excluded.section,
703
+ source_agent_id = excluded.source_agent_id,
704
+ source_run_id = excluded.source_run_id,
705
+ content = excluded.content,
706
+ status = excluded.status,
707
+ reviewed_by = excluded.reviewed_by,
708
+ reviewed_at = excluded.reviewed_at,
709
+ version = team_outcome_fragments.version + 1`,[W,Q.outcomeId,Q.id,Q.section,Q.sourceAgentId,Q.sourceRunId??null,Q.content,Q.status,Q.reviewedBy??null,Q.reviewedAt?Q.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted(f,$){let J=Y2(f),W=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(W.length===0)return[];let H=M9();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
710
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[$,H,J]),W.map((Q)=>Q.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function _9(f={}){try{let $=new s$(f);return $.init(),$}catch{let $=new D4({teamDir:f.teamDir});return $.init(),$}}function L9(f,$){return IM(f,$)}function gM(f,$){let J=$?.["*"]??{},W=$?.[f]??{};return{...J,...W}.enabled!==!1}function vM(f,$){return f.filter((J)=>gM(J.name,$))}function jV(f,$){return z$(vM(f,$))}function cJ(){return`team-${xM(5)}`}function z9(f,$,J,W,H,Q,Z,j){let P=Nf[B0({mode:J})],X=j1($,W,J,H??Z1);return jV(T$({cwd:f,...P,enableSkills:!!Z,...X,executors:{...Z?{skills:Z}:{},...j??{}}}),Q)}function uM(f){return z9(f.cwd,f.providerId,f.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,cM,f.toolExecutors).some(($)=>$.name==="skills")}var cM=async()=>"";async function dM(f){let $=Q$();if(!s1({filePath:$}))return{tools:[]};let J=new r$({clientFactory:t1()}),W;try{W=await o1(J,{filePath:$})}catch(j){await J.dispose().catch(()=>{});let P=j instanceof Error?j.message:String(j);return f?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${P}`),{tools:[]}}let H=W.filter((j)=>j.disabled!==!0),Q=await Promise.allSettled(H.map((j)=>e1({serverName:j.name,provider:J}))),Z=[];for(let[j,P]of Q.entries())if(P.status==="fulfilled")Z.push(...P.value);else{let X=P.reason instanceof Error?P.reason.message:String(P.reason);f?.log(`[mcp] Failed to load tools from MCP server "${H[j].name}", skipping: ${X}`)}return{tools:Z,shutdown:async()=>{await J.dispose()}}}function rM(f,$){if(!f)return;for(let J of f.getTeammateIds())try{f.shutdownTeammate(J,$)}catch{}}function lM(f){if(f===void 0)return!0;switch(f){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function pM(f){let $=Nf[B0({mode:f.mode})];return{sessionId:f.sessionId||"",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",enableTools:f.enableTools!==!1,enableSpawnAgent:f.enableSpawnAgent??$.enableSpawnAgent??!0,enableAgentTeams:f.enableAgentTeams??$.enableAgentTeams??!0,disableMcpSettingsTools:f.disableMcpSettingsTools===!0,yolo:f.yolo===!0,missionLogIntervalSteps:typeof f.missionLogIntervalSteps==="number"&&Number.isFinite(f.missionLogIntervalSteps)?f.missionLogIntervalSteps:3,missionLogIntervalMs:typeof f.missionLogIntervalMs==="number"&&Number.isFinite(f.missionLogIntervalMs)?f.missionLogIntervalMs:120000}}class B2{teamRuntimeEntries=new Map;async build(f){let{config:$,hooks:J,extensions:W,logger:H,telemetry:Q,createSpawnTool:Z,onTeamRestored:j,userInstructionService:P,configExtensions:X,toolExecutors:V}=f,Y=f.onTeamEvent??(()=>{}),B=pM($),A=rf(),R=[],U=$.teamName?.trim()||cJ(),y=$.sessionId?.trim()||U,F=L9(X,"rules"),K=L9(X,"skills"),M=L9(X,"workflows"),h=F||K||M,G=!1,T=Boolean(P),z=P,u;if(!z&&h)z=o0({skills:{workspacePath:$.cwd},rules:{workspacePath:$.cwd},workflows:{workspacePath:$.cwd}});if(z)await z.start().catch(()=>{});let vf=B.enableTools&&K&&Boolean(z)&&(T||z?.hasConfiguredSkills($.skills)===!0)&&uM({cwd:$.cwd,providerId:$.providerId,mode:B.mode,modelId:$.modelId,toolRoutingRules:$.toolRoutingRules,toolPolicies:$.toolPolicies,toolExecutors:V}),a=z&&h?z.createExtension({includeRules:F,includeSkills:K,includeWorkflows:M,registerSkillsTool:vf,allowedSkillNames:$.skills}):void 0,c=a?[...W??$.extensions??[],a]:W??$.extensions;if(B.enableTools){if(R.push(...z9($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,V)),!B.disableMcpSettingsTools){let r=await dM($.logger);R.push(...r.tools),u=r.shutdown}}let d,t=B.enableAgentTeams?_9():void 0,nf=t?.loadRuntime(y),C=nf?.state,af=nf?.teammates??[],uf=new Map(af.map((r)=>[r.agentId,r])),$f=$.sessionId||U,R2,P$=[],X$=!1,e$=X1({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey??"",baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:J,extensions:c,logger:H??$.logger,telemetry:f.telemetry??$.telemetry,workspaceMetadata:$.workspaceMetadata});if(!this.teamRuntimeEntries.has($f))this.teamRuntimeEntries.set($f,{delegatedAgentConfigProvider:e$});let F2=()=>{if(!B.enableAgentTeams)return;let r=this.teamRuntimeEntries.get($f)??{delegatedAgentConfigProvider:e$};if(this.teamRuntimeEntries.set($f,r),d=r.runtime,!d){if(d=new d$({teamName:U,leadAgentId:$.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(e)=>{if(Y(e),d&&t){if(e.type==="teammate_spawned"&&e.teammate?.rolePrompt){let X0={agentId:e.agentId,rolePrompt:e.teammate.rolePrompt,modelId:e.teammate.modelId,maxIterations:e.teammate.maxIterations};uf.set(X0.agentId,X0)}if(e.type==="teammate_shutdown"&&!lM(e.reason))uf.delete(e.agentId);t.handleTeamEvent(y,e),t.persistRuntime(y,d.exportState(),Array.from(uf.values()))}}}),C)d.hydrateState(C),X$=!0;r.runtime=d}if(!G){if(!d)return;G=!0;let e=B1({runtime:d,leadAgentId:$.sessionId||"lead",restoredFromPersistence:Boolean(C),restoredTeammates:af,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(X0)=>{P$=X0,R2?.addTools(X0)},createBaseTools:B.enableTools?()=>z9($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,V):void 0,teammateConfigProvider:e$});if(X$)d.recoverActiveRuns("runtime_recovered");if(e.restoredFromPersistence)j?.();R.push(...e.tools)}return d};if(B.enableSpawnAgent&&Z){let r=Z();R.push({...r,execute:async(e,X0)=>{return F2(),r.execute(e,X0)}})}if(B.enableAgentTeams)F2();let z4=jV(R,$.toolPolicies),QW=z4.some((r)=>r.name===ff.SUBMIT_AND_EXIT&&r.lifecycle?.completesRun===!0),f1=B.enableAgentTeams?()=>{let r=this.teamRuntimeEntries.get($f)?.runtime;if(!r)return;let e=r.listTasks(),X0=e.some((N0)=>N0.status==="in_progress"||N0.status==="pending"),V3=r.listRuns({}),QY=V3.some((N0)=>N0.status==="running"||N0.status==="queued");if(X0||QY){let N0=e.filter((_f)=>_f.status==="in_progress"||_f.status==="pending").map((_f)=>`${_f.id} (${_f.status}): ${_f.title}`).join(", "),Y3=V3.filter((_f)=>_f.status==="running"||_f.status==="queued").map((_f)=>`${_f.id} (${_f.status})`).join(", "),ZW=[];if(N0)ZW.push(`Unfinished tasks: ${N0}`);if(Y3)ZW.push(`Active runs: ${Y3}`);return`[SYSTEM] You still have team obligations. ${ZW.join(". ")}. Use team_run_task to delegate work, or team_task with action=complete to mark tasks done, or team_await_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0,y2=QW?{requireCompletionTool:!0,...f1?{completionGuard:f1}:{}}:f1?{completionGuard:f1}:void 0;return{tools:z4,logger:H??$.logger,telemetry:Q??$.telemetry,teamRuntime:d,teamRestoredFromPersistence:Boolean(C),delegatedAgentConfigProvider:this.teamRuntimeEntries.get($f)?.delegatedAgentConfigProvider??e$,extensions:c,completionPolicy:y2,registerLeadAgent:(r)=>{if(R2=r,P$.length>0)r.addTools(z$(P$,[...A]))},shutdown:async(r)=>{if(rM(d,r),this.teamRuntimeEntries.delete($f),await u?.(),!T)z?.stop()}}}}var VV={};N(VV,{requestDesktopToolApproval:()=>N9});import{mkdir as iM,readFile as nM,unlink as aM,writeFile as tM}from"node:fs/promises";import{join as XV}from"node:path";function sM(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function oM(f){return new Promise(($)=>setTimeout($,f))}async function O9(f){try{await aM(f)}catch{}}async function N9(f,$={}){let J=$.approvalDir?.trim(),W=$.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await iM(J,{recursive:!0});let H=sM(`${f.toolCallId}`),Q=XV(J,`${W}.request.${H}.json`),Z=XV(J,`${W}.decision.${H}.json`),j=$.nowIso??(()=>new Date().toISOString());await tM(Q,`${JSON.stringify({requestId:H,sessionId:W,createdAt:j(),toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,iteration:f.iteration,agentId:f.agentId,conversationId:f.conversationId},null,2)}
711
+ `,"utf8");let P=$.timeoutMs??300000,X=$.pollIntervalMs??200,V=Date.now();while(Date.now()-V<P){try{let Y=await nM(Z,"utf8"),B=JSON.parse(Y),A={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([O9(Z),O9(Q)]),A}catch{}await oM(X)}return await O9(Q),{approved:!1,reason:"Tool approval request timed out"}}G0();var OV={};N(OV,{updateLocalProvider:()=>nJ,saveLocalProviderSettings:()=>m9,saveLocalProviderOAuthCredentials:()=>v9,resolveLocalClineAuthToken:()=>u9,refreshProviderModelsFromSource:()=>I9,normalizeOAuthProvider:()=>x9,loginLocalProvider:()=>g9,listLocalProviders:()=>S9,getProviderConfigFields:()=>c9,getLocalProviderModels:()=>k9,ensureCustomProvidersLoaded:()=>iJ,deleteLocalProvider:()=>aJ,addLocalProvider:()=>E9});import*as jf from"@cline/llms";import{isOAuthProviderId as T_}from"@cline/shared";import{existsSync as eM,mkdirSync as f_,readFileSync as $_,writeFileSync as J_}from"node:fs";import{mkdir as W_,readFile as H_,writeFile as Q_}from"node:fs/promises";import{dirname as q9,join as Z_}from"node:path";import*as Mf from"@cline/llms";import{ModelCapabilitySchema as j_,ProviderCapabilitySchema as P_,ProviderClientSchema as X_,ProviderProtocolSchema as V_}from"@cline/shared";import{z as p}from"zod";var Y_=p.object({id:p.string().optional(),name:p.string().optional(),capabilities:p.array(j_).optional(),supportsVision:p.boolean().optional(),supportsAttachments:p.boolean().optional(),supportsReasoning:p.boolean().optional()}).passthrough(),B_=p.object({name:p.string(),baseUrl:p.string(),defaultModelId:p.string().optional(),protocol:V_.optional(),client:X_.optional(),capabilities:p.array(P_).optional(),modelsSourceUrl:p.string().optional()}).passthrough(),YV=p.object({provider:B_.optional(),models:p.record(p.string(),Y_).optional()}).passthrough(),BV=p.object({version:p.literal(1),providers:p.record(p.string(),YV)}),A_=p.object({version:p.literal(1),providers:p.record(p.string(),p.unknown())}),dJ=new Set;function AV(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function o$(f){return Z_(q9(f.getFilePath()),"models.json")}function rJ(){return{version:1,providers:{}}}function RV(f){let $=A_.safeParse(f);if(!$.success)return rJ();let J={};for(let[W,H]of Object.entries($.data.providers)){let Q=YV.safeParse(H);if(Q.success)J[W]=Q.data}return{version:1,providers:J}}function b9(f){if(!eM(f))return rJ();try{let $=$_(f,"utf8");return RV(JSON.parse($))}catch{}return rJ()}async function A2(f){try{let $=await H_(f,"utf8");return RV(JSON.parse($))}catch{}return rJ()}function FV(f,$){f_(q9(f),{recursive:!0});let J=BV.parse($);J_(f,`${JSON.stringify(J,null,2)}
712
+ `,"utf8")}async function lJ(f,$){await W_(q9(f),{recursive:!0});let J=BV.parse($);await Q_(f,`${JSON.stringify(J,null,2)}
713
+ `,"utf8")}function yV(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function KV(f){if(!f||f.length===0)return;let $=new Set;if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("tools"))$.add("tools");return $.size>0?[...$]:void 0}function UV(f){let $=new Set;if(!f||f.length===0)return[...$];if(f.includes("streaming"))$.add("streaming");if(f.includes("tools"))$.add("tools");if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("vision"))$.add("images"),$.add("files");return[...$]}function R_(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function GV(f,$){return f??$??"openai-chat"}function TV(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function F_(f,$){let J=new Set($?.capabilities??[]);if($?.supportsVision)J.add("images");if($?.supportsAttachments)J.add("files");if($?.supportsReasoning)J.add("reasoning");return{id:f,name:$?.name??f,capabilities:J.size>0?[...J]:void 0}}function y_(f,$){for(let[J,W]of Object.entries($??{})){let H=W.id?.trim()||J.trim();if(!H)continue;Mf.registerModel(f,H,F_(H,W))}}function K_(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function U_(f){return Object.assign({},...Mf.resolveProviderModelCatalogKeys(f).map((J)=>Mf.getGeneratedModelsForProvider(J)))}function G_(f){let $=f.provider.trim();if(!$||Mf.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let W=Mf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],H=U_($),Q=UV(f.capabilities),Z=Q.length>0?Q:void 0,j=f.model?.trim(),P={...H,...W?.models??{}};if(j)P[j]=K_(j,P[j],Z);let X=Object.keys(P).filter(Boolean),V=j||X[0];if(!V)return;let Y=GV(f.protocol,W?.provider.protocol),B=TV(f.client,Y,W?.provider.client);Mf.registerProvider({provider:{id:$,name:W?.provider.name??AV($),description:W?.provider.description,protocol:Y,client:B,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:V,capabilities:KV(f.capabilities)??W?.provider.capabilities,source:"file"},models:P})}function pJ(f){for(let $ of Object.values(f.providers))G_($.settings)}function M4(f,$){let J=$.models??{};if(!R_($.provider)){y_(f,J);return}let W=UV($.provider.capabilities),H=Object.entries(J).map(([X,V])=>({id:V.id?.trim()||X.trim(),model:V})).filter(({id:X})=>X.length>0),Q=$.provider.defaultModelId?.trim()||H[0]?.id||"default",Z=GV($.provider.protocol,void 0),j=TV($.provider.client,Z,void 0),P=Object.fromEntries(H.map(({id:X,model:V})=>[X,{id:X,name:V.name??X,capabilities:W.length>0?W:void 0,status:"active"}]));Mf.registerProvider({provider:{id:f,name:$.provider.name.trim()||AV(f),protocol:Z,client:j,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:Q,capabilities:KV($.provider.capabilities),source:"file"},models:P})}function hV(f){let $=o$(f);if(dJ.has($))return;let J=b9($);for(let[W,H]of Object.entries(J.providers))M4(W,H);dJ.add($)}async function iJ(f){let $=o$(f);if(dJ.has($))return;let J=await A2($);for(let[W,H]of Object.entries(J.providers))M4(W,H);dJ.add($)}function h_(f){return f.apiKey??f.auth?.apiKey}function D_(f){return(f.auth?.accessToken?.trim()??"").length>0}function DV(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function M_(f){let $=f.split(/\s+/).filter(Boolean);if($.length===0)return"?";if($.length===1)return $[0].slice(0,2).toUpperCase();return`${$[0][0]}${$[1][0]}`.toUpperCase()}function __(f){let $=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let W of f)J=J*31+W.charCodeAt(0)>>>0;return $[J%$.length]}function MV(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>yV($,J))}async function L_(f,$){let J=await jf.getModelsForProvider(f);if(!$)return J;let W=await Y8(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return W?.knownModels?{...J,...W.knownModels}:J}function w9(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function _V(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function C9(f,$){let J=$?.includes("vision")??!1,W=$?.includes("reasoning")??!1;return Object.fromEntries(f.map((H)=>[H,{id:H,name:H,supportsVision:J,supportsAttachments:J,supportsReasoning:W}]))}async function LV(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await O6(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function zV(f,$){let J=f.read(),W=!1;if(J.providers[$])delete J.providers[$],W=!0;if(J.lastUsedProvider===$)delete J.lastUsedProvider,W=!0;if(W)f.write(J);jf.unregisterProvider($)}async function E9(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=$.baseUrl.trim(),H=$.apiKey?.trim()??"";if(!W&&!H){let R=o$(f);if((await A2(R)).providers[J]){let y=await aJ(f,{providerId:J});return{providerId:J,settingsPath:y.settingsPath,modelsPath:y.modelsPath,modelsCount:0}}return zV(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:R,modelsCount:0}}if(jf.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=$.name.trim();if(!Q)throw Error("name is required");if(!W)throw Error("baseUrl is required");let Z=w9($.models),j=$.modelsSourceUrl?.trim(),P=await LV({providerId:J,explicitModels:Z,modelsSourceUrl:j,shouldRecompute:!0});if(P.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let X=$.defaultModelId?.trim()&&P.includes($.defaultModelId.trim())?$.defaultModelId.trim():P[0],V=$.capabilities?.length?[...new Set($.capabilities)]:void 0,Y=_V($.headers);f.saveProviderSettings({provider:J,apiKey:H||void 0,baseUrl:W,headers:Y,timeout:$.timeoutMs,model:X,protocol:$.protocol,client:$.client},{setLastUsed:!1});let B=o$(f),A=await A2(B);return A.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:X,protocol:$.protocol,client:$.client,capabilities:V,modelsSourceUrl:j},models:C9(P,V)},await lJ(B,A),M4(J,A.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:B,modelsCount:P.length}}async function nJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=o$(f),H=await A2(W),Q=H.providers[J];if(!Q){let h=f.getProviderSettings(J);if(!h)throw Error(`provider "${J}" does not exist`);let G=$.modelsSourceUrl?.trim(),T=w9($.models)[0]??h.model?.trim();if(!T&&!G)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:$.name?.trim()||DV(J),baseUrl:$.baseUrl?.trim()??h.baseUrl?.trim()??"",defaultModelId:T,protocol:h.protocol,client:h.client,capabilities:h.capabilities},models:T?C9([T],h.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let Z=$.name?.trim()??Q.provider.name.trim();if(!Z)throw Error("name is required");let j=$.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!j)throw Error("baseUrl is required");let P=$.capabilities===void 0?Q.provider.capabilities:$.capabilities===null?void 0:[...new Set($.capabilities)],X=$.protocol===void 0?Q.provider.protocol:$.protocol??void 0,V=$.client===void 0?Q.provider.client:$.client??void 0,Y=w9($.models),B=$.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:$.modelsSourceUrl?.trim()||void 0,A=$.models!==void 0||$.modelsSourceUrl!==void 0&&!!B,R=Object.keys(Q.models??{}).map((h)=>h.trim()).filter(Boolean),U=await LV({providerId:J,explicitModels:Y,modelsSourceUrl:B,fallbackModelIds:R,shouldRecompute:A});if(U.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let y=$.defaultModelId===void 0?Q.provider.defaultModelId?.trim():$.defaultModelId?.trim(),F=y&&U.includes(y)?y:U[0],M={...f.getProviderSettings(J)??{},provider:J,baseUrl:j,model:F};if(X)M.protocol=X;else delete M.protocol;if(V)M.client=V;else delete M.client;if($.apiKey!==void 0){let h=$.apiKey?.trim()??"";if(h)M.apiKey=h;else delete M.apiKey}if($.headers!==void 0){let h=_V($.headers);if(h)M.headers=h;else delete M.headers}if($.timeoutMs!==void 0)if(typeof $.timeoutMs==="number")M.timeout=$.timeoutMs;else delete M.timeout;return f.saveProviderSettings(M,{setLastUsed:!1}),H.providers[J]={provider:{name:Z,baseUrl:j,defaultModelId:F,protocol:X,client:V,capabilities:P,modelsSourceUrl:B},models:C9(U,P)},await lJ(W,H),M4(J,H.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W,modelsCount:U.length}}async function aJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=o$(f),H=await A2(W);if(!H.providers[J])throw Error(`provider "${J}" does not exist`);return delete H.providers[J],await lJ(W,H),jf.unregisterProvider(J),zV(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W}}async function S9(f){let $=f.read(),J=jf.getProviderIds().sort((H,Q)=>H.localeCompare(Q));return{providers:await Promise.all(J.map(async(H)=>{let[Q,Z]=await Promise.all([jf.getProvider(H),jf.getModelsForProvider(H)]),j=MV(Z),P=$.providers[H]?.settings,X=Q?.name??DV(H);return{id:H,name:X,models:j.length,color:__(H),letter:M_(X),enabled:Boolean(P),apiKey:P?h_(P):void 0,oauthAccessTokenPresent:P?D_(P):void 0,baseUrl:P?.baseUrl??Q?.baseUrl,defaultModelId:Q?.defaultModelId,protocol:P?.protocol??Q?.protocol,client:P?.client??Q?.client,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:j}})),settingsPath:f.getFilePath()}}async function k9(f,$){let J=f.trim(),W=await L_(J,$),H=MV(W);return{providerId:J,models:H}}function m9(f,$){let J=$.providerId.trim();if($.enabled===!1){let Q=f.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return f.write(Q),{providerId:J,enabled:!1,settingsPath:f.getFilePath()}}let H={...f.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn($,Q)&&typeof $[Q]==="string")if($[Q].trim().length===0)delete H[Q];else H[Q]=$[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn($,Q))H[Q]=$[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn($,Q)&&$[Q]!=null)H[Q]={...typeof H[Q]==="object"&&H[Q]!=null?H[Q]:{},...$[Q]};return f.saveProviderSettings(H,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:f.getFilePath()}}async function I9(f,$){let J=$.trim(),W=f.getProviderSettings(J),Q=jf.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,Z=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),j=N6(Z,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!Z||!j)return{providerId:J,refreshed:!1};let P=await nJ(f,{providerId:J,name:Q.name,baseUrl:Z,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:j,protocol:W.protocol??Q.protocol??null,client:W.client??Q.client??null,capabilities:W.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:P.modelsCount}}function x9(f){let $=f.trim().toLowerCase();if($==="codex"||$==="openai-codex")return"openai-codex";if($==="cline"||$==="oca")return $;throw Error(`provider "${f}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function z_(f,$){if(f==="cline")return $.access.startsWith("workos:")?$.access:`workos:${$.access}`;return $.access}async function g9(f,$,J){let W=T8({onPrompt:async(H)=>H.defaultValue??"",openUrl:J,onOpenUrlError:({error:H})=>{throw H instanceof Error?H:Error(String(H))}});if(f==="cline")return k1({apiBaseUrl:$?.baseUrl?.trim()||"https://api.cline.bot",useWorkOSDeviceAuth:!0,callbacks:W});if(f==="oca")return N1({mode:$?.oca?.mode,callbacks:W});return m1(W)}function v9(f,$,J,W){let H={...J?.auth??{},accessToken:z_($,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:$},provider:$,auth:H};return f.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function u9(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var O_=new Set(["ollama","lmstudio","litellm"]);function N_(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return O_.has(f)}function c9(f){let $=jf.normalizeProviderId(f);if(T_($))return{providerId:$,authMethod:"oauth",fields:{}};let J=jf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=J?.provider.baseUrl,H={apiKey:{}};if(N_($,J))H.baseUrl={defaultValue:W};return{providerId:$,authMethod:"api-key",fields:H}}var CV={};N(CV,{resolveLegacyClineAuth:()=>wV,migrateLegacyProviderSettings:()=>_4});import{existsSync as q_,readFileSync as b_}from"node:fs";import{dirname as w_,join as d9}from"node:path";import*as qV from"@cline/llms";import{resolveClineDataDir as C_}from"@cline/shared/storage";var bV="openai";function wV(f){let $=f?.trim();if(!$)return;try{let J=JSON.parse($);if(!J)return;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:J.expiresAt,accountId:J.userInfo?.id}}catch{return}}function E(f){let $=f?.trim();return $?$:void 0}function NV(f){if(!q_(f))return;try{let $=b_(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function E_(f){let $=f.dataDir??C_(),J=f.globalStatePath??d9($,"globalState.json"),W=f.secretsPath??d9($,"secrets.json"),H=NV(J),Q=NV(W);if(!H&&!Q)return;return{globalState:H??{},secrets:Q??{}}}function S_(f){try{let J=new URL(f).hostname.toLowerCase();return J==="api.openai.com"||J.endsWith(".openai.azure.com")||J.endsWith(".services.ai.azure.com")}catch{return!1}}function k_(f){let $=E(f.openAiBaseUrl);if(!$)return!1;if(f.azureApiVersion||f.azureIdentity)return!1;return!S_($)}function r9(f,$){if(f==="openai"&&k_($))return bV;return f}function m_(f,$,J,W){let H=J==="plan"?"planMode":"actMode",Q=$===W?E(J==="plan"?f.planModeApiModelId:f.actModeApiModelId):void 0,j={openrouter:`${H}OpenRouterModelId`,cline:`${H}ClineModelId`,openai:`${H}OpenAiModelId`,ollama:`${H}OllamaModelId`,lmstudio:`${H}LmStudioModelId`,litellm:`${H}LiteLlmModelId`,requesty:`${H}RequestyModelId`,together:`${H}TogetherModelId`,fireworks:`${H}FireworksModelId`,sapaicore:`${H}SapAiCoreModelId`,groq:`${H}GroqModelId`,baseten:`${H}BasetenModelId`,huggingface:`${H}HuggingFaceModelId`,"huawei-cloud-maas":`${H}HuaweiCloudMaasModelId`,oca:`${H}OcaModelId`,aihubmix:`${H}AihubmixModelId`,hicap:`${H}HicapModelId`,nousResearch:`${H}NousResearchModelId`,"vercel-ai-gateway":`${H}VercelAiGatewayModelId`}[$];return(j?E(typeof f[j]==="string"?f[j]:void 0):void 0)??Q}function I_(f,$,J){let W=J==="plan"?f.planModeReasoningEffort:f.actModeReasoningEffort,H=J==="plan"?f.geminiPlanModeThinkingLevel:f.geminiActModeThinkingLevel,Q=J==="plan"?f.planModeThinkingBudgetTokens:f.actModeThinkingBudgetTokens,Z=($==="gemini"?H:void 0)??W,j=Z==="none"||Z==="low"||Z==="medium"||Z==="high"?Z:void 0,P=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&P===void 0)return;return{...j?{effort:j}:{},...P!==void 0?{budgetTokens:P}:{}}}function x_(f){let $=f["openai-codex-oauth-credentials"];if(!$)return;try{let J=JSON.parse($),W=E(J.access_token),H=E(J.refresh_token),Q=E(J.accountId);if(!W&&!H&&!Q)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...H?{refreshToken:H}:{},...Q?{accountId:Q}:{}}}}catch{return}}function g_(f){let $=qV.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function v_(f,$,J,W){let H=r9(f,$),Q=E(W==="plan"?$.planModeApiProvider:$.actModeApiProvider),Z=m_($,f,W,Q)??g_(H),j=I_($,H,W),P=typeof $.requestTimeoutMs==="number"&&Number.isInteger($.requestTimeoutMs)&&$.requestTimeoutMs>0?$.requestTimeoutMs:void 0,X={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey,sapaicore:J.sapAiCoreClientId},V={};if(f==="openai-codex")Object.assign(V,x_(J));if(f==="cline")try{let F=E(J["cline:clineAccountId"]);if(F)V.auth={...V.auth??{},...wV(F)}}catch{}if(f==="openai"&&$.openAiHeaders)V.headers=$.openAiHeaders;if(f==="bedrock")V.aws={accessKey:E(J.awsAccessKey),secretKey:E(J.awsSecretKey),sessionToken:E(J.awsSessionToken),region:E($.awsRegion),authentication:$.awsAuthentication,profile:$.awsUseProfile?E($.awsProfile):void 0,usePromptCache:$.awsBedrockUsePromptCache,useCrossRegionInference:$.awsUseCrossRegionInference,useGlobalInference:$.awsUseGlobalInference,endpoint:E($.awsBedrockEndpoint),customModelBaseId:E(W==="plan"?$.planModeAwsBedrockCustomModelBaseId:$.actModeAwsBedrockCustomModelBaseId)};if(f==="vertex")V.gcp={projectId:E($.vertexProjectId),region:E($.vertexRegion)};if(f==="openai"&&($.azureApiVersion||$.azureIdentity!==void 0))V.azure={apiVersion:E($.azureApiVersion),useIdentity:$.azureIdentity};if(f==="sapaicore")V.sap={clientId:E(J.sapAiCoreClientId),clientSecret:E(J.sapAiCoreClientSecret),tokenUrl:E($.sapAiCoreTokenUrl),resourceGroup:E($.sapAiResourceGroup),deploymentId:E(W==="plan"?$.planModeSapAiCoreDeploymentId:$.actModeSapAiCoreDeploymentId),useOrchestrationMode:$.sapAiCoreUseOrchestrationMode};if(f==="oca"){V.oca={mode:$.ocaMode};let F=E(J.ocaRefreshToken);if(F)V.auth={...V.auth??{},refreshToken:F}}if(f==="qwen")V.apiLine=$.qwenApiLine;if(f==="moonshot")V.apiLine=$.moonshotApiLine;if(f==="zai")V.apiLine=$.zaiApiLine;if(f==="minimax")V.apiLine=$.minimaxApiLine;let Y={anthropic:$.anthropicBaseUrl,openai:$.openAiBaseUrl,ollama:$.ollamaBaseUrl,lmstudio:$.lmStudioBaseUrl,litellm:$.liteLlmBaseUrl,gemini:$.geminiBaseUrl,requesty:$.requestyBaseUrl,asksage:$.asksageApiUrl,dify:$.difyBaseUrl,oca:$.ocaBaseUrl,aihubmix:$.aihubmixBaseUrl,sapaicore:$.sapAiCoreBaseUrl},B=E(X[f]),A=E(Y[f]),R={provider:H,...B?{apiKey:B}:{},...Z?{model:Z}:{},...A?{baseUrl:A}:{},...j?{reasoning:j}:{},...P?{timeout:P}:{},...V},U=R8.safeParse(R);if(!U.success)return;return Object.keys(R).filter((F)=>F!=="provider").length>0?U.data:void 0}function u_(f,$){if(f!==bV)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model}}}}function c_(f,$){let J=new Set;for(let W of[f.actModeApiProvider,f.planModeApiProvider]){let H=E(W);if(H)J.add(H)}if(E($.apiKey))J.add("anthropic");if(E($.openRouterApiKey))J.add("openrouter");if(E($.openAiApiKey))J.add("openai");if(E($.openAiNativeApiKey))J.add("openai-native");if(E($["openai-codex-oauth-credentials"]))J.add("openai-codex");if(E($.geminiApiKey))J.add("gemini");if(E($.ollamaApiKey))J.add("ollama");if(E($.awsAccessKey)||E($.awsBedrockApiKey))J.add("bedrock");if(E(f.vertexProjectId)||E(f.vertexRegion))J.add("vertex");if(E($.clineApiKey))J.add("cline");if(E($.ocaApiKey))J.add("oca");return J}function _4(f){let $=f.providerSettingsManager.read(),J=E_(f);if(!J)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let{globalState:W,secrets:H}=J,Q=W.mode==="plan"?"plan":"act",Z=c_(W,H),j=t0();j.providers={...$.providers},j.lastUsedProvider=$.lastUsedProvider;let P=new Date().toISOString(),X=0,V=d9(w_(f.providerSettingsManager.getFilePath()),"models.json"),Y=b9(V),B=0;for(let U of Z){let y=r9(U,W);if(j.providers[y])continue;let F=v_(U,W,H,Q);if(!F)continue;j.providers[y]={settings:F,updatedAt:P,tokenSource:"migration"},X+=1;let K=u_(y,F);if(K&&!Y.providers[y])Y.providers[y]=K,B+=1}if(X===0&&B===0)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let A=E(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),R=A?r9(A,W):void 0;if(j.lastUsedProvider=$.lastUsedProvider??(R&&j.providers[R]?R:Object.keys(j.providers)[0]),f.providerSettingsManager.write(j),B>0)FV(V,Y);return{migrated:X>0||B>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}Gf();SJ();var EV={};N(EV,{FileTeamPersistenceStore:()=>tJ});import{appendFileSync as d_,existsSync as l9,mkdirSync as r_,readFileSync as l_,renameSync as p_,unlinkSync as i_,writeFileSync as n_}from"node:fs";import{join as p9}from"node:path";import{resolveTeamDataDir as a_}from"@cline/shared/storage";function t_(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class tJ{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=t_(f.teamName),J=f.baseDir?.trim()||a_();this.dirPath=p9(J,$),this.statePath=p9(this.dirPath,"state.json"),this.taskHistoryPath=p9(this.dirPath,"task-history.jsonl")}loadState(){if(!l9(this.statePath))return;try{let f=l_(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return CP($.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec(f){this.teammateSpecs.set(f.agentId,f)}removeTeammateSpec(f){this.teammateSpecs.delete(f)}persist(f){if(!this.hasPersistableState(f)){this.clearPersistedState();return}this.ensureDir();let $={version:1,updatedAt:new Date().toISOString(),teamState:f.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;n_(J,`${JSON.stringify($,null,2)}
714
+ `,"utf8"),p_(J,this.statePath)}appendTaskHistory(f){let $={};switch(f.type){case"team_task_updated":$=f.task;break;case"team_message":$={agentId:f.message.fromAgentId,toAgentId:f.message.toAgentId,subject:f.message.subject,taskId:f.message.taskId};break;case"team_mission_log":$={agentId:f.entry.agentId,kind:f.entry.kind,summary:f.entry.summary,taskId:f.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":$={agentId:f.agentId,message:"message"in f?f.message:void 0};break;case"task_end":$={agentId:f.agentId,finishReason:f.result?.finishReason,error:f.error?.message};break;case"agent_event":$={agentId:f.agentId,eventType:f.event.type};break}this.ensureDir(),d_(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:f.type,task:$})}
715
+ `,"utf8")}ensureDir(){if(!l9(this.dirPath))r_(this.dirPath,{recursive:!0})}hasPersistableState(f){let $=f.exportState();if(this.teammateSpecs.size>0)return!0;if($.members.some((J)=>J.role==="teammate"))return!0;return $.tasks.length>0||$.mailbox.length>0||$.missionLog.length>0}clearPersistedState(){if(l9(this.statePath))i_(this.statePath)}}var SV={};N(SV,{ChatViewStateSchema:()=>i9,ChatSummarySchema:()=>$W,ChatSessionStatusSchema:()=>oJ,ChatSessionConfigSchema:()=>sJ,ChatMessageSchema:()=>fW,ChatMessageRoleSchema:()=>eJ});import{z as q}from"zod";var sJ=q.object({workspaceRoot:q.string().min(1),cwd:q.string().optional(),provider:q.string().min(1),model:q.string().min(1),mode:q.enum(["act","plan"]).default("act"),apiKey:q.string(),systemPrompt:q.string().optional(),rules:q.string().optional(),maxIterations:q.number().int().positive().optional(),enableTools:q.boolean(),enableSpawn:q.boolean().optional(),enableTeams:q.boolean().optional(),autoApproveTools:q.boolean().optional(),missionStepInterval:q.number().int().positive().optional(),missionTimeIntervalMs:q.number().int().positive().optional()}),oJ=q.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),eJ=q.enum(["user","assistant","tool","system","status","error"]),fW=q.object({id:q.string().min(1),sessionId:q.string().nullable(),role:eJ,content:q.string(),createdAt:q.number().int().nonnegative(),meta:q.object({stream:q.enum(["stdout","stderr"]).optional(),toolName:q.string().optional(),iteration:q.number().int().nonnegative().optional(),agentId:q.string().optional(),conversationId:q.string().optional(),hookEventName:q.string().optional(),inputTokens:q.number().int().nonnegative().optional(),outputTokens:q.number().int().nonnegative().optional(),checkpoint:q.object({ref:q.string(),createdAt:q.number().int().nonnegative(),runCount:q.number().int().positive(),kind:q.enum(["stash","commit"]).optional()}).optional()}).optional()}),$W=q.object({toolCalls:q.number().int().nonnegative(),tokensIn:q.number().int().nonnegative(),tokensOut:q.number().int().nonnegative()}),i9=q.object({sessionId:q.string().nullable(),status:oJ,config:sJ,messages:q.array(fW),rawTranscript:q.string(),error:q.string().nullable(),summary:$W});var kV={};N(kV,{CORE_BUILD_VERSION:()=>n9});var n9=xj;import{Agent as OL,createAgentRuntime as NL}from"@cline/agents";var xV={};N(xV,{fetchClineRecommendedModels:()=>a9,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>JW});var mV="https://api.cline.bot",s_=5000,JW={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}]};function o_(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function IV(f){if(!f||typeof f!=="object")return null;let $=f;if(typeof $.id!=="string"||$.id.length===0)return null;return{id:$.id,name:typeof $.name==="string"&&$.name.length>0?$.name:$.id,description:typeof $.description==="string"?$.description:"",tags:Array.isArray($.tags)?$.tags.filter((J)=>typeof J==="string"):[]}}function e_(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],W=Array.isArray($.free)?$.free:[],H=J.map(IV).filter((Z)=>Z!==null),Q=W.map(IV).filter((Z)=>Z!==null);if(H.length===0&&Q.length===0)return null;return{recommended:H,free:Q}}function fL(f){let $=f.baseUrl?.trim();if($)return $;try{return(f.providerSettingsManager??new P0).getProviderSettings("cline")?.baseUrl?.trim()||mV}catch{return mV}}async function $L(f,$,J){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await f($,{signal:W.signal})}finally{clearTimeout(H)}}async function a9(f={}){try{let $=fL(f),J=f.fetchImpl??fetch,W=await $L(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??s_);if(!W.ok)throw Error(`HTTP ${W.status}`);let H=await W.json(),Q=e_(H);if(Q)return Q}catch{}return o_(JW)}var gV={};N(gV,{loadLlmsConfigFromFile:()=>s9,defineLlmsConfig:()=>t9});import{readFile as JL}from"node:fs/promises";import WL from"node:path";function t9(f){return f}async function s9(f){let $=WL.resolve(f),J=await JL($,"utf8"),W;try{W=JSON.parse(J)}catch(H){let Q=H instanceof Error?H.message:String(H);throw Error(`Failed to parse JSON config at "${$}": ${Q}`)}return HL(W,$)}function HL(f,$){if(!f||typeof f!=="object")throw Error(`Invalid llms config in "${$}": expected an object.`);let W=f.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${$}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${$}": "providers" cannot be empty.`);return f}var lV={};N(lV,{createLlmsSdk:()=>e9,DefaultLlmsSdk:()=>L4});import{BUILT_IN_PROVIDER_IDS as cV,createHandler as jL,createHandlerAsync as PL,getProviderCollection as XL,hasProvider as dV,registerAsyncHandler as VL,registerHandler as YL,registerModel as BL,registerProvider as rV}from"@cline/llms";function vV(f){return f?{...f}:{}}function QL(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function ZL(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function uV(f){let $=Object.keys(f.collection.models);return{id:f.collection.provider.id,name:f.collection.provider.name,description:f.collection.provider.description,protocol:f.collection.provider.protocol,baseUrl:f.collection.provider.baseUrl,capabilities:f.collection.provider.capabilities,env:f.collection.provider.env,models:$,defaultModel:f.collection.provider.defaultModelId,modelCount:$.length}}class o9{providers=new Map;register(f){ZL(f.id,f.models);let $=f.defaultModel??f.models[0];if(!$)throw Error(`Provider "${f.id}" must define a default model.`);if(!f.models.includes($))throw Error(`Default model "${$}" is not included in configured models for "${f.id}".`);let J=this.providers.get(f.id);this.providers.set(f.id,{id:f.id,models:new Set([...J?.models??[],...f.models]),defaultModel:$,defaults:{...J?.defaults??{},...vV(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:QL(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...vV(f.settings)}})}registerModel(f,$){let J=this.providers.get(f);if(!J){this.providers.set(f,{id:f,models:new Set([$]),defaultModel:$,defaults:{}});return}J.models.add($)}createHandlerConfig(f){let $=this.require(f.providerId),J=f.modelId??$.defaultModel;if(!$.models.has(J))throw Error(`Model "${J}" is not configured for provider "${f.providerId}".`);return{providerId:f.providerId,modelId:J,...$.defaults,...f.overrides}}list(){return Array.from(this.providers.values()).map((f)=>({id:f.id,models:Array.from(f.models),defaultModel:f.defaultModel}))}getModels(f){return Array.from(this.require(f).models)}hasProvider(f){return this.providers.has(f)}hasModel(f,$){return this.providers.get(f)?.models.has($)??!1}require(f){let $=this.providers.get(f);if(!$)throw Error(`Provider "${f}" is not configured in this SDK instance.`);return $}}class L4{configuredProviders=new o9;constructor(f){this.applyConfig(f)}createHandler(f){return jL(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return PL(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(rV(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)YL(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)VL(f.collection.provider.id,f.asyncHandlerFactory);this.configuredProviders.register({id:f.collection.provider.id,models:f.exposeModels??Object.keys(f.collection.models),defaultModel:f.defaultModel??f.collection.provider.defaultModelId,defaults:f.defaults})}registerBuiltinProvider(f){let $=f.exposeModels??Object.keys(f.models),J=f.defaultModel??$[0];if(!J)throw Error(`Provider "${f.id}" must define a default model.`);rV({provider:{id:f.id,name:f.name??f.id,description:f.description,protocol:f.protocol,baseUrl:f.baseUrl,defaultModelId:J,client:f.client??"openai-compatible",capabilities:f.capabilities,env:f.env,source:"system"},models:f.models}),this.configuredProviders.register({id:f.id,models:$,defaultModel:J,defaults:{routingProviderId:f.builtinProviderId,...f.defaults??{}}})}registerModel(f){BL(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...cV]}async getBuiltInProviders(){return(await Promise.all(cV.map(($)=>XL($)))).filter(($)=>$!==void 0).map(($)=>uV({collection:$}))}getModels(f){return this.configuredProviders.getModels(f)}isProviderConfigured(f){return this.configuredProviders.hasProvider(f)}isModelConfigured(f,$){return this.configuredProviders.hasModel(f,$)}applyConfig(f){for(let $ of f.providers)this.configuredProviders.registerSelectionConfig($);for(let $ of f.models??[])this.registerModel($);for(let $ of f.customProviders??[])this.registerProvider($);for(let $ of this.configuredProviders.list()){let J=dV($.id),W=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,H=typeof W==="string"&&dV(W);if(!J&&!H)throw Error(`Provider "${$.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function e9(f){return new L4(f)}$9();async function AL(){return Promise.resolve().then(() => (iV(),pV))}function EL(){return new Date().toISOString()}function SL(f){if(sV(f)!=="providers.json")return;let $=$3(f);if(sV($)!=="settings")return;return $3($)}class P0{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??CL(),this.dataDir=f.dataDir??SL(this.filePath),this.dataDir||!f.filePath)_4({providerSettingsManager:this,dataDir:this.dataDir});if(hV(this),pJ(this.read()),f3(this.filePath))try{tV(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!f3(this.filePath))return t0();try{let f=bL(this.filePath,"utf8"),$=JSON.parse(f),J=w1.safeParse($);if(J.success)return pJ(J.data),J.data}catch{}return t0()}write(f){let $=w1.parse(f),J=$3(this.filePath);if(!f3(J))qL(J,{recursive:!0,mode:448});wL(this.filePath,`${JSON.stringify($,null,2)}
716
+ `,"utf8");try{tV(this.filePath,384)}catch{}pJ($)}saveProviderSettings(f,$={}){let J=R8.parse(f),W=this.read(),H=J.provider,Q=$.setLastUsed!==!1,Z=W.providers[H],j=$.tokenSource??Z?.tokenSource??"manual",P={...W,providers:{...W.providers,[H]:{settings:J,updatedAt:EL(),tokenSource:j}},lastUsedProvider:Q?H:W.lastUsedProvider};return this.write(P),P}getProviderSettings(f){return this.read().providers[f]?.settings}getLastUsedProviderSettings(){let f=this.read(),$=f.lastUsedProvider;if(!$)return;return f.providers[$]?.settings}getProviderConfig(f,$){let J=this.getProviderSettings(f);if(!J)return;return bf(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return bf($,f)}async refreshCatalog(){try{await q1({})}catch{}}}Gf();_J();import{isOAuthProviderId as kL}from"@cline/shared";var mL="https://api.cline.bot",J3="workos:";function IL(f,$){if(f==="cline")return`${J3}${$}`;return $}function xL(f,$){if(f==="cline"&&$.toLowerCase().startsWith(J3))return $.slice(J3.length);return $}function gL(f){let J=Rf(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function vL(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=gL($);if(W)return W;return Date.now()-1}function uL(f,$){let J=$.auth?.accessToken?.trim(),W=$.auth?.refreshToken?.trim();if(!J||!W)return null;let H=xL(f,J);if(!H)return null;return{access:H,refresh:W,expires:vL($,H),accountId:$.auth?.accountId}}function cL(f,$){let J=f?.expiresAt,W=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===W}class WW extends Error{providerId;constructor(f){super(`OAuth credentials for provider "${f}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=f}}class W3{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new P0,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){if(!kL(f.providerId))return null;return this.resolveWithSingleFlight(f.providerId,f.forceRefresh)}async resolveWithSingleFlight(f,$=!1){let J=this.refreshInFlight.get(f);if(J)return J;let W=this.resolveProviderApiKeyInternal(f,$).catch((H)=>{throw H}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,W),W}async resolveProviderApiKeyInternal(f,$){let J=this.providerSettingsManager.getProviderSettings(f);if(!J)return null;let W=uL(f,J);if(!W)return null;let H=await this.resolveCredentials(f,J,W,$);if(!H)throw new WW(f);let Q=IL(f,H.access),Z={...J.auth??{},accessToken:Q,refreshToken:H.refresh,accountId:H.accountId};Z.expiresAt=H.expires;let j={...J,auth:Z},P=!cL(J.auth,j.auth);if(P)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:Q,accountId:H.accountId,refreshed:P}}async resolveCredentials(f,$,J,W){if(f==="cline")return D8(J,{apiBaseUrl:$.baseUrl?.trim()||mL,telemetry:this.telemetry},{forceRefresh:W});if(f==="oca")return P8(J,{forceRefresh:W,telemetry:this.telemetry},{mode:$.oca?.mode,telemetry:this.telemetry});return _8(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as dL}from"@cline/shared";import{nanoid as rL}from"nanoid";class oV{list(f){return f?gf(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),W=f.pendingPrompts.findIndex((P)=>P.id===J);if(W<0)return{sessionId:$.sessionId,prompts:gf(f),updated:!1};let H=f.pendingPrompts[W];if(!H)return{sessionId:$.sessionId,prompts:gf(f),updated:!1};let Q=$.prompt===void 0?H.prompt:dL($.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let Z=$.delivery??H.delivery,j={...H,prompt:Q,delivery:Z};return f.pendingPrompts.splice(W,1),lL(f,j,W,H.delivery),{sessionId:$.sessionId,prompts:gf(f),prompt:HW(j),updated:!0}}delete(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=$.promptId.trim(),W=f.pendingPrompts.findIndex((Q)=>Q.id===J);if(W<0)return{sessionId:$.sessionId,prompts:gf(f),removed:!1};let[H]=f.pendingPrompts.splice(W,1);return{sessionId:$.sessionId,prompts:gf(f),prompt:H?HW(H):void 0,removed:!0}}enqueue(f,$){let{prompt:J,delivery:W,userImages:H,userFiles:Q}=$,Z=f.pendingPrompts.findIndex((j)=>j.prompt===J);if(Z>=0){let[j]=f.pendingPrompts.splice(Z,1),P={...j,prompt:J,userImages:H??j.userImages,userFiles:Q??j.userFiles};if(W==="steer"||j.delivery==="steer")f.pendingPrompts.unshift({...P,delivery:"steer"});else f.pendingPrompts.push(P)}else{let j={id:`pending_${Date.now()}_${rL(5)}`,prompt:J,delivery:W,userImages:H,userFiles:Q};if(W==="steer")f.pendingPrompts.unshift(j);else f.pendingPrompts.push(j)}return gf(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((W)=>W.delivery==="steer");if($<0)return{prompts:gf(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:gf(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:gf(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),gf(f)}clear(f){return f.pendingPrompts.length=0,[]}}class H3{deps;service=new oV;constructor(f){this.deps=f}list(f){return this.service.list(this.deps.getSession(f))}update(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=this.service.update($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}delete(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=this.service.delete($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}enqueue(f,$){let J=this.deps.getSession(f);if(!J||J.aborting)return;this.service.enqueue(J,$),this.emitPrompts(J),this.scheduleDrain(f,J)}consumeSteer(f){let $=this.deps.getSession(f);if(!$)return;let{entry:J}=this.service.consumeSteer($);if(!J)return;return this.emitPrompts($),this.emitSubmitted($,J),J.prompt}clearAborted(f){if(f.pendingPrompts.length===0)return;this.service.clear(f),this.emitPrompts(f)}emitPrompts(f){this.deps.emit({type:"pending_prompts",payload:{sessionId:f.sessionId,prompts:gf(f)}})}scheduleDrain(f,$){if($.pendingPrompts.length===0||$.aborting||$.drainingPendingPrompts||!$.agent.canStartRun())return;queueMicrotask(()=>{this.drain(f)})}async drain(f){let $=this.deps.getSession(f);if(!$||$.aborting||$.drainingPendingPrompts)return;if(!$.agent.canStartRun())return;let{entry:J}=this.service.shiftNext($);if(!J)return;this.emitPrompts($),this.emitSubmitted($,J),$.drainingPendingPrompts=!0;try{await this.deps.send({sessionId:f,prompt:J.prompt,userImages:J.userImages,userFiles:J.userFiles})}catch(W){if((W instanceof Error?W.message:String(W)).includes("already in progress"))this.service.requeueFront($,J),this.emitPrompts($);else throw W}finally{if($.drainingPendingPrompts=!1,$.pendingPrompts.length>0&&$.status!=="failed"&&$.status!=="cancelled")queueMicrotask(()=>{this.drain(f)})}}emitSubmitted(f,$){let J=HW($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function HW(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function gf(f){return f.pendingPrompts.map(HW)}function lL(f,$,J,W){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(W==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}Gf();class Q3{deps;constructor(f){this.deps=f}dispatchAgentEvent(f,$,J){let W=this.deps.getSession(f),H={sessionId:f,config:$,liveSession:W,usageBySession:this.deps.usageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=nW(J),Z=W&&Q.agentId===eV(W.agent);aW(H,J,Z?{isPrimaryAgentEvent:!0,...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(xH(J,$),$.type==="agent_event"){let W={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};aW(W,$.event,{teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let W=U0({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:eV(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(W)v0(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await gH(f,$,this.deps.invokeBackendOptional),J)vH(J,f,$,this.deps.emit)}async handlePluginEvent(f,$,J){if($.name==="plugin_log"){this.handlePluginLog(f,$.payload);return}if($.name==="automation_event"){let P=this.deps.getSession(f)?.config.extensionContext?.automation??J;if(!P)return;let X=$.payload&&typeof $.payload==="object"?$.payload:void 0;if(!X)return;await P.ingestEvent(X);return}if($.name!=="steer_message"&&$.name!=="queue_message"&&$.name!=="pending_prompt")return;let W=$.payload&&typeof $.payload==="object"?$.payload:void 0,H=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():f,Q=typeof W?.prompt==="string"?W.prompt.trim():"";if(!Q)return;let Z=$.name==="steer_message"?"steer":$.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(H,{prompt:Q,delivery:Z})}handlePluginLog(f,$,J){let W=this.deps.getSession(f),H=J??W?.config.extensionContext?.logger??W?.config.logger;if(!H||!$||typeof $!=="object")return;let Q=$,Z=typeof Q.message==="string"?Q.message:"";if(!Z)return;let j=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(j.sessionId??=f,typeof Q.pluginName==="string"&&Q.pluginName)j.pluginName=Q.pluginName;if(Q.level==="debug"){H.debug(Z,j);return}if(Q.level==="error"){if(H.error)H.error(Z,j);else H.log(Z,{...j,severity:"error"});return}H.log(Z,j)}}function eV(f){return f.getAgentId()}function Z3(f){return{sessionId:f.sessionId,source:f.source,pid:process.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:d0(f.config),teamName:f.config.teamName?.trim()||void 0,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,parentSessionId:typeof f.sessionMetadata?.parentSessionId==="string"?f.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof f.sessionMetadata?.parentAgentId==="string"?f.sessionMetadata.parentAgentId:void 0,agentId:typeof f.sessionMetadata?.agentId==="string"?f.sessionMetadata.agentId:void 0,conversationId:typeof f.sessionMetadata?.conversationId==="string"?f.sessionMetadata.conversationId:void 0,isSubagent:typeof f.sessionMetadata?.isSubagent==="boolean"?f.sessionMetadata.isSubagent:!1,prompt:f.pendingPrompt,metadata:f.sessionMetadata,messagesPath:f.artifacts?.messagesPath,updatedAt:f.updatedAt??f.endedAt??f.startedAt}}function j3(f,$){let J=f[$];return typeof J==="function"?J:null}async function fY(f,$,...J){let W=j3(f,$);if(!W)throw Error(`session service method not available: ${$}`);return Promise.resolve(W.apply(f,J))}async function $Y(f,$,...J){let W=j3(f,$);if(!W)return;await Promise.resolve(W.apply(f,J))}async function JY(f,$,...J){let W=j3(f,$);if(!W)return;return await Promise.resolve(W.apply(f,J))}G0();Gf();function P3(f,$,J,W){return I0({configProvider:{getRuntimeConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:$.hooks,extensions:$.extensions,logger:$.logger,telemetry:$.telemetry},getConnectionConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=$.enableTools?T$({cwd:$.cwd,...Nf[B0({mode:$.mode})],executors:W}):[];if($.enableSpawnAgent)Q.push(P3(f,$,J,W));return z$(Q)},onSubAgentEvent:(Q)=>f.onAgentEvent(J,$,Q),onSubAgentStart:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime;f.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let j=U0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)v0($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...j});n2($.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),f.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime,j=f.subAgentStarts.get(Q.subAgentId),P=j?Date.now()-j.startedAt:0,X=Q.result?.text?Q.result.text.split(`
717
+ `).length:0;n2($.telemetry,{event:"ended",ulid:J,durationMs:P,outputLines:X,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...U0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),f.subAgentStarts.delete(Q.subAgentId),f.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as pL,stat as iL}from"node:fs/promises";var nL=20480000;async function WY(f){let $=await iL(f);if(!$.isFile())throw Error("Path is not a file");if($.size>nL)throw Error("File is too large to read into context.");let J=await pL(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var HY=5000;class Z0{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new a8;sessions=new Map;usageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new j$;constructor(f){let $=aL();if($)$z($);let J=c$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new B2,this.createAgentInstance=f.createAgent??((W)=>new m0(W)),this.defaultCapabilities=Vf(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new P0,this.oauthTokenManager=f.oauthTokenManager??new W3({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new H3({getSession:(W)=>this.sessions.get(W),emit:(W)=>this.emit(W),send:(W)=>this.runTurn(W)}),this.pendingPrompts={list:async(W)=>this.pendingPromptsController.list(W.sessionId),update:async(W)=>this.pendingPromptsController.update(W),delete:async(W)=>this.pendingPromptsController.delete(W)},this.eventBridge=new Q3({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,emit:(W)=>this.emit(W),persistMessages:(W,H,Q)=>{this.invoke("persistSessionMessages",W,H,Q)},enqueuePendingPrompt:(W,H)=>this.pendingPromptsController.enqueue(W,H),invokeBackendOptional:(W,...H)=>this.invokeOptional(W,...H)})}async startSession(f){let $=f.source??Pf.CLI,J=s(),W=f.config.sessionId?.trim()??"",H=W||oL(),Q=f,Z=Q.initialMessages??[];this.usageBySession.set(H,Z.length>0?a2(Z):u0());let j=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!j)throw Error("session service method not available: ensureSessionsDir");let P=X3(j,H),X=X3(P,`${H}.messages.json`),V=X3(P,`${H}.json`),Y=d0(f.config),B=Uf.parse({version:1,session_id:H,source:$,pid:process.pid,started_at:J,status:"running",interactive:f.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:Y,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:X}),A;if(W.length>0&&Z.length>0&&!Q.prompt?.trim()){let C=await this.invokeOptionalValue("readSessionManifest",H);if(C)B=C,A={manifestPath:V,messagesPath:C.messages_path||X,manifest:C}}let U=Vf(this.defaultCapabilities,f.capabilities),y=U?.toolExecutors??this.toolExecutors,F=f.localRuntime,K=F?.extensionContext?.logger??F?.logger,M=F?.extensionContext?.automation,h;h=await FZ({input:Q,localRuntime:f.localRuntime,sessionId:H,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(C)=>{if(C.name==="plugin_log"){this.eventBridge.handlePluginLog(H,C.payload,K);return}this.eventBridge.handlePluginEvent(H,C,M)},onTeamEvent:(C)=>{this.eventBridge.handleTeamEvent(H,C),h.config.onTeamEvent?.(C)},createSpawnTool:()=>P3({getSession:(C)=>this.sessions.get(C),subAgentStarts:this.subAgentStarts,onAgentEvent:(C,af,uf)=>this.eventBridge.dispatchAgentEvent(C,af,uf),invokeBackendOptional:(C,...af)=>this.invokeOptional(C,...af)},h.config,H,y),readSessionMetadata:async()=>(await this.getSession(H))?.metadata,writeSessionMetadata:async(C)=>{await this.persistSessionMetadata(H,()=>C)}});let G=await this.runtimeBuilder.build(h.runtimeBuilderInput),T=h.config,z=h.providerConfig;if(G.teamRuntime&&!T.teamName?.trim())T.teamName=G.teamRuntime.getTeamName();let u=[...G.tools,...T.extraTools??[]],vf=G.extensions??h.extensions,a={sessionId:H,providerId:z.providerId,modelId:z.modelId,apiKey:z.apiKey,baseUrl:z.baseUrl,headers:z.headers,knownModels:z.knownModels,providerConfig:z,thinking:T.thinking,reasoningEffort:T.reasoningEffort??z.reasoningEffort,systemPrompt:T.systemPrompt,maxIterations:T.maxIterations,execution:T.execution,prepareTurn:h2(T),tools:u,hooks:h.hooks,extensions:vf,hookErrorMode:T.hookErrorMode,initialMessages:h.effectiveInput.initialMessages,userFileContentLoader:WY,toolPolicies:h.toolPolicies,requestToolApproval:h.requestToolApproval,onConsecutiveMistakeLimitReached:T.onConsecutiveMistakeLimitReached,completionPolicy:G.completionPolicy,consumePendingUserMessage:()=>{let C=this.pendingPromptsController.consumeSteer(H);return C?Q4(C,T.mode):C},logger:G.logger??T.logger,extensionContext:T.extensionContext,onEvent:(C)=>this.eventBridge.dispatchAgentEvent(H,T,C)};a.hooks={...a.hooks,onEvent:async(C)=>{if(await h.hooks?.onEvent?.(C),C.type!=="assistant-message")return;let af=this.sessions.get(H);if(!af)return;let uf=af.agent.getMessages();try{await this.invoke("persistSessionMessages",H,uf,T.systemPrompt)}catch($f){T.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:H,error:$f})}}};let c=this.createAgentInstance(a);if(a.onEvent)c.subscribeEvents(a.onEvent);G.registerLeadAgent?.(c);let d=U0({agentId:c.getAgentId(),conversationId:c.getConversationId(),teamId:G.teamRuntime?.getTeamId(),teamName:G.teamRuntime?.getTeamName(),teamRole:G.teamRuntime?"lead":void 0});if(KZ(T,H,W.length>0,Y,d),d)v0(T.telemetry,{ulid:H,modelId:T.modelId,provider:T.providerId,...d});if(G.teamRuntime)J6(T.telemetry,{ulid:H,teamId:G.teamRuntime.getTeamId(),teamName:G.teamRuntime.getTeamName(),leadAgentId:c.getAgentId(),restoredFromPersistence:G.teamRestoredFromPersistence===!0});let t={sessionId:H,config:T,sessionMetadata:Q.sessionMetadata,...A?{artifacts:A}:{},source:$,startedAt:A?.manifest.started_at??J,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??J,pendingPrompt:B.prompt,runtime:G,agent:c,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:f.interactive===!0,persistedMessages:Z,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:h.pluginSandboxShutdown,submitAndExitObserved:!1};if(this.sessions.set(H,t),this.emitStatus(H,"running"),Z.length>0&&!A){if(await this.ensureSessionPersisted(t),await this.invoke("persistSessionMessages",t.sessionId,Z,t.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(t,"completed",0)}let nf;try{if(Q.prompt?.trim())if(nf=await this.executeTurn(t,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!t.interactive)await this.finalizeSingleRun(t,nf.finishReason);else await this.completeInteractiveTurn(t,nf.finishReason)}catch(C){if(t.interactive&&t.aborting)nf=await this.completeAbortedInteractiveTurn(t);else throw await this.failSession(t),C}return{sessionId:H,manifest:B,manifestPath:V,messagesPath:X,result:nf}}async restoreSession(f){return this.sessionVersioning.restoreCheckpoint({...f,getSession:($)=>this.getSession($),readMessages:($)=>this.readSessionMessages($),buildStartInput:($,J)=>{let W=$.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:$.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...W?{sessionMetadata:W}:{},initialMessages:$.initialMessages}},startSession:($)=>this.startSession($),getStartedSessionId:($)=>$.sessionId,readRestoredSession:($)=>this.getSession($)})}async runTurn(f){let $=this.getSessionOrThrow(f.sessionId),J=$.agent.canStartRun(),W=f.delivery??($.interactive&&!J?"queue":void 0);if($.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:f.sessionId,promptLength:f.prompt.length,userImageCount:f.userImages?.length??0,userFileCount:f.userFiles?.length??0,delivery:W??"immediate"}}),W==="queue"||W==="steer"){this.pendingPromptsController.enqueue(f.sessionId,{prompt:f.prompt,delivery:W,userImages:f.userImages,userFiles:f.userFiles});return}try{let H=await this.executeTurn($,{prompt:f.prompt,userImages:f.userImages,userFiles:f.userFiles});if(!$.interactive)await this.finalizeSingleRun($,H.finishReason);else await this.completeInteractiveTurn($,H.finishReason);if(H.finishReason==="error"||H.finishReason==="aborted")return H;return queueMicrotask(()=>{this.pendingPromptsController.drain(f.sessionId)}),H}catch(H){if($.interactive&&$.aborting)return await this.completeAbortedInteractiveTurn($);throw await this.failSession($),H}}async getAccumulatedUsage(f){return qj(this.usageBySession.get(f))}async abort(f,$){let J=this.sessions.get(f);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:f}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort($)}async stopSession(f){let $=this.sessions.get(f);if(!$)return;if($.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:f}}),$.interactive&&$.status!=="running"){await this.releaseSessionRuntime($,"session_stop");return}$.aborting=!0,$.agent.abort(Error("session_stop")),await this.shutdownSession($,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose(f="session_manager_dispose"){let $=[...this.sessions.values()];if($.length===0)return;await Promise.allSettled($.map((J)=>J.interactive&&J.status!=="running"?this.releaseSessionRuntime(J,f):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:f,endReason:"disposed"}))),this.usageBySession.clear()}async getSession(f){let $=this.sessions.get(f);if($)return Z3($);let J=f.trim();if(!J)return;let W=await this.getRow(J);if(W)return r2(W);let H=await this.readManifest(J);return H?RJ(H):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(r2),W=new Set(J.map((H)=>H.sessionId));for(let H of this.sessions.values()){if(W.has(H.sessionId))continue;J.unshift(Z3(H))}return J.slice(0,f)}async deleteSession(f){if(this.sessions.has(f))await this.stopSession(f);let $=await this.invoke("deleteSession",f);if($.deleted)this.usageBySession.delete(f);return $.deleted}async updateSession(f,$){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:f,prompt:$.prompt,metadata:$.metadata,title:$.title}))?.updated===!0}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.getRow($);if(J?.messagesPath)return x$(J.messagesPath);let W=await this.readManifest($);return x$(W?.messages_path)}async dispatchHookEvent(f){await bj(f,{queueSpawnRequest:($)=>this.invokeOptional("queueSpawnRequest",$),upsertSubagentSessionFromHook:($)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",$),appendSubagentHookAudit:($,J)=>this.invokeOptional("appendSubagentHookAudit",$,J),applySubagentStatus:($,J)=>this.invokeOptional("applySubagentStatus",$,J)})}subscribe(f,$){return this.events.subscribe(f,$)}async updateSessionModel(f,$){let J=this.getSessionOrThrow(f);J.config.modelId=$,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:$}),J.agent.updateConnection({modelId:$})}handlePluginEvent(f,$,J){return this.eventBridge.handlePluginEvent(f,$,J)}async executeTurn(f,$){let J=await this.prepareTurnInput(f,$),W=J.prompt.trim();if(!W)throw Error("prompt cannot be empty");if(!f.artifacts&&!f.pendingPrompt)f.pendingPrompt=W;await this.ensureSessionPersisted(f),await this.syncOAuthCredentials(f),await this.markTurnRunning(f);let H=await this.executeAgentTurn(f,W,J.userImages,J.userFiles);while(uH(f,H.finishReason)){let Q=await cH(f);if(Q.length===0)break;let Z=dH(f,Q);H=await this.executeAgentTurn(f,Z)}return H}async completeInteractiveTurn(f,$){if(H4(f))return;let J=$==="aborted"||f.aborting,W=$==="error";await this.updateStatus(f,J?"cancelled":W?"failed":"completed",W?1:0),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$,ts:Date.now()}}),f.aborting=!1}async completeAbortedInteractiveTurn(f){let $=new Date,J=f.agent.getMessages();return f.persistedMessages=J,f.started=f.started||J.length>0,await this.completeInteractiveTurn(f,"aborted"),{text:"",usage:u0(),messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:f.config.modelId,provider:f.config.providerId},startedAt:$,endedAt:$,durationMs:0}}async executeAgentTurn(f,$,J,W){let H=f.started||f.agent.getMessages().length>0,Q=f.persistedMessages??f.agent.getMessages(),Z=this.usageBySession.get(f.sessionId)??u0();f.turnUsageBaseline=Z,a4(f.config.telemetry,f.sessionId,f.config.mode),F1(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,model:f.config.modelId,source:"user",mode:f.config.mode,...this.getSessionAgentTelemetryIdentity(f)});try{let j=H?()=>f.agent.continue($,J,W):()=>f.agent.run($,J,W),P=await this.runWithAuthRetry(f,j,Q);f.started=!0;let X=c4(P.messages,P,Q);f.persistedMessages=X;let V=c0(Z,P.usage);return this.usageBySession.set(f.sessionId,V),await this.persistSessionMetadata(f.sessionId,(Y)=>({...Y??{},totalCost:V.totalCost})),await this.invoke("persistSessionMessages",f.sessionId,X,f.config.systemPrompt),this.observeTaskCompletionTool(f,P),P}catch(j){throw await this.invoke("persistSessionMessages",f.sessionId,f.agent.getMessages(),f.config.systemPrompt),j}finally{f.turnUsageBaseline=void 0}}observeTaskCompletionTool(f,$){if(f.submitAndExitObserved)return;if(!$.toolCalls.some((W)=>W.name===ff.SUBMIT_AND_EXIT&&W.error===void 0))return;f.submitAndExitObserved=!0,p2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity(f)})}async prepareTurnInput(f,$){let J=d0(f.config),W=fz($.prompt).trim();if(!W)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let H=await H1(W,J);UZ(f.config.telemetry,H);let Q=Q4(H.prompt,f.config.mode),Z=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),j=this.resolveAbsoluteFilePaths(J,H.matchedFiles),P=Array.from(new Set([...Z,...j]));return{prompt:Q,userImages:$.userImages,userFiles:P.length>0?P:void 0}}async ensureSessionPersisted(f){if(f.artifacts)return;let $=d0(f.config);f.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:f.sessionId,source:f.source,pid:process.pid,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:$,teamName:f.config.teamName,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,prompt:f.pendingPrompt,metadata:f.sessionMetadata,startedAt:f.startedAt})}async markTurnRunning(f){if(f.status==="running")return;await this.updateStatus(f,"running",null)}async persistSessionMetadata(f,$){let J=this.sessions.get(f),W=await this.invokeOptionalValue("readSessionManifest",f)??J?.artifacts?.manifest,H=$(W?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:f,metadata:H}))?.updated===!1)return;J.sessionMetadata=H,J.artifacts.manifest.metadata=H}async finalizeSingleRun(f,$){if(H4(f))return;let J=$==="aborted"||f.aborting,W=$==="error";await this.shutdownSession(f,{status:J?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:$})}async failSession(f){await this.shutdownSession(f,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession(f,$){if($.status==="completed"&&!f.submitAndExitObserved)p2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity(f)});zJ(f);let J=[],W=(H,Q)=>{J.push(Q),f.config.logger?.log("Session shutdown cleanup failed",{sessionId:f.sessionId,stage:H,error:Q,severity:"warn"})};if(f.artifacts){try{await this.updateStatus(f,$.status,$.exitCode)}catch(H){W("update_status",H)}try{await f.agent.shutdown($.shutdownReason)}catch(H){W("agent_shutdown",H)}}try{await Promise.resolve(f.runtime.shutdown($.shutdownReason))}catch(H){W("runtime_shutdown",H)}try{await f.pluginSandboxShutdown?.()}catch(H){W("plugin_sandbox_shutdown",H)}if(this.sessions.delete(f.sessionId),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$.endReason,ts:Date.now()}}),J.length>0&&$.status==="failed")throw J[0]}async releaseSessionRuntime(f,$){let J=[],W=(H,Q)=>{J.push(Q),f.config.logger?.log("Session runtime cleanup failed",{sessionId:f.sessionId,stage:H,error:Q,severity:"warn"})};try{await f.agent.shutdown($)}catch(H){W("agent_shutdown",H)}try{await Promise.resolve(f.runtime.shutdown($))}catch(H){W("runtime_shutdown",H)}try{await f.pluginSandboxShutdown?.()}catch(H){W("plugin_sandbox_shutdown",H)}if(this.sessions.delete(f.sessionId),J.length>0)throw J[0]}async updateStatus(f,$,J){if(!f.artifacts)return;let W=await this.invoke("updateSessionStatus",f.sessionId,$,J);if(!W.updated)return;let H=await this.invokeOptionalValue("readSessionManifest",f.sessionId)??f.artifacts.manifest;if(H.status=$,$==="running")delete H.ended_at,H.exit_code=null;else H.ended_at=W.endedAt??s(),H.exit_code=typeof J==="number"?J:null;f.artifacts.manifest=H,f.status=$,f.updatedAt=W.endedAt??s(),f.endedAt=$==="running"?null:H.ended_at,f.exitCode=H.exit_code,await this.invoke("writeSessionManifest",f.artifacts.manifestPath,H),this.emitStatus(f.sessionId,$)}async runWithAuthRetry(f,$,J){try{return await $()}catch(W){if(!eL(W,f.config.providerId))throw W;return await this.syncOAuthCredentials(f,{forceRefresh:!0}),f.agent.restore(J),$()}}async syncOAuthCredentials(f,$){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:f.config.providerId,forceRefresh:$?.forceRefresh})}catch(W){if(W instanceof WW)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!J?.apiKey||f.config.apiKey===J.apiKey)return;f.config.apiKey=J.apiKey,f.agent.updateConnection({apiKey:J.apiKey}),f.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),f.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow(f){let $=this.sessions.get(f);if(!$)throw Error(`session not found: ${f}`);return $}resolveAbsoluteFilePaths(f,$){if(!$||$.length===0)return[];let J=$.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>tL(W)?W:sL(f,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return U0({agentId:f.agent.getAgentId(),conversationId:f.agent.getConversationId(),teamId:f.runtime.teamRuntime?.getTeamId(),teamName:f.runtime.teamRuntime?.getTeamName(),teamRole:f.runtime.teamRuntime?"lead":void 0})}emitStatus(f,$){this.emitSessionSnapshot(f),this.emit({type:"status",payload:{sessionId:f,status:$}})}async emitSessionSnapshot(f){let $=await this.getSession(f);if(!$)return;this.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:$0({session:$,messages:await this.readSessionMessages(f),usage:this.usageBySession.get(f)})}})}emit(f){this.events.emit(f)}async listRows(f){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor(f)),HY))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(HY)).find((W)=>W.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return fY(this.sessionService,f,...$)}invokeOptional(f,...$){return $Y(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return JY(this.sessionService,f,...$)}}function Wz(f){return{text:f.text,usage:f.usage,inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function Hz(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function uJ(f={}){let $=new Z0({sessionService:new Q0(new W0),fetch:f.fetch,telemetry:f.telemetry});return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),H=await $.startSession({source:J.source?.trim()||Pf.CLI,interactive:!1,config:{providerId:Jz(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:Hz(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:H.sessionId,startResult:{sessionId:H.sessionId,manifestPath:H.manifestPath,messagesPath:H.messagesPath}}},async sendSession(J,W){let H=await $.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content)});if(!H)throw Error("local hub schedule runtime returned no turn result");return{result:Wz(H)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}Qz(process.env.CLINE_VCR);function Zz(f){let $=process.cwd(),J,W,H;for(let Q=0;Q<f.length;Q+=1){let Z=f[Q],j=f[Q+1];if(Z==="--cwd"&&j){$=j,Q+=1;continue}if(Z==="--host"&&j){J=j,Q+=1;continue}if(Z==="--port"&&j){let P=Number(j);if(Number.isFinite(P))W=P;Q+=1;continue}if(Z==="--pathname"&&j)H=j,Q+=1}return{cwd:$,host:J,port:W,pathname:H}}async function jz(){let f=Zz(process.argv.slice(2));process.chdir(f.cwd);let $=Sf({host:f.host,port:f.port,pathname:f.pathname}),J=await t$({host:$.host,port:$.port,pathname:$.pathname,owner:Qf(),runtimeHandlers:uJ(),cronOptions:{workspaceRoot:f.cwd}}),W=async()=>{await J.close(),process.exit(0)},H=!1,Q=(Z,j)=>{if(H)return;H=!0;let P=j instanceof Error?j.stack||j.message:String(j);process.stderr.write(`[hub-daemon] ${Z}: ${P}
718
+ `),J.close().catch((X)=>{let V=X instanceof Error?X.stack||X.message:String(X);process.stderr.write(`[hub-daemon] shutdown after ${Z} failed: ${V}
719
+ `)}).finally(()=>{process.exit(1)})};process.on("SIGINT",()=>{W()}),process.on("SIGTERM",()=>{W()}),process.on("uncaughtException",(Z)=>{Q("uncaughtException",Z)}),process.on("unhandledRejection",(Z)=>{Q("unhandledRejection",Z)}),await new Promise(()=>{})}jz().catch((f)=>{let $=f instanceof Error?f.stack||f.message:String(f);process.stderr.write(`[hub-daemon] fatal: ${$}
720
+ `),process.exit(1)});