@cline/core 0.0.88-nightly.1790735522 → 0.0.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -198,7 +198,7 @@ Searched ${f} files.`;let y=[`Found ${g.length} result${g.length===1?"":"s"} for
198
198
 
199
199
  ...[assistant text truncated: omitted ${e} chars due to repeated tool-call markup]...
200
200
 
201
- `;function kk(e=process.env){return{maxToolResultChars:Ck(e[gf.maxToolResultChars]),maxTotalTextBytes:Ck(e[gf.maxTotalTextBytes]),minOutdatedRewriteBytes:dW(e[gf.minOutdatedRewriteBytes])}}class hf{indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor(e={}){this.maxToolResultChars=ia(e.maxToolResultChars,Y$),this.maxFileContentChars=ia(e.maxFileContentChars,Q$),this.maxTotalTextBytes=ia(e.maxTotalTextBytes,Z$),this.mediaBudget=e.mediaBudget??{},this.maxAssistantTextChars=ia(e.maxAssistantTextChars,eW),this.maxAssistantToolMarkupChars=ia(e.maxAssistantToolMarkupChars,tW),this.minOutdatedRewriteBytes=cW(e.minOutdatedRewriteBytes,nW)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi(e){this.reindex(e),this.commitOutdatedRewrites(e);let n=this.addMissingToolResults(e).map((o)=>{if(!Array.isArray(o.content)){if(o.role==="user"&&typeof o.content==="string"){let a=yk(o.content);if(a!==o.content)return{...o,content:a}}if(o.role==="assistant"&&typeof o.content==="string"){let a=this.truncateAssistantText(o.content);if(a!==o.content)return{...o,content:a}}return o}let s=!1,i=o.content.map((a)=>{let d=this.transformBlock(a,o.role);if(d!==a)s=!0;return d});return s?{...o,content:i}:o}),r=this.applyMediaBudget(n);return this.truncateToTotalTextBudget(r)}transformBlock(e,t){if(t==="user"&&e.type==="text"&&typeof e.text==="string"){let o=yk(e.text);if(o!==e.text)return{...e,text:o};return e}if(t==="assistant"&&e.type==="text"&&typeof e.text==="string"){let o=this.truncateAssistantText(e.text);return o===e.text?e:{...e,text:o}}if(e.type==="file"){let o=bs(e.content,this.maxFileContentChars,vk);return o===e.content?e:{...e,content:o}}if(e.type!=="tool_result")return e;let n=this.resolveToolName(e),r=e.content;if(this.isReadTool(n)&&e.is_error!==!0){let o=this.committedOutdatedRewrites.get(e.tool_use_id);if(o&&o.size>0){let i=this.getReadLocators(e).filter((a)=>o.has(this.toReadLocatorKey(a))&&this.isOutdatedReadLocator(a,e.tool_use_id));if(i.length>0)r=this.replaceOutdatedReadContent(r,i)}}return r=this.truncateToolResultContent(r),r===e.content?e:{...e,content:r}}reindex(e){let t=this.indexedMessageCount===0||e.length>=this.indexedMessageCount&&e[this.indexedMessageCount-1]===this.indexedTailRef;if(e.length<this.indexedMessageCount||!t)this.resetIndexes();for(let n=this.indexedMessageCount;n<e.length;n++){let r=e[n];if(!Array.isArray(r.content))continue;for(let o=0;o<r.content.length;o++){let s=r.content[o];if(s.type==="file")this.latestFullContentOwnerByPathCache.set(s.path,`file:${n}:${o}`);else if(s.type==="tool_use"){let i=s.name.toLowerCase();if(this.toolNameByIdCache.set(s.id,i),this.isReadTool(i)){let a=this.extractLocatorsFromReadToolInput(s.input);if(a.length>0)this.readLocatorsByToolUseIdCache.set(s.id,a)}}else if(s.type==="tool_result"){let i=this.resolveToolName(s);if(!this.isReadTool(i)||s.is_error===!0)continue;let a=this.getReadLocators(s);for(let d of a)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(d),s.tool_use_id),this.isFullFileRead(d))this.latestFullContentOwnerByPathCache.set(d.path,s.tool_use_id)}}}this.indexedMessageCount=e.length,this.indexedTailRef=e.length>0?e[e.length-1]:void 0}commitOutdatedRewrites(e){let t=new Map,n=new Set,r=0;for(let o of e){if(!Array.isArray(o.content))continue;for(let s of o.content){if(s.type!=="tool_result"||s.is_error===!0)continue;let i=this.resolveToolName(s);if(!this.isReadTool(i))continue;n.add(s.tool_use_id);let a=this.committedOutdatedRewrites.get(s.tool_use_id),d=new Set,c=new Set;for(let l of this.getReadLocators(s)){let p=this.toReadLocatorKey(l);if(!this.isOutdatedReadLocator(l,s.tool_use_id))continue;if(c.add(p),!a?.has(p))d.add(p)}if(a){for(let l of a)if(!c.has(l))a.delete(l);if(a.size===0)this.committedOutdatedRewrites.delete(s.tool_use_id)}if(d.size===0)continue;let u=t.get(s.tool_use_id);if(!u)u=new Set,t.set(s.tool_use_id,u);for(let l of d)u.add(l);r+=this.estimateOutdatedReclaimBytes(s.content,d)}}for(let o of this.committedOutdatedRewrites.keys())if(!n.has(o))this.committedOutdatedRewrites.delete(o);if(t.size===0||r<this.minOutdatedRewriteBytes)return;for(let[o,s]of t){let i=this.committedOutdatedRewrites.get(o);if(!i)i=new Set,this.committedOutdatedRewrites.set(o,i);for(let a of s)i.add(a)}}estimateOutdatedReclaimBytes(e,t){let n=this.extractReadLocatorsFromToolResultContent(e),r=n.length>0&&n.every((d)=>t.has(this.toReadLocatorKey(d))),o=(d)=>{let c;try{c=JSON.parse(d)}catch{return r||n.length===0?Te(this.truncateMiddle(d)):0}let u=Array.isArray(c)?c:[c],l=0;for(let p of u){let m=this.extractLocatorFromResultEntry(p);if(m&&t.has(this.toReadLocatorKey(m)))l+=this.providerBoundEntryBytes(p)}return l};if(typeof e==="string")return o(e);let s=new Set(t),i=0;for(let d of e)if(d.type==="text")i+=this.countOutdatedImageEntries(d.text,s);let a=0;for(let d of e)if(d.type==="text")a+=o(d.text);else if(d.type==="image"){if(i>0)i-=1,a+=Te(d.data)}else if(cr(d)){let c=this.extractLocatorFromResultEntry(d);if(c&&t.has(this.toReadLocatorKey(c)))a+=this.providerBoundEntryBytes(d)}else if(d.type==="file"){if(t.has(this.toReadLocatorKey({path:d.path,startLine:null,endLine:null})))a+=Te(this.truncateMiddle(d.content))}return a}providerBoundEntryBytes(e){let t=this.truncateNestedStrings(e);return Te(JSON.stringify(t))}addMissingToolResults(e){let t=this.collectToolResultIds(e),n=[],r=new Map,o=!1,s=()=>{if(r.size===0)return;i(this.createMissingToolResultMessage(r)),r.clear(),o=!0},i=(a)=>{let d=n.at(-1);if(this.shouldMergeUserAfterToolResults(d,a)){n[n.length-1]={...d,content:[...d.content,...this.contentBlocksForUserMerge(a.content)]},o=!0;return}n.push(a)};for(let a of e){if(this.isToolResultOnlyMessage(a)){if(i(this.appendMissingToolResults(a,r)),r.size>0)r.clear(),o=!0;continue}if(Array.isArray(a.content)){let d=a.content.filter((u)=>u.type==="tool_result"),c=a.content.filter((u)=>u.type!=="tool_result");if(d.length>0){let u=this.appendMissingToolResults({...a,role:"user",content:d},r);if(i(u),r.size>0)r.clear();o=!0}if(c.length>0||d.length===0){if(d.length===0)s();let u=d.length>0?{...a,content:c}:a;if(i(u),u.role==="assistant")this.trackMissingToolCalls(u,t,r)}continue}s(),i(a)}return s(),o?n:e}appendMissingToolResults(e,t){if(t.size===0||!Array.isArray(e.content))return e;return{...e,role:"user",content:[...e.content,...this.createMissingToolResultBlocks(t)]}}shouldMergeUserAfterToolResults(e,t){return e?.role==="user"&&t.role==="user"&&this.isToolResultOnlyMessage(e)&&this.contentBlocksForUserMerge(t.content).length>0}contentBlocksForUserMerge(e){return typeof e==="string"?e.length>0?[{type:"text",text:e}]:[]:e}collectToolResultIds(e){let t=new Set;for(let n of e){if(!Array.isArray(n.content))continue;for(let r of n.content)if(r.type==="tool_result")t.add(r.tool_use_id)}return t}isToolResultOnlyMessage(e){return e.role==="user"&&Array.isArray(e.content)&&e.content.length>0&&e.content.every((t)=>t.type==="tool_result")}trackMissingToolCalls(e,t,n){if(!Array.isArray(e.content))return;for(let r of e.content){if(r.type!=="tool_use"||t.has(r.id))continue;n.set(r.id,r.name)}}createMissingToolResultMessage(e){return{role:"user",content:this.createMissingToolResultBlocks(e)}}createMissingToolResultBlocks(e){return Array.from(e,([t,n])=>({type:"tool_result",tool_use_id:t,name:n,content:[{type:"text",text:this.formatMissingToolResultText(n)}],is_error:!0}))}formatMissingToolResultText(e){return e?`${bk} Tool: ${e}.`:bk}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(e){let t=e,n=this.readResultLocatorCache.get(t);if(n===void 0)n=this.extractReadLocatorsFromToolResultContent(e.content),this.readResultLocatorCache.set(t,n);if(n.length>0)return n;return this.readLocatorsByToolUseIdCache.get(e.tool_use_id)??[]}extractLocatorsFromReadToolInput(e){if(!e||typeof e!=="object")return[];let t=e,n=[],r=this.extractLocatorFromReadRequest(t);if(r)n.push(r);if(Array.isArray(t.files))for(let o of t.files){let s=this.extractLocatorFromReadRequest(o);if(s)n.push(s)}if(Array.isArray(t.file_paths)){for(let o of t.file_paths)if(typeof o==="string"&&o.length>0)n.push({path:o,startLine:null,endLine:null})}return this.dedupeReadLocators(n)}extractReadLocatorsFromToolResultContent(e){if(typeof e==="string")return this.tryParseReadLocators(e);let t=[];for(let n of e){if(n.type==="text"){t.push(...this.tryParseReadLocators(n.text));continue}if(cr(n)){let r=this.extractLocatorFromResultEntry(n);if(r)t.push(r)}}return this.dedupeReadLocators(t)}tryParseReadLocators(e){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(e))}catch{return[]}}extractLocatorsFromParsedReadResult(e){if(Array.isArray(e)){let n=[];for(let r of e){let o=this.extractLocatorFromResultEntry(r);if(o)n.push(o)}return this.dedupeReadLocators(n)}let t=this.extractLocatorFromResultEntry(e);return t?[t]:[]}extractLocatorFromReadRequest(e){if(!e||typeof e!=="object")return;let t=e,n=this.extractPath(t);if(!n)return;return{path:n,startLine:this.extractLineNumber(t.start_line),endLine:this.extractLineNumber(t.end_line)}}extractLocatorFromResultEntry(e){if(!e||typeof e!=="object")return;let t=e,n=this.extractPath(t);if(n)return{path:n,startLine:this.extractLineNumber(t.start_line),endLine:this.extractLineNumber(t.end_line)};if(typeof t.query==="string"&&t.query.length>0)return this.parseReadQuery(t.query);return}extractPath(e){let t=[e.path,e.file_path,e.filePath];for(let n of t)if(typeof n==="string"&&n.length>0)return n;return}extractLineNumber(e){return typeof e==="number"&&Number.isInteger(e)?e:null}parseReadQuery(e){let t=/^(.*):(\d+)-(EOF|\d+)$/.exec(e);if(!t)return{path:e,startLine:null,endLine:null};return{path:t[1],startLine:Number(t[2]),endLine:t[3]==="EOF"?null:Number(t[3])}}dedupeReadLocators(e){let t=new Map;for(let n of e)t.set(this.toReadLocatorKey(n),n);return Array.from(t.values())}toReadLocatorKey(e){if(this.isFullFileRead(e))return e.path;return`${e.path}:${e.startLine??1}-${e.endLine??"EOF"}`}isFullFileRead(e){return e.startLine==null&&e.endLine==null}isOutdatedReadLocator(e,t){let n=this.latestFullContentOwnerByPathCache.get(e.path);if(n&&n!==t)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(e))!==t}replaceOutdatedReadContent(e,t){let n=new Set(t.map((s)=>this.toReadLocatorKey(s))),r=new Set(t.map((s)=>s.path));if(typeof e==="string")return this.replaceOutdatedInString(e,n)??Zr;let o=0;for(let s of e)if(s.type==="text")o+=this.countOutdatedImageEntries(s.text,n);return e.map((s)=>{if(s.type==="file"){if(!r.has(s.path))return s;return{...s,content:Zr}}if(s.type==="image"){if(o===0)return s;return o-=1,{type:"text",text:Zr}}if(cr(s))return this.replaceOutdatedReadEntry(s,n);if(s.type!=="text")return s;let i=this.replaceOutdatedInString(s.text,n);if(i===null)return{...s,text:Zr};return i===s.text?s:{...s,text:i}})}countOutdatedImageEntries(e,t){let n;try{n=JSON.parse(e)}catch{return 0}let r=Array.isArray(n)?n:[n],o=0;for(let s of r){if(!s||typeof s!=="object")continue;let i=s,a=this.extractLocatorFromResultEntry(i);if(!a)continue;if(!t.has(this.toReadLocatorKey(a)))continue;if(i.result==="Successfully read image"||i.content==="Successfully read image")o+=1}return o}replaceOutdatedInString(e,t){let n;try{n=JSON.parse(e)}catch{return null}let r=Array.isArray(n)?n.map((o)=>this.replaceOutdatedReadEntry(o,t)):this.replaceOutdatedReadEntry(n,t);return JSON.stringify(r)}replaceOutdatedReadEntry(e,t){if(!e||typeof e!=="object")return e;let n=this.extractLocatorFromResultEntry(e);if(!n||!t.has(this.toReadLocatorKey(n)))return e;let r={...e};if(typeof r.result==="string")r.result=Zr;else if(typeof r.content==="string")r.content=Zr;else r.result=Zr;return r}isReadTool(e){return!!e&&oW.has(e)}resolveToolName(e){let t=this.toolNameByIdCache.get(e.tool_use_id);if(t!==void 0)return t;return typeof e.name==="string"&&e.name.length>0?e.name.toLowerCase():void 0}truncateToolResultContent(e){if(typeof e==="string")return this.truncateMiddle(e);return e.map((t)=>{if(t.type==="file"){let n=this.truncateMiddle(t.content);return n===t.content?t:{...t,content:n}}if(t.type==="text"){let n=this.truncateMiddle(t.text);return n===t.text?t:{...t,text:n}}if(cr(t))return this.truncateNestedStrings(t);return t})}truncateNestedStrings(e){if(typeof e==="string")return this.truncateMiddle(e);if(Array.isArray(e)){let t=!1,n=e.map((r)=>{let o=this.truncateNestedStrings(r);if(o!==r)t=!0;return o});return t?n:e}if(e!==null&&typeof e==="object"){if(yf(e))return e;let t=!1,n={};for(let[r,o]of Object.entries(e)){let s=this.truncateNestedStrings(o);if(s!==o)t=!0;n[r]=s}return t?n:e}return e}truncateMiddle(e){return bs(e,this.maxToolResultChars,vk)}truncateAssistantText(e){if(this.hasRepeatedToolCallMarkup(e))return bs(e,this.maxAssistantToolMarkupChars,iW);return bs(e,this.maxAssistantTextChars,sW)}hasRepeatedToolCallMarkup(e){if(e.length<=this.maxAssistantToolMarkupChars)return!1;let t=0;for(let n of e.matchAll(aW))if(t+=1,t>=rW)return!0;return!1}truncateToTotalTextBudget(e){let t=this.countMessageTextBytes(e);if(t<=this.maxTotalTextBytes)return e;let n=e.map((o)=>{if(!Array.isArray(o.content))return{...o};return{...o,content:o.content.map((s)=>lW(s))}}),r=this.collectTruncationCandidates(n);for(let o of r){if(t<=this.maxTotalTextBytes)break;let s=o.byteLength;if(s<=o.minBytes)continue;let i=t-this.maxTotalTextBytes,a=Math.max(o.minBytes,s-i),d=uW(o.get(),a,o.makeMarker);o.set(d),t-=s-Te(d)}return n}countMessageTextBytes(e){let t=0;for(let n of e){if(typeof n.content==="string"){t+=Te(n.content);continue}for(let r of n.content)if(r.type==="text")t+=Te(r.text);else if(r.type==="thinking")t+=Te(r.thinking);else if(r.type==="file")t+=Te(r.content);else if(r.type==="tool_use")t+=Su(r.input);else if(r.type==="tool_result"){if(typeof r.content==="string")t+=Te(r.content);else for(let o of r.content)if(o.type==="text")t+=Te(o.text);else if(o.type==="file")t+=Te(o.content);else if(cr(o))t+=Su(o)}}return t}collectTruncationCandidates(e){let t=[],n=[];for(let r of e){if(r.role==="assistant"&&typeof r.content==="string"){t.push({byteLength:Te(r.content),minBytes:Sk,makeMarker:Tk,get:()=>r.content,set:(o)=>{r.content=o}});continue}if(!Array.isArray(r.content))continue;for(let o of r.content){if(o.type==="tool_use"){bu(o.input,n);continue}if(r.role==="assistant"&&o.type==="text"){t.push({byteLength:Te(o.text),minBytes:Sk,makeMarker:Tk,get:()=>o.text,set:(s)=>{o.text=s}});continue}if(o.type!=="tool_result")continue;if(typeof o.content==="string"){t.push({byteLength:Te(o.content),minBytes:aa,makeMarker:da,get:()=>o.content,set:(s)=>{o.content=s}});continue}for(let s of o.content)if(s.type==="text")t.push({byteLength:Te(s.text),minBytes:aa,makeMarker:da,get:()=>s.text,set:(i)=>{s.text=i}});else if(s.type==="file")t.push({byteLength:Te(s.content),minBytes:aa,makeMarker:da,get:()=>s.content,set:(i)=>{s.content=i}});else if(cr(s))bu(s,t)}}return t.sort((r,o)=>o.byteLength-r.byteLength),n.sort((r,o)=>o.byteLength-r.byteLength),[...t,...n]}applyMediaBudget(e){let t=this.resolveMediaBudget();if(t.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&t.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&t.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return e;let n=V$(),r=!1,o=e.map((s)=>{if(!Array.isArray(s.content))return s;let i=!1,a=s.content.map((d)=>{let c=this.applyMediaBudgetToBlock(d,t,n);if(c!==d)i=!0;return c});if(!i)return s;return r=!0,{...s,content:a}});return r?o:e}resolveMediaBudget(){return J$(this.mediaBudget)}applyMediaBudgetToBlock(e,t,n){if(ff(e))return this.limitImageContent(e,t,n);if(e.type!=="tool_result"||typeof e.content==="string")return e;let r=!1,o=e.content.map((s)=>{let i=this.applyMediaBudgetToToolResultEntry(s,t,n);if(i!==s)r=!0;return i});return r?{...e,content:o}:e}applyMediaBudgetToToolResultEntry(e,t,n){if(ff(e))return this.limitImageContent(e,t,n);if(cr(e))return this.limitNestedMedia(e,t,n);return e}limitNestedMedia(e,t,n){if(ff(e)){let r=this.limitImageContent(e,t,n);return r.type==="text"?r.text:r}if(Array.isArray(e)){let r=!1,o=e.map((s)=>{let i=this.limitNestedMedia(s,t,n);if(i!==s)r=!0;return i});return r?o:e}if(e!==null&&typeof e==="object"){let r=!1,o={};for(let[s,i]of Object.entries(e)){let a=this.limitNestedMedia(i,t,n);if(a!==i)r=!0;o[s]=a}return r?o:e}return e}limitImageContent(e,t,n){if(!Ik(e))return{type:"text",text:hk};let r=X$(e.mediaType,e.data,{maxImageEncodedBytes:t.maxImageEncodedBytes,maxImageDecodedBytes:t.maxImageDecodedBytes,maxTotalMediaBytes:t.maxTotalMediaBytes},n);if(!r.ok)return{type:"text",text:hk};return{...e,data:r.base64,mediaType:r.mediaType}}}var wk=String.raw`[\|\uFF5C]`,aW=new RegExp(String.raw`<\s*(?:${wk}\s*)?DSML\s*(?:${wk}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function Te(e){return Buffer.byteLength(e,"utf8")}function Ck(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function dW(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="infinity"||t==="disable")return Number.POSITIVE_INFINITY;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:void 0}function ia(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0?Math.floor(e):t}function cW(e,t){if(typeof e!=="number"||Number.isNaN(e)||e<0)return t;return Number.isFinite(e)?Math.floor(e):e}function bs(e,t,n){if(e.length<=t)return e;let r=n(e.length-t),o=Math.max(0,Math.floor((t-r.length)/2)),s=Math.max(0,e.length-o*2),i=n(s),a=Math.max(0,Math.floor((t-i.length)/2)),d=e.slice(0,a),c=a>0?e.slice(-a):"";return`${d}${i}${c}`}function uW(e,t,n){if(Te(e)<=t)return e;let r=0,o=e.length,s=bs(e,0,n);while(r<=o){let i=r+o>>>1,a=bs(e,i,n);if(Te(a)<=t)s=a,r=i+1;else o=i-1}return s}function lW(e){if(e.type==="tool_use")return{...e,input:vu(e.input)};if(e.type!=="tool_result"||typeof e.content==="string")return{...e};return{...e,content:e.content.map((t)=>cr(t)?vu(t):{...t})}}function cr(e){if(e===null||typeof e!=="object")return!1;let t=e.type;return t!=="text"&&t!=="image"&&t!=="file"}function ff(e){return e!==null&&typeof e==="object"&&e.type==="image"}function Ik(e){return e!==null&&typeof e==="object"&&e.type==="image"&&typeof e.data==="string"&&typeof e.mediaType==="string"}function yf(e){return Ik(e)}function Su(e){if(typeof e==="string")return Te(e);if(Array.isArray(e)){let t=0;for(let n of e)t+=Su(n);return t}if(e!==null&&typeof e==="object"){if(yf(e))return 0;let t=0;for(let n of Object.values(e))t+=Su(n);return t}return 0}function bu(e,t){if(Array.isArray(e)){e.forEach((n,r)=>{if(typeof n==="string")t.push({byteLength:Te(n),minBytes:aa,makeMarker:da,get:()=>e[r],set:(o)=>{e[r]=o}});else bu(n,t)});return}if(e!==null&&typeof e==="object"){if(yf(e))return;let n=e;for(let r of Object.keys(n)){let o=n[r];if(typeof o==="string")t.push({byteLength:Te(o),minBytes:aa,makeMarker:da,get:()=>n[r],set:(s)=>{n[r]=s}});else bu(o,t)}}}function vu(e){if(Array.isArray(e))return e.map(vu);if(e!==null&&typeof e==="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=vu(r);return t}return e}function Sf(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class bf{messages=[];conversationId=Sf();sessionStarted=!1;constructor(e){if((e?.length??0)>0)this.restore(e??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(e){this.messages.push(e)}appendMessages(e){if(e.length===0)return;this.messages.push(...e)}replaceMessages(e){let t=new Map(e.map((o,s)=>[o.id,s])),n=new Map,r=-1;for(let o of this.messages){let s=o.id?t.get(o.id):void 0;if(s!==void 0)r=s;else if(o.metadata?.displayOnly===!0){let i=n.get(r)??[];i.push(o),n.set(r,i)}}this.messages=[...n.get(-1)??[]];for(let[o,s]of e.entries())this.messages.push(s,...n.get(o)??[])}resetForRun(){this.messages=[],this.conversationId=Sf(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=Sf(),this.sessionStarted=!1}restore(e){this.messages=[...e],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}var ur="0.0.88-nightly.1790735522";var lr={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:ur,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",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:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","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:*","@modelcontextprotocol/sdk":"^1.29.0","@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:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};function Ak(e){let{agentConfig:t}=e,n=pW(t),r=mW(t),o=e.hooks,s=gW(t.maxParallelToolCalls);return{distinctId:t.distinctId,clientName:t.extensionContext?.client?.name,clientVersion:t.extensionContext?.client?.version,clineCoreVersion:ur,sessionId:e.sessionId??t.sessionId,agentId:e.agentId,conversationId:e.conversationId,parentAgentId:e.parentAgentId,agentRole:e.agentRole,systemPrompt:e.systemPrompt??t.systemPrompt,messageModelInfo:r,model:e.model,modelOptions:n,modelTools:t.modelTools,tools:e.tools,hooks:o,prepareTurn:e.prepareTurn,consumePendingUserMessage:t.consumePendingUserMessage,plugins:e.plugins,logger:e.logger??t.logger,telemetry:e.telemetry??t.telemetry,initialMessages:e.initialMessages,completionPolicy:e.completionPolicy===null?void 0:e.completionPolicy??t.completionPolicy,maxIterations:t.maxIterations,toolExecution:s,toolPolicies:t.toolPolicies,toolContextMetadata:e.toolContextMetadata,requestToolApproval:t.requestToolApproval}}function pW(e){let t={};if(e.thinking!==void 0)t.thinking=e.thinking;if(e.reasoningEffort!==void 0)t.reasoningEffort=e.reasoningEffort;if(e.thinkingBudgetTokens!==void 0)t.thinkingBudgetTokens=e.thinkingBudgetTokens;if(e.maxTokensPerTurn!==void 0)t.maxTokensPerTurn=e.maxTokensPerTurn;if(e.temperature!==void 0)t.temperature=e.temperature;if(e.apiTimeoutMs!==void 0)t.apiTimeoutMs=e.apiTimeoutMs;return Object.keys(t).length>0?t:void 0}function mW(e){let t=e.providerConfig?.family;return{id:e.modelId,provider:e.providerId,family:t}}function gW(e){if(e===void 0)return;return e>=2?"parallel":"sequential"}function fW(e){let t={};if(e.providerId!==void 0)t.providerId=e.providerId;if(e.modelId!==void 0)t.modelId=e.modelId;if(e.apiKey!==void 0)t.apiKey=e.apiKey;if(e.baseUrl!==void 0)t.baseUrl=e.baseUrl;if(e.headers!==void 0)t.headers=e.headers;if(e.providerConfig!==void 0)t.providerConfig=e.providerConfig;if(e.thinking===!1)return t.thinking=!1,t.reasoningEffort=null,t.thinkingBudgetTokens=null,t;if(e.thinking===!0)t.thinking=!0,t.reasoningEffort=e.reasoningEffort??null,t.thinkingBudgetTokens=null;else if(e.reasoningEffort!==void 0)t.thinking=!0,t.reasoningEffort=e.reasoningEffort;if(typeof e.thinkingBudgetTokens==="number"&&Number.isFinite(e.thinkingBudgetTokens)&&e.thinkingBudgetTokens>0)t.thinking=!0,t.thinkingBudgetTokens=Math.trunc(e.thinkingBudgetTokens);return t}function vs(e){let t={...e},n=Object.hasOwn(e,"thinking"),r=Object.hasOwn(e,"thinkingBudgetTokens");if(e.thinking===!1||e.thinking===null)return t.reasoningEffort=void 0,t.thinkingBudgetTokens=void 0,t;if(!n&&r&&typeof e.thinkingBudgetTokens==="number"&&Number.isFinite(e.thinkingBudgetTokens)&&e.thinkingBudgetTokens>0)t.thinking=!0;return t}function hW(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function yW(e){e.lastToolName="",e.lastToolSignature="",e.consecutiveIdenticalCount=0}function vf(e){if(e==null||typeof e!=="object")return e;if(Array.isArray(e))return e.map(vf);let t={};for(let n of Object.keys(e).sort())t[n]=vf(e[n]);return t}function SW(e){if(e==null)return"null";if(typeof e==="string")return e;if(typeof e!=="object")return String(e);try{return JSON.stringify(vf(e))}catch{return String(e)}}function bW(e,t,n,r){if(t===e.lastToolName&&n===e.lastToolSignature)e.consecutiveIdenticalCount++;else e.consecutiveIdenticalCount=1;return e.lastToolName=t,e.lastToolSignature=n,{softWarning:e.consecutiveIdenticalCount===r.softThreshold,hardEscalation:e.consecutiveIdenticalCount>=r.hardThreshold}}var Rk={softThreshold:3,hardThreshold:5};class Tf{config;state=hW();constructor(e){this.config={softThreshold:e?.softThreshold??Rk.softThreshold,hardThreshold:e?.hardThreshold??Rk.hardThreshold}}inspect(e){let t=SW(e.input),n=bW(this.state,e.name,t,this.config);if(n.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${e.name}\`; stopping to avoid a loop.`};if(n.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${e.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){yW(this.state)}}class wf{consecutiveMistakes=0;options;constructor(e){this.options=e}async record(e){let t=this.options.maxConsecutiveMistakes,n=e.forceAtLimit&&t?t:this.consecutiveMistakes+1;this.consecutiveMistakes=n;let r=e.details?.trim()||`consecutive mistake (${e.reason})`;if(this.options.emit({type:"error",error:Error(r),recoverable:!0,iteration:e.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:e.iteration,reason:e.reason,details:e.details,consecutiveMistakes:n,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!t||n<t)return{action:"continue"};let o={iteration:e.iteration,consecutiveMistakes:n,maxConsecutiveMistakes:t,reason:e.reason,details:e.details};this.options.onLimitTelemetry?.(o);let s=await TW(o,this.options.onLimitReached);if(s.action==="continue"){let i=s.guidance?.trim();if(i)this.options.appendRecoveryNotice(i,e.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:i}}return{action:"stop",reason:s.reason?.trim()||void 0,message:vW({iteration:e.iteration,consecutiveMistakes:n,maxConsecutiveMistakes:t,reason:e.reason,details:e.details,stopReason:s.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function vW(e){let t=[`Stopped after ${e.consecutiveMistakes}/${e.maxConsecutiveMistakes} consecutive mistakes (${e.reason}) at iteration ${e.iteration}.`],n=e.details?.trim();if(n)t.push(`Error: ${n}`);let r=e.stopReason?.trim();if(r)t.push(`Decision: ${r}`);return t.push("Session state was preserved. Send a new prompt to resume from the latest state."),t.join(" ")}async function TW(e,t){if(!t)return{action:"stop",reason:`maximum consecutive mistakes reached (${e.maxConsecutiveMistakes})`};try{return await t(e)}catch(n){return{action:"stop",reason:n instanceof Error?n.message:`maximum consecutive mistakes reached (${e.maxConsecutiveMistakes})`}}}function wW(e){switch(e){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return e;default:return}}function CW(e){let t=e.content.filter((n)=>n.type==="text");if(t.length===0)return;return t.map((n)=>n.text).join("")}function kW(e){let t=e.content.filter((n)=>n.type==="reasoning");if(t.length===0)return;return{reasoning:t.map((n)=>n.text).join(""),redacted:t.some((n)=>n.redacted===!0)}}function IW(e){return e.content.find((t)=>t.type==="tool-result")}function PW(e){switch(e){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function AW(e){if(!e||e.isError!==!0)return;if(typeof e.output==="string")return e.output;if(e.output instanceof Error)return e.output.message;try{return JSON.stringify(e.output)}catch{return String(e.output)}}class Cf{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0,reasoningTokenCount:0};toolStartedAt=new Map;translate(e){switch(e.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:e.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:e.iteration,hadToolCalls:e.toolCallCount>0,toolCallCount:e.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:e.text,accumulated:e.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:e.text,redacted:e.redacted===!0}];case"assistant-media":return[{type:"content_end",contentType:"media",media:e.media}];case"assistant-message":return this.translateAssistantMessage(e.message);case"tool-started":return this.translateToolStarted(e);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,update:e.update}];case"tool-finished":return this.translateToolFinished(e);case"usage-updated":return this.translateUsage(e.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:e.message,reason:wW(e.metadata?.reason),metadata:e.metadata}];case"run-finished":return this.translateRunFinished(e.result);case"run-failed":return[{type:"error",error:e.error,errorClass:e.errorClass,recoverable:!1,iteration:e.snapshot.iteration}];default:return e}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0,reasoningTokenCount:0},this.toolStartedAt.clear()}translateAssistantMessage(e){let t=[],n=CW(e);if(n!==void 0)t.push({type:"content_end",contentType:"text",text:n});let r=kW(e);if(r!==void 0)t.push({type:"content_end",contentType:"reasoning",reasoning:r.reasoning});return t}translateToolStarted(e){return this.toolStartedAt.set(e.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input,execution:e.toolCall.execution}]}translateToolFinished(e){let t=this.toolStartedAt.get(e.toolCall.toolCallId),n=t===void 0?void 0:Date.now()-t;this.toolStartedAt.delete(e.toolCall.toolCallId);let r=IW(e.message),o=r?.output,s=AW(r);return[{type:"content_end",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,output:o,error:s,durationMs:n,execution:e.toolCall.execution}]}translateUsage(e){let t=e.inputTokens-this.lastUsage.inputTokens,n=e.outputTokens-this.lastUsage.outputTokens,r=e.cacheReadTokens-this.lastUsage.cacheReadTokens,o=e.cacheWriteTokens-this.lastUsage.cacheWriteTokens,s=this.lastUsage.totalCost??0,a=(e.totalCost??0)-s,d=this.lastUsage.reasoningTokenCount??0,u=(e.reasoningTokenCount??0)-d;return this.lastUsage={inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,totalCost:e.totalCost,reasoningTokenCount:e.reasoningTokenCount},[{type:"usage",inputTokens:Math.max(0,t),outputTokens:Math.max(0,n),cacheReadTokens:r===0?void 0:Math.max(0,r),cacheWriteTokens:o===0?void 0:Math.max(0,o),cost:a===0?void 0:a,reasoningTokenCount:u===0?void 0:Math.max(0,u),totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalCacheReadTokens:e.cacheReadTokens===0?void 0:e.cacheReadTokens,totalCacheWriteTokens:e.cacheWriteTokens===0?void 0:e.cacheWriteTokens,totalCost:e.totalCost}]}translateRunFinished(e){let t={inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens,cacheReadTokens:e.usage.cacheReadTokens===0?void 0:e.usage.cacheReadTokens,cacheWriteTokens:e.usage.cacheWriteTokens===0?void 0:e.usage.cacheWriteTokens,totalCost:e.usage.totalCost};return[{type:"done",reason:PW(e.status),text:e.outputText,iterations:e.iterations,usage:t}]}}var HW="session_run_in_progress";class Ok extends Error{agentId;code=HW;constructor(e){super(`SessionRuntime.shutdown called while a run is in progress${e?` (agentId=${e})`:""}`);this.agentId=e;this.name="SessionRunInProgressError"}}function UW(e){if(typeof e==="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}async function FW(e){let n=(typeof e.content==="function"?await e.content():e.content).trim();return n.length>0?n:void 0}function BW(e,t){let n=e.trim(),r=t.map((o)=>o.trim()).filter(Boolean).join(`
201
+ `;function kk(e=process.env){return{maxToolResultChars:Ck(e[gf.maxToolResultChars]),maxTotalTextBytes:Ck(e[gf.maxTotalTextBytes]),minOutdatedRewriteBytes:dW(e[gf.minOutdatedRewriteBytes])}}class hf{indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor(e={}){this.maxToolResultChars=ia(e.maxToolResultChars,Y$),this.maxFileContentChars=ia(e.maxFileContentChars,Q$),this.maxTotalTextBytes=ia(e.maxTotalTextBytes,Z$),this.mediaBudget=e.mediaBudget??{},this.maxAssistantTextChars=ia(e.maxAssistantTextChars,eW),this.maxAssistantToolMarkupChars=ia(e.maxAssistantToolMarkupChars,tW),this.minOutdatedRewriteBytes=cW(e.minOutdatedRewriteBytes,nW)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi(e){this.reindex(e),this.commitOutdatedRewrites(e);let n=this.addMissingToolResults(e).map((o)=>{if(!Array.isArray(o.content)){if(o.role==="user"&&typeof o.content==="string"){let a=yk(o.content);if(a!==o.content)return{...o,content:a}}if(o.role==="assistant"&&typeof o.content==="string"){let a=this.truncateAssistantText(o.content);if(a!==o.content)return{...o,content:a}}return o}let s=!1,i=o.content.map((a)=>{let d=this.transformBlock(a,o.role);if(d!==a)s=!0;return d});return s?{...o,content:i}:o}),r=this.applyMediaBudget(n);return this.truncateToTotalTextBudget(r)}transformBlock(e,t){if(t==="user"&&e.type==="text"&&typeof e.text==="string"){let o=yk(e.text);if(o!==e.text)return{...e,text:o};return e}if(t==="assistant"&&e.type==="text"&&typeof e.text==="string"){let o=this.truncateAssistantText(e.text);return o===e.text?e:{...e,text:o}}if(e.type==="file"){let o=bs(e.content,this.maxFileContentChars,vk);return o===e.content?e:{...e,content:o}}if(e.type!=="tool_result")return e;let n=this.resolveToolName(e),r=e.content;if(this.isReadTool(n)&&e.is_error!==!0){let o=this.committedOutdatedRewrites.get(e.tool_use_id);if(o&&o.size>0){let i=this.getReadLocators(e).filter((a)=>o.has(this.toReadLocatorKey(a))&&this.isOutdatedReadLocator(a,e.tool_use_id));if(i.length>0)r=this.replaceOutdatedReadContent(r,i)}}return r=this.truncateToolResultContent(r),r===e.content?e:{...e,content:r}}reindex(e){let t=this.indexedMessageCount===0||e.length>=this.indexedMessageCount&&e[this.indexedMessageCount-1]===this.indexedTailRef;if(e.length<this.indexedMessageCount||!t)this.resetIndexes();for(let n=this.indexedMessageCount;n<e.length;n++){let r=e[n];if(!Array.isArray(r.content))continue;for(let o=0;o<r.content.length;o++){let s=r.content[o];if(s.type==="file")this.latestFullContentOwnerByPathCache.set(s.path,`file:${n}:${o}`);else if(s.type==="tool_use"){let i=s.name.toLowerCase();if(this.toolNameByIdCache.set(s.id,i),this.isReadTool(i)){let a=this.extractLocatorsFromReadToolInput(s.input);if(a.length>0)this.readLocatorsByToolUseIdCache.set(s.id,a)}}else if(s.type==="tool_result"){let i=this.resolveToolName(s);if(!this.isReadTool(i)||s.is_error===!0)continue;let a=this.getReadLocators(s);for(let d of a)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(d),s.tool_use_id),this.isFullFileRead(d))this.latestFullContentOwnerByPathCache.set(d.path,s.tool_use_id)}}}this.indexedMessageCount=e.length,this.indexedTailRef=e.length>0?e[e.length-1]:void 0}commitOutdatedRewrites(e){let t=new Map,n=new Set,r=0;for(let o of e){if(!Array.isArray(o.content))continue;for(let s of o.content){if(s.type!=="tool_result"||s.is_error===!0)continue;let i=this.resolveToolName(s);if(!this.isReadTool(i))continue;n.add(s.tool_use_id);let a=this.committedOutdatedRewrites.get(s.tool_use_id),d=new Set,c=new Set;for(let l of this.getReadLocators(s)){let p=this.toReadLocatorKey(l);if(!this.isOutdatedReadLocator(l,s.tool_use_id))continue;if(c.add(p),!a?.has(p))d.add(p)}if(a){for(let l of a)if(!c.has(l))a.delete(l);if(a.size===0)this.committedOutdatedRewrites.delete(s.tool_use_id)}if(d.size===0)continue;let u=t.get(s.tool_use_id);if(!u)u=new Set,t.set(s.tool_use_id,u);for(let l of d)u.add(l);r+=this.estimateOutdatedReclaimBytes(s.content,d)}}for(let o of this.committedOutdatedRewrites.keys())if(!n.has(o))this.committedOutdatedRewrites.delete(o);if(t.size===0||r<this.minOutdatedRewriteBytes)return;for(let[o,s]of t){let i=this.committedOutdatedRewrites.get(o);if(!i)i=new Set,this.committedOutdatedRewrites.set(o,i);for(let a of s)i.add(a)}}estimateOutdatedReclaimBytes(e,t){let n=this.extractReadLocatorsFromToolResultContent(e),r=n.length>0&&n.every((d)=>t.has(this.toReadLocatorKey(d))),o=(d)=>{let c;try{c=JSON.parse(d)}catch{return r||n.length===0?Te(this.truncateMiddle(d)):0}let u=Array.isArray(c)?c:[c],l=0;for(let p of u){let m=this.extractLocatorFromResultEntry(p);if(m&&t.has(this.toReadLocatorKey(m)))l+=this.providerBoundEntryBytes(p)}return l};if(typeof e==="string")return o(e);let s=new Set(t),i=0;for(let d of e)if(d.type==="text")i+=this.countOutdatedImageEntries(d.text,s);let a=0;for(let d of e)if(d.type==="text")a+=o(d.text);else if(d.type==="image"){if(i>0)i-=1,a+=Te(d.data)}else if(cr(d)){let c=this.extractLocatorFromResultEntry(d);if(c&&t.has(this.toReadLocatorKey(c)))a+=this.providerBoundEntryBytes(d)}else if(d.type==="file"){if(t.has(this.toReadLocatorKey({path:d.path,startLine:null,endLine:null})))a+=Te(this.truncateMiddle(d.content))}return a}providerBoundEntryBytes(e){let t=this.truncateNestedStrings(e);return Te(JSON.stringify(t))}addMissingToolResults(e){let t=this.collectToolResultIds(e),n=[],r=new Map,o=!1,s=()=>{if(r.size===0)return;i(this.createMissingToolResultMessage(r)),r.clear(),o=!0},i=(a)=>{let d=n.at(-1);if(this.shouldMergeUserAfterToolResults(d,a)){n[n.length-1]={...d,content:[...d.content,...this.contentBlocksForUserMerge(a.content)]},o=!0;return}n.push(a)};for(let a of e){if(this.isToolResultOnlyMessage(a)){if(i(this.appendMissingToolResults(a,r)),r.size>0)r.clear(),o=!0;continue}if(Array.isArray(a.content)){let d=a.content.filter((u)=>u.type==="tool_result"),c=a.content.filter((u)=>u.type!=="tool_result");if(d.length>0){let u=this.appendMissingToolResults({...a,role:"user",content:d},r);if(i(u),r.size>0)r.clear();o=!0}if(c.length>0||d.length===0){if(d.length===0)s();let u=d.length>0?{...a,content:c}:a;if(i(u),u.role==="assistant")this.trackMissingToolCalls(u,t,r)}continue}s(),i(a)}return s(),o?n:e}appendMissingToolResults(e,t){if(t.size===0||!Array.isArray(e.content))return e;return{...e,role:"user",content:[...e.content,...this.createMissingToolResultBlocks(t)]}}shouldMergeUserAfterToolResults(e,t){return e?.role==="user"&&t.role==="user"&&this.isToolResultOnlyMessage(e)&&this.contentBlocksForUserMerge(t.content).length>0}contentBlocksForUserMerge(e){return typeof e==="string"?e.length>0?[{type:"text",text:e}]:[]:e}collectToolResultIds(e){let t=new Set;for(let n of e){if(!Array.isArray(n.content))continue;for(let r of n.content)if(r.type==="tool_result")t.add(r.tool_use_id)}return t}isToolResultOnlyMessage(e){return e.role==="user"&&Array.isArray(e.content)&&e.content.length>0&&e.content.every((t)=>t.type==="tool_result")}trackMissingToolCalls(e,t,n){if(!Array.isArray(e.content))return;for(let r of e.content){if(r.type!=="tool_use"||t.has(r.id))continue;n.set(r.id,r.name)}}createMissingToolResultMessage(e){return{role:"user",content:this.createMissingToolResultBlocks(e)}}createMissingToolResultBlocks(e){return Array.from(e,([t,n])=>({type:"tool_result",tool_use_id:t,name:n,content:[{type:"text",text:this.formatMissingToolResultText(n)}],is_error:!0}))}formatMissingToolResultText(e){return e?`${bk} Tool: ${e}.`:bk}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(e){let t=e,n=this.readResultLocatorCache.get(t);if(n===void 0)n=this.extractReadLocatorsFromToolResultContent(e.content),this.readResultLocatorCache.set(t,n);if(n.length>0)return n;return this.readLocatorsByToolUseIdCache.get(e.tool_use_id)??[]}extractLocatorsFromReadToolInput(e){if(!e||typeof e!=="object")return[];let t=e,n=[],r=this.extractLocatorFromReadRequest(t);if(r)n.push(r);if(Array.isArray(t.files))for(let o of t.files){let s=this.extractLocatorFromReadRequest(o);if(s)n.push(s)}if(Array.isArray(t.file_paths)){for(let o of t.file_paths)if(typeof o==="string"&&o.length>0)n.push({path:o,startLine:null,endLine:null})}return this.dedupeReadLocators(n)}extractReadLocatorsFromToolResultContent(e){if(typeof e==="string")return this.tryParseReadLocators(e);let t=[];for(let n of e){if(n.type==="text"){t.push(...this.tryParseReadLocators(n.text));continue}if(cr(n)){let r=this.extractLocatorFromResultEntry(n);if(r)t.push(r)}}return this.dedupeReadLocators(t)}tryParseReadLocators(e){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(e))}catch{return[]}}extractLocatorsFromParsedReadResult(e){if(Array.isArray(e)){let n=[];for(let r of e){let o=this.extractLocatorFromResultEntry(r);if(o)n.push(o)}return this.dedupeReadLocators(n)}let t=this.extractLocatorFromResultEntry(e);return t?[t]:[]}extractLocatorFromReadRequest(e){if(!e||typeof e!=="object")return;let t=e,n=this.extractPath(t);if(!n)return;return{path:n,startLine:this.extractLineNumber(t.start_line),endLine:this.extractLineNumber(t.end_line)}}extractLocatorFromResultEntry(e){if(!e||typeof e!=="object")return;let t=e,n=this.extractPath(t);if(n)return{path:n,startLine:this.extractLineNumber(t.start_line),endLine:this.extractLineNumber(t.end_line)};if(typeof t.query==="string"&&t.query.length>0)return this.parseReadQuery(t.query);return}extractPath(e){let t=[e.path,e.file_path,e.filePath];for(let n of t)if(typeof n==="string"&&n.length>0)return n;return}extractLineNumber(e){return typeof e==="number"&&Number.isInteger(e)?e:null}parseReadQuery(e){let t=/^(.*):(\d+)-(EOF|\d+)$/.exec(e);if(!t)return{path:e,startLine:null,endLine:null};return{path:t[1],startLine:Number(t[2]),endLine:t[3]==="EOF"?null:Number(t[3])}}dedupeReadLocators(e){let t=new Map;for(let n of e)t.set(this.toReadLocatorKey(n),n);return Array.from(t.values())}toReadLocatorKey(e){if(this.isFullFileRead(e))return e.path;return`${e.path}:${e.startLine??1}-${e.endLine??"EOF"}`}isFullFileRead(e){return e.startLine==null&&e.endLine==null}isOutdatedReadLocator(e,t){let n=this.latestFullContentOwnerByPathCache.get(e.path);if(n&&n!==t)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(e))!==t}replaceOutdatedReadContent(e,t){let n=new Set(t.map((s)=>this.toReadLocatorKey(s))),r=new Set(t.map((s)=>s.path));if(typeof e==="string")return this.replaceOutdatedInString(e,n)??Zr;let o=0;for(let s of e)if(s.type==="text")o+=this.countOutdatedImageEntries(s.text,n);return e.map((s)=>{if(s.type==="file"){if(!r.has(s.path))return s;return{...s,content:Zr}}if(s.type==="image"){if(o===0)return s;return o-=1,{type:"text",text:Zr}}if(cr(s))return this.replaceOutdatedReadEntry(s,n);if(s.type!=="text")return s;let i=this.replaceOutdatedInString(s.text,n);if(i===null)return{...s,text:Zr};return i===s.text?s:{...s,text:i}})}countOutdatedImageEntries(e,t){let n;try{n=JSON.parse(e)}catch{return 0}let r=Array.isArray(n)?n:[n],o=0;for(let s of r){if(!s||typeof s!=="object")continue;let i=s,a=this.extractLocatorFromResultEntry(i);if(!a)continue;if(!t.has(this.toReadLocatorKey(a)))continue;if(i.result==="Successfully read image"||i.content==="Successfully read image")o+=1}return o}replaceOutdatedInString(e,t){let n;try{n=JSON.parse(e)}catch{return null}let r=Array.isArray(n)?n.map((o)=>this.replaceOutdatedReadEntry(o,t)):this.replaceOutdatedReadEntry(n,t);return JSON.stringify(r)}replaceOutdatedReadEntry(e,t){if(!e||typeof e!=="object")return e;let n=this.extractLocatorFromResultEntry(e);if(!n||!t.has(this.toReadLocatorKey(n)))return e;let r={...e};if(typeof r.result==="string")r.result=Zr;else if(typeof r.content==="string")r.content=Zr;else r.result=Zr;return r}isReadTool(e){return!!e&&oW.has(e)}resolveToolName(e){let t=this.toolNameByIdCache.get(e.tool_use_id);if(t!==void 0)return t;return typeof e.name==="string"&&e.name.length>0?e.name.toLowerCase():void 0}truncateToolResultContent(e){if(typeof e==="string")return this.truncateMiddle(e);return e.map((t)=>{if(t.type==="file"){let n=this.truncateMiddle(t.content);return n===t.content?t:{...t,content:n}}if(t.type==="text"){let n=this.truncateMiddle(t.text);return n===t.text?t:{...t,text:n}}if(cr(t))return this.truncateNestedStrings(t);return t})}truncateNestedStrings(e){if(typeof e==="string")return this.truncateMiddle(e);if(Array.isArray(e)){let t=!1,n=e.map((r)=>{let o=this.truncateNestedStrings(r);if(o!==r)t=!0;return o});return t?n:e}if(e!==null&&typeof e==="object"){if(yf(e))return e;let t=!1,n={};for(let[r,o]of Object.entries(e)){let s=this.truncateNestedStrings(o);if(s!==o)t=!0;n[r]=s}return t?n:e}return e}truncateMiddle(e){return bs(e,this.maxToolResultChars,vk)}truncateAssistantText(e){if(this.hasRepeatedToolCallMarkup(e))return bs(e,this.maxAssistantToolMarkupChars,iW);return bs(e,this.maxAssistantTextChars,sW)}hasRepeatedToolCallMarkup(e){if(e.length<=this.maxAssistantToolMarkupChars)return!1;let t=0;for(let n of e.matchAll(aW))if(t+=1,t>=rW)return!0;return!1}truncateToTotalTextBudget(e){let t=this.countMessageTextBytes(e);if(t<=this.maxTotalTextBytes)return e;let n=e.map((o)=>{if(!Array.isArray(o.content))return{...o};return{...o,content:o.content.map((s)=>lW(s))}}),r=this.collectTruncationCandidates(n);for(let o of r){if(t<=this.maxTotalTextBytes)break;let s=o.byteLength;if(s<=o.minBytes)continue;let i=t-this.maxTotalTextBytes,a=Math.max(o.minBytes,s-i),d=uW(o.get(),a,o.makeMarker);o.set(d),t-=s-Te(d)}return n}countMessageTextBytes(e){let t=0;for(let n of e){if(typeof n.content==="string"){t+=Te(n.content);continue}for(let r of n.content)if(r.type==="text")t+=Te(r.text);else if(r.type==="thinking")t+=Te(r.thinking);else if(r.type==="file")t+=Te(r.content);else if(r.type==="tool_use")t+=Su(r.input);else if(r.type==="tool_result"){if(typeof r.content==="string")t+=Te(r.content);else for(let o of r.content)if(o.type==="text")t+=Te(o.text);else if(o.type==="file")t+=Te(o.content);else if(cr(o))t+=Su(o)}}return t}collectTruncationCandidates(e){let t=[],n=[];for(let r of e){if(r.role==="assistant"&&typeof r.content==="string"){t.push({byteLength:Te(r.content),minBytes:Sk,makeMarker:Tk,get:()=>r.content,set:(o)=>{r.content=o}});continue}if(!Array.isArray(r.content))continue;for(let o of r.content){if(o.type==="tool_use"){bu(o.input,n);continue}if(r.role==="assistant"&&o.type==="text"){t.push({byteLength:Te(o.text),minBytes:Sk,makeMarker:Tk,get:()=>o.text,set:(s)=>{o.text=s}});continue}if(o.type!=="tool_result")continue;if(typeof o.content==="string"){t.push({byteLength:Te(o.content),minBytes:aa,makeMarker:da,get:()=>o.content,set:(s)=>{o.content=s}});continue}for(let s of o.content)if(s.type==="text")t.push({byteLength:Te(s.text),minBytes:aa,makeMarker:da,get:()=>s.text,set:(i)=>{s.text=i}});else if(s.type==="file")t.push({byteLength:Te(s.content),minBytes:aa,makeMarker:da,get:()=>s.content,set:(i)=>{s.content=i}});else if(cr(s))bu(s,t)}}return t.sort((r,o)=>o.byteLength-r.byteLength),n.sort((r,o)=>o.byteLength-r.byteLength),[...t,...n]}applyMediaBudget(e){let t=this.resolveMediaBudget();if(t.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&t.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&t.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return e;let n=V$(),r=!1,o=e.map((s)=>{if(!Array.isArray(s.content))return s;let i=!1,a=s.content.map((d)=>{let c=this.applyMediaBudgetToBlock(d,t,n);if(c!==d)i=!0;return c});if(!i)return s;return r=!0,{...s,content:a}});return r?o:e}resolveMediaBudget(){return J$(this.mediaBudget)}applyMediaBudgetToBlock(e,t,n){if(ff(e))return this.limitImageContent(e,t,n);if(e.type!=="tool_result"||typeof e.content==="string")return e;let r=!1,o=e.content.map((s)=>{let i=this.applyMediaBudgetToToolResultEntry(s,t,n);if(i!==s)r=!0;return i});return r?{...e,content:o}:e}applyMediaBudgetToToolResultEntry(e,t,n){if(ff(e))return this.limitImageContent(e,t,n);if(cr(e))return this.limitNestedMedia(e,t,n);return e}limitNestedMedia(e,t,n){if(ff(e)){let r=this.limitImageContent(e,t,n);return r.type==="text"?r.text:r}if(Array.isArray(e)){let r=!1,o=e.map((s)=>{let i=this.limitNestedMedia(s,t,n);if(i!==s)r=!0;return i});return r?o:e}if(e!==null&&typeof e==="object"){let r=!1,o={};for(let[s,i]of Object.entries(e)){let a=this.limitNestedMedia(i,t,n);if(a!==i)r=!0;o[s]=a}return r?o:e}return e}limitImageContent(e,t,n){if(!Ik(e))return{type:"text",text:hk};let r=X$(e.mediaType,e.data,{maxImageEncodedBytes:t.maxImageEncodedBytes,maxImageDecodedBytes:t.maxImageDecodedBytes,maxTotalMediaBytes:t.maxTotalMediaBytes},n);if(!r.ok)return{type:"text",text:hk};return{...e,data:r.base64,mediaType:r.mediaType}}}var wk=String.raw`[\|\uFF5C]`,aW=new RegExp(String.raw`<\s*(?:${wk}\s*)?DSML\s*(?:${wk}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function Te(e){return Buffer.byteLength(e,"utf8")}function Ck(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function dW(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="infinity"||t==="disable")return Number.POSITIVE_INFINITY;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:void 0}function ia(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0?Math.floor(e):t}function cW(e,t){if(typeof e!=="number"||Number.isNaN(e)||e<0)return t;return Number.isFinite(e)?Math.floor(e):e}function bs(e,t,n){if(e.length<=t)return e;let r=n(e.length-t),o=Math.max(0,Math.floor((t-r.length)/2)),s=Math.max(0,e.length-o*2),i=n(s),a=Math.max(0,Math.floor((t-i.length)/2)),d=e.slice(0,a),c=a>0?e.slice(-a):"";return`${d}${i}${c}`}function uW(e,t,n){if(Te(e)<=t)return e;let r=0,o=e.length,s=bs(e,0,n);while(r<=o){let i=r+o>>>1,a=bs(e,i,n);if(Te(a)<=t)s=a,r=i+1;else o=i-1}return s}function lW(e){if(e.type==="tool_use")return{...e,input:vu(e.input)};if(e.type!=="tool_result"||typeof e.content==="string")return{...e};return{...e,content:e.content.map((t)=>cr(t)?vu(t):{...t})}}function cr(e){if(e===null||typeof e!=="object")return!1;let t=e.type;return t!=="text"&&t!=="image"&&t!=="file"}function ff(e){return e!==null&&typeof e==="object"&&e.type==="image"}function Ik(e){return e!==null&&typeof e==="object"&&e.type==="image"&&typeof e.data==="string"&&typeof e.mediaType==="string"}function yf(e){return Ik(e)}function Su(e){if(typeof e==="string")return Te(e);if(Array.isArray(e)){let t=0;for(let n of e)t+=Su(n);return t}if(e!==null&&typeof e==="object"){if(yf(e))return 0;let t=0;for(let n of Object.values(e))t+=Su(n);return t}return 0}function bu(e,t){if(Array.isArray(e)){e.forEach((n,r)=>{if(typeof n==="string")t.push({byteLength:Te(n),minBytes:aa,makeMarker:da,get:()=>e[r],set:(o)=>{e[r]=o}});else bu(n,t)});return}if(e!==null&&typeof e==="object"){if(yf(e))return;let n=e;for(let r of Object.keys(n)){let o=n[r];if(typeof o==="string")t.push({byteLength:Te(o),minBytes:aa,makeMarker:da,get:()=>n[r],set:(s)=>{n[r]=s}});else bu(o,t)}}}function vu(e){if(Array.isArray(e))return e.map(vu);if(e!==null&&typeof e==="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=vu(r);return t}return e}function Sf(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class bf{messages=[];conversationId=Sf();sessionStarted=!1;constructor(e){if((e?.length??0)>0)this.restore(e??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(e){this.messages.push(e)}appendMessages(e){if(e.length===0)return;this.messages.push(...e)}replaceMessages(e){let t=new Map(e.map((o,s)=>[o.id,s])),n=new Map,r=-1;for(let o of this.messages){let s=o.id?t.get(o.id):void 0;if(s!==void 0)r=s;else if(o.metadata?.displayOnly===!0){let i=n.get(r)??[];i.push(o),n.set(r,i)}}this.messages=[...n.get(-1)??[]];for(let[o,s]of e.entries())this.messages.push(s,...n.get(o)??[])}resetForRun(){this.messages=[],this.conversationId=Sf(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=Sf(),this.sessionStarted=!1}restore(e){this.messages=[...e],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}var ur="0.0.88";var lr={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:ur,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",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:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","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:*","@modelcontextprotocol/sdk":"^1.29.0","@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:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};function Ak(e){let{agentConfig:t}=e,n=pW(t),r=mW(t),o=e.hooks,s=gW(t.maxParallelToolCalls);return{distinctId:t.distinctId,clientName:t.extensionContext?.client?.name,clientVersion:t.extensionContext?.client?.version,clineCoreVersion:ur,sessionId:e.sessionId??t.sessionId,agentId:e.agentId,conversationId:e.conversationId,parentAgentId:e.parentAgentId,agentRole:e.agentRole,systemPrompt:e.systemPrompt??t.systemPrompt,messageModelInfo:r,model:e.model,modelOptions:n,modelTools:t.modelTools,tools:e.tools,hooks:o,prepareTurn:e.prepareTurn,consumePendingUserMessage:t.consumePendingUserMessage,plugins:e.plugins,logger:e.logger??t.logger,telemetry:e.telemetry??t.telemetry,initialMessages:e.initialMessages,completionPolicy:e.completionPolicy===null?void 0:e.completionPolicy??t.completionPolicy,maxIterations:t.maxIterations,toolExecution:s,toolPolicies:t.toolPolicies,toolContextMetadata:e.toolContextMetadata,requestToolApproval:t.requestToolApproval}}function pW(e){let t={};if(e.thinking!==void 0)t.thinking=e.thinking;if(e.reasoningEffort!==void 0)t.reasoningEffort=e.reasoningEffort;if(e.thinkingBudgetTokens!==void 0)t.thinkingBudgetTokens=e.thinkingBudgetTokens;if(e.maxTokensPerTurn!==void 0)t.maxTokensPerTurn=e.maxTokensPerTurn;if(e.temperature!==void 0)t.temperature=e.temperature;if(e.apiTimeoutMs!==void 0)t.apiTimeoutMs=e.apiTimeoutMs;return Object.keys(t).length>0?t:void 0}function mW(e){let t=e.providerConfig?.family;return{id:e.modelId,provider:e.providerId,family:t}}function gW(e){if(e===void 0)return;return e>=2?"parallel":"sequential"}function fW(e){let t={};if(e.providerId!==void 0)t.providerId=e.providerId;if(e.modelId!==void 0)t.modelId=e.modelId;if(e.apiKey!==void 0)t.apiKey=e.apiKey;if(e.baseUrl!==void 0)t.baseUrl=e.baseUrl;if(e.headers!==void 0)t.headers=e.headers;if(e.providerConfig!==void 0)t.providerConfig=e.providerConfig;if(e.thinking===!1)return t.thinking=!1,t.reasoningEffort=null,t.thinkingBudgetTokens=null,t;if(e.thinking===!0)t.thinking=!0,t.reasoningEffort=e.reasoningEffort??null,t.thinkingBudgetTokens=null;else if(e.reasoningEffort!==void 0)t.thinking=!0,t.reasoningEffort=e.reasoningEffort;if(typeof e.thinkingBudgetTokens==="number"&&Number.isFinite(e.thinkingBudgetTokens)&&e.thinkingBudgetTokens>0)t.thinking=!0,t.thinkingBudgetTokens=Math.trunc(e.thinkingBudgetTokens);return t}function vs(e){let t={...e},n=Object.hasOwn(e,"thinking"),r=Object.hasOwn(e,"thinkingBudgetTokens");if(e.thinking===!1||e.thinking===null)return t.reasoningEffort=void 0,t.thinkingBudgetTokens=void 0,t;if(!n&&r&&typeof e.thinkingBudgetTokens==="number"&&Number.isFinite(e.thinkingBudgetTokens)&&e.thinkingBudgetTokens>0)t.thinking=!0;return t}function hW(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function yW(e){e.lastToolName="",e.lastToolSignature="",e.consecutiveIdenticalCount=0}function vf(e){if(e==null||typeof e!=="object")return e;if(Array.isArray(e))return e.map(vf);let t={};for(let n of Object.keys(e).sort())t[n]=vf(e[n]);return t}function SW(e){if(e==null)return"null";if(typeof e==="string")return e;if(typeof e!=="object")return String(e);try{return JSON.stringify(vf(e))}catch{return String(e)}}function bW(e,t,n,r){if(t===e.lastToolName&&n===e.lastToolSignature)e.consecutiveIdenticalCount++;else e.consecutiveIdenticalCount=1;return e.lastToolName=t,e.lastToolSignature=n,{softWarning:e.consecutiveIdenticalCount===r.softThreshold,hardEscalation:e.consecutiveIdenticalCount>=r.hardThreshold}}var Rk={softThreshold:3,hardThreshold:5};class Tf{config;state=hW();constructor(e){this.config={softThreshold:e?.softThreshold??Rk.softThreshold,hardThreshold:e?.hardThreshold??Rk.hardThreshold}}inspect(e){let t=SW(e.input),n=bW(this.state,e.name,t,this.config);if(n.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${e.name}\`; stopping to avoid a loop.`};if(n.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${e.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){yW(this.state)}}class wf{consecutiveMistakes=0;options;constructor(e){this.options=e}async record(e){let t=this.options.maxConsecutiveMistakes,n=e.forceAtLimit&&t?t:this.consecutiveMistakes+1;this.consecutiveMistakes=n;let r=e.details?.trim()||`consecutive mistake (${e.reason})`;if(this.options.emit({type:"error",error:Error(r),recoverable:!0,iteration:e.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:e.iteration,reason:e.reason,details:e.details,consecutiveMistakes:n,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!t||n<t)return{action:"continue"};let o={iteration:e.iteration,consecutiveMistakes:n,maxConsecutiveMistakes:t,reason:e.reason,details:e.details};this.options.onLimitTelemetry?.(o);let s=await TW(o,this.options.onLimitReached);if(s.action==="continue"){let i=s.guidance?.trim();if(i)this.options.appendRecoveryNotice(i,e.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:i}}return{action:"stop",reason:s.reason?.trim()||void 0,message:vW({iteration:e.iteration,consecutiveMistakes:n,maxConsecutiveMistakes:t,reason:e.reason,details:e.details,stopReason:s.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function vW(e){let t=[`Stopped after ${e.consecutiveMistakes}/${e.maxConsecutiveMistakes} consecutive mistakes (${e.reason}) at iteration ${e.iteration}.`],n=e.details?.trim();if(n)t.push(`Error: ${n}`);let r=e.stopReason?.trim();if(r)t.push(`Decision: ${r}`);return t.push("Session state was preserved. Send a new prompt to resume from the latest state."),t.join(" ")}async function TW(e,t){if(!t)return{action:"stop",reason:`maximum consecutive mistakes reached (${e.maxConsecutiveMistakes})`};try{return await t(e)}catch(n){return{action:"stop",reason:n instanceof Error?n.message:`maximum consecutive mistakes reached (${e.maxConsecutiveMistakes})`}}}function wW(e){switch(e){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return e;default:return}}function CW(e){let t=e.content.filter((n)=>n.type==="text");if(t.length===0)return;return t.map((n)=>n.text).join("")}function kW(e){let t=e.content.filter((n)=>n.type==="reasoning");if(t.length===0)return;return{reasoning:t.map((n)=>n.text).join(""),redacted:t.some((n)=>n.redacted===!0)}}function IW(e){return e.content.find((t)=>t.type==="tool-result")}function PW(e){switch(e){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function AW(e){if(!e||e.isError!==!0)return;if(typeof e.output==="string")return e.output;if(e.output instanceof Error)return e.output.message;try{return JSON.stringify(e.output)}catch{return String(e.output)}}class Cf{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0,reasoningTokenCount:0};toolStartedAt=new Map;translate(e){switch(e.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:e.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:e.iteration,hadToolCalls:e.toolCallCount>0,toolCallCount:e.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:e.text,accumulated:e.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:e.text,redacted:e.redacted===!0}];case"assistant-media":return[{type:"content_end",contentType:"media",media:e.media}];case"assistant-message":return this.translateAssistantMessage(e.message);case"tool-started":return this.translateToolStarted(e);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,update:e.update}];case"tool-finished":return this.translateToolFinished(e);case"usage-updated":return this.translateUsage(e.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:e.message,reason:wW(e.metadata?.reason),metadata:e.metadata}];case"run-finished":return this.translateRunFinished(e.result);case"run-failed":return[{type:"error",error:e.error,errorClass:e.errorClass,recoverable:!1,iteration:e.snapshot.iteration}];default:return e}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0,reasoningTokenCount:0},this.toolStartedAt.clear()}translateAssistantMessage(e){let t=[],n=CW(e);if(n!==void 0)t.push({type:"content_end",contentType:"text",text:n});let r=kW(e);if(r!==void 0)t.push({type:"content_end",contentType:"reasoning",reasoning:r.reasoning});return t}translateToolStarted(e){return this.toolStartedAt.set(e.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input,execution:e.toolCall.execution}]}translateToolFinished(e){let t=this.toolStartedAt.get(e.toolCall.toolCallId),n=t===void 0?void 0:Date.now()-t;this.toolStartedAt.delete(e.toolCall.toolCallId);let r=IW(e.message),o=r?.output,s=AW(r);return[{type:"content_end",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,output:o,error:s,durationMs:n,execution:e.toolCall.execution}]}translateUsage(e){let t=e.inputTokens-this.lastUsage.inputTokens,n=e.outputTokens-this.lastUsage.outputTokens,r=e.cacheReadTokens-this.lastUsage.cacheReadTokens,o=e.cacheWriteTokens-this.lastUsage.cacheWriteTokens,s=this.lastUsage.totalCost??0,a=(e.totalCost??0)-s,d=this.lastUsage.reasoningTokenCount??0,u=(e.reasoningTokenCount??0)-d;return this.lastUsage={inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,totalCost:e.totalCost,reasoningTokenCount:e.reasoningTokenCount},[{type:"usage",inputTokens:Math.max(0,t),outputTokens:Math.max(0,n),cacheReadTokens:r===0?void 0:Math.max(0,r),cacheWriteTokens:o===0?void 0:Math.max(0,o),cost:a===0?void 0:a,reasoningTokenCount:u===0?void 0:Math.max(0,u),totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalCacheReadTokens:e.cacheReadTokens===0?void 0:e.cacheReadTokens,totalCacheWriteTokens:e.cacheWriteTokens===0?void 0:e.cacheWriteTokens,totalCost:e.totalCost}]}translateRunFinished(e){let t={inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens,cacheReadTokens:e.usage.cacheReadTokens===0?void 0:e.usage.cacheReadTokens,cacheWriteTokens:e.usage.cacheWriteTokens===0?void 0:e.usage.cacheWriteTokens,totalCost:e.usage.totalCost};return[{type:"done",reason:PW(e.status),text:e.outputText,iterations:e.iterations,usage:t}]}}var HW="session_run_in_progress";class Ok extends Error{agentId;code=HW;constructor(e){super(`SessionRuntime.shutdown called while a run is in progress${e?` (agentId=${e})`:""}`);this.agentId=e;this.name="SessionRunInProgressError"}}function UW(e){if(typeof e==="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}async function FW(e){let n=(typeof e.content==="function"?await e.content():e.content).trim();return n.length>0?n:void 0}function BW(e,t){let n=e.trim(),r=t.map((o)=>o.trim()).filter(Boolean).join(`
202
202
 
203
203
  `);if(n&&r)return`${n}
204
204
 
@@ -536,7 +536,7 @@ ${JSON.stringify(r,null,2)}`}startClaimLeaseHeartbeat(e){let t=Math.max(1000,Mat
536
536
  `)[0]?.trim())}function Rn(e){if(!e)return;let t={...e},n=mo(typeof t.title==="string"?t.title:void 0);if(n)t.title=n;else delete t.title;return Object.keys(t).length>0?t:void 0}function Ba(e){let t=Rn(e.metadata)??{},n=e.title!==void 0?mo(e.title):Ih(e.prompt);if(n)t.title=n;return Object.keys(t).length>0?t:void 0}function Ph(e){let t=yn(e.metadata),n={source:e.source,mode:t?.mode??"user",sessionId:e.sessionId,...e.parentSessionId?{parentThreadId:e.parentSessionId}:{},...e.agentId?{subagent:e.agentId}:{},...t?.version?{version:t.version}:{},...t?.trigger?{trigger:t.trigger}:{}};if(Ua(e.sessionId))return{agent:"teammate",sessionId:e.sessionId,taskType:"team",origin:n};if(tl(e.sessionId))return{agent:"subagent",sessionId:e.sessionId,taskType:"subagent_task",origin:n};return{agent:"lead",sessionId:e.sessionId,origin:n}}function Ah(e){return{version:1,updated_at:e.updatedAt,agent:e.context.agent,sessionId:e.context.sessionId,...e.context.taskType?{taskType:e.context.taskType}:{},origin:e.context.origin,messages:nl(e.messages),...e.systemPrompt?{system_prompt:e.systemPrompt}:{}}}function oA(e,t,n){$1(j1(e),{recursive:!0}),W1(e,`${JSON.stringify(Ah({updatedAt:t,context:n,messages:[]}),null,2)}
537
537
  `,"utf8")}function sA(e,t){return mt.parse({version:1,session_id:e.sessionId,source:e.source,pid:e.pid,started_at:e.startedAt,ended_at:t?.endedAt??e.endedAt??void 0,exit_code:t?.exitCode??e.exitCode??void 0,status:t?.status??e.status,interactive:e.interactive,provider:e.provider,model:e.model,cwd:e.cwd,workspace_root:e.workspaceRoot,team_name:e.teamName??void 0,enable_tools:e.enableTools,enable_spawn:e.enableSpawn,enable_teams:e.enableTeams,prompt:e.prompt??void 0,metadata:t?.metadata??e.metadata??void 0,messages_path:e.messagesPath??void 0})}async function iA(e,t,n){let r=0;while(!0){let o=await e();if(o===void 0)return{updated:!1};let s=await t(o);if(typeof s==="object"&&s!==null&&"updated"in s&&s.updated===!1){if(r+=1,r>=n)return s;continue}return s}}import{existsSync as V1}from"node:fs";import{readFile as J1}from"node:fs/promises";class $a{listeners=new Set;subscribe(e,t){let n={listener:e,sessionId:t?.sessionId?.trim()||void 0};return this.listeners.add(n),()=>{this.listeners.delete(n)}}emit(e){let t=e.payload.sessionId?.trim();for(let n of this.listeners){if(n.sessionId&&n.sessionId!==t)continue;n.listener(e)}}get size(){return this.listeners.size}}async function Sr(e){let t=e?.trim();if(!t||!V1(t))return[];try{let n=(await J1(t,"utf8")).trim();if(!n)return[];let r=JSON.parse(n);if(Array.isArray(r))return r;if(r&&typeof r==="object"&&!Array.isArray(r)){let o=r.messages;if(Array.isArray(o))return o}return[]}catch{return[]}}function Rh(e){return e?{...e}:void 0}async function aA(e,t){if(!(e.hookName==="tool_call"||!!e.parent_agent_id))return;await t.queueSpawnRequest(e);let r=await t.upsertSubagentSessionFromHook(e);if(!r)return;await t.appendSubagentHookAudit(r,e),await t.applySubagentStatus(r,e)}function Wa(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function Rt(e){let t=Wa(e);if(!t)return;return t.toLowerCase()==="unknown"?void 0:t}function ol(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function Z1(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return{...e}}function _h(e){let t=e??200;return Number.isFinite(t)?Math.max(0,Math.floor(t)):200}var Eh=2000;function eK(e){if(e===0)return 0;return Math.min(Math.max(e*2,20),Eh)}function tK(e){return e.isSubagent!==!0&&!Wa(e.parentSessionId)}function nK(e){let t=e.match(/\d{13,}/g);if(!t||t.length===0)return 0;let n=0;for(let r of t){let o=Number.parseInt(r,10);if(Number.isFinite(o)&&o>n)n=o}return n}function Mh(e){return{sessionId:e.session_id,source:e.source,pid:e.pid,startedAt:e.started_at,endedAt:e.ended_at??null,exitCode:e.exit_code??null,status:e.status,interactive:e.interactive,provider:e.provider,model:e.model,cwd:e.cwd,workspaceRoot:e.workspace_root,teamName:e.team_name,enableTools:e.enable_tools,enableSpawn:e.enable_spawn,enableTeams:e.enable_teams,isSubagent:!1,prompt:e.prompt,metadata:e.metadata,messagesPath:e.messages_path,updatedAt:e.ended_at??e.started_at}}async function rK(e){let t=_h(e);if(t===0)return[];let n=lA(),o=(await X1(n,{withFileTypes:!0}).catch(()=>[])).filter((i)=>i.isDirectory()).map((i)=>({entry:i,recency:nK(i.name.trim())})).sort((i,a)=>a.recency-i.recency||a.entry.name.localeCompare(i.entry.name));return(await Promise.all(o.map(async({entry:i})=>{let a=i.name.trim();if(!a)return;let d=uA(n,a,`${a}.json`),c=await cA(d,"utf8").catch(()=>{return});if(!c)return;let u;try{u=JSON.parse(c)}catch{return}let l=mt.safeParse(u);if(!l.success)return;return Mh(l.data)}))).filter((i)=>Boolean(i)).sort((i,a)=>a.startedAt.localeCompare(i.startedAt)).slice(0,t)}async function oK(e,t,n){let r=_h(t);if(r===0)return await e.listSessions(0),[];if(n.includeSubagents)return(await e.listSessions(r)).slice(0,r);let o=eK(r);for(;;){let s=await e.listSessions(o,{rootOnly:!0}),i=s.filter(tK);if(i.length>=r||s.length<o||o>=Eh)return i.slice(0,r);o=Math.min(o*2,Eh)}}function sK(e){if(typeof e==="string")return e.trim();let t=[];for(let n of e){if(!n||typeof n!=="object")continue;let r=n;if(r.type!=="text")continue;let o=r.text?.trim();if(o)t.push(o)}return t.join(`
538
538
  `).trim()}function dA(e){return e.replace(/\s+/g," ").trim()}function iK(e,t){if(e.length<=t)return e;return`${e.slice(0,Math.max(0,t-3)).trimEnd()}...`}function aK(e){for(let t of["user","assistant"])for(let n of e){if(n.role!==t)continue;let r=dA(sK(n.content));if(!r)continue;let o=t==="user"?dA(Y1(r)):r,s=Q1(o.split(`
539
- `)[0]??o);return iK(s,50)}return}function dK(e){let t=0;for(let n of e)t+=ol(n.metrics?.cost)??0;return t}function cK(e){let t,n;for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(!t)t=Rt(o.modelInfo?.provider);if(!n)n=Rt(o.modelInfo?.id);if(t&&n)break}return{provider:t,model:n}}function uK(e){return Rt(e?.provider)??Rt(e?.provider&&typeof e.provider==="object"&&!Array.isArray(e.provider)?e.provider.id:void 0)}function lK(e){return Rt(e?.model)??Rt(e?.model&&typeof e.model==="object"&&!Array.isArray(e.model)?e.model.id:void 0)}function xh(e,t){let n=Z1(e.metadata),r=Wa(t?.title)??Wa(n?.title),o=ol(t?.totalCost)??ol(n?.totalCost),s=n||r!==void 0||o!==void 0?{...n??{},...r!==void 0?{title:r}:{},...o!==void 0?{totalCost:o}:{}}:void 0;return{...e,provider:Rt(t?.provider)??Rt(e.provider)??uK(n)??"",model:Rt(t?.model)??Rt(e.model)??lK(n)??"",metadata:s}}function pK(e){let t=e.content;if(!Array.isArray(t))return!1;return t.some((n)=>!!n&&typeof n==="object"&&n.type==="tool-call")}function mK(e,t){if(e.status!=="running"||e.interactive!==!0)return!1;let n=t.at(-1);return n?.role==="assistant"&&!pK(n)}async function gK(e,t){return await Promise.all(t.map(async(n)=>{if(n.status!=="running"||n.interactive!==!0)return n;let r=await e.readSessionMessages(n.sessionId);return mK(n,r)?{...n,status:"idle"}:n}))}async function fK(e,t){return await Promise.all(t.map(async(n)=>{let r=xh(n),o=Boolean(Wa(r.metadata?.title)),s=Boolean(Rt(r.provider)),i=Boolean(Rt(r.model)),a=ol(r.metadata?.totalCost),d=a!==void 0&&a>0;if(o&&s&&i&&d)return r;let c=await e.readSessionMessages(n.sessionId);if(c.length===0)return r;let u=cK(c),l=dK(c);return xh(n,{title:o?void 0:aK(c),provider:s?void 0:u.provider,model:i?void 0:u.model,totalCost:d||l<=0?void 0:l})}))}async function Oh(e,t={}){let n=_h(t.limit),r=t.includeSubagents===!0,o=await oK(e,n,{includeSubagents:r}),s=t.includeManifestFallback===!0&&o.length<n?await rK(Math.min(Math.max(n*2,100),500)):[],i=new Map;for(let c of[...o,...s]){if(i.has(c.sessionId))continue;i.set(c.sessionId,c)}let a=s.length===0?o:Array.from(i.values()).sort((c,u)=>u.startedAt.localeCompare(c.startedAt)).slice(0,n),d=await gK(e,a);if(t.hydrate===!1)return d.map((c)=>xh(c));return await fK(e,d)}async function hK(e){let t=e.trim();if(!t)return;let n=uA(lA(),t,`${t}.json`),r=await cA(n,"utf8").catch(()=>{return});if(!r)return;try{let o=mt.safeParse(JSON.parse(r));return o.success?o.data.messages_path:void 0}catch{return}}async function yK(e,t={}){let n=new Map;return await Oh({listSessions:async(o,s)=>{let i=await e.listSessions(o,s);n.clear();for(let a of i)n.set(a.sessionId,a);return i.map(Fa)},readSessionMessages:async(o)=>{let s=n.get(o)?.messagesPath??await hK(o);return await Sr(s)}},t)}import{captureSdkError as h_}from"@cline/shared";import{createSessionId as xG,ensureLoopbackProxyBypass as HA,isHubProtocolCompatible as _G,resolveClineBuildEnv as MG,resolveHubCommandTimeoutMs as OG}from"@cline/shared";import LG from"ws";import{spawn as YK}from"node:child_process";import{closeSync as QK,mkdirSync as ZK,openSync as eG,readFileSync as tG,unlinkSync as nG}from"node:fs";import{basename as rG,dirname as oG,join as sG}from"node:path";import{fileURLToPath as iG}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as aG,isBunEmbeddedModulePath as dG,isHubDaemonProcess as EA,resolveClineBuildEnv as xA,withResolvedClineBuildEnv as cG}from"@cline/shared";import{createHash as SK,randomBytes as yA}from"node:crypto";import{existsSync as bK}from"node:fs";import{mkdir as Nh,open as pA,readFile as SA,rename as vK,rm as sl,writeFile as TK}from"node:fs/promises";import{dirname as bA,join as Dh}from"node:path";import{ensureLoopbackProxyBypass as wK,isHubProtocolCompatible as CK}from"@cline/shared";import{resolveClineDataDir as ja,resolveClineDir as Mle}from"@cline/shared/storage";var kK="CLINE_HUB_DISCOVERY_PATH",IK="CLINE_HUB_BUILD_ID",PK="CLINE_HUB_BUILD_EPOCH_MS",AK=30000,RK=15000,mA=100;function EK(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function xK(e){return SK("sha256").update(e).digest("hex").slice(0,12)}function _K(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function vA(){return yA(32).toString("hex")}function gA(e){return new Promise((t)=>setTimeout(t,e))}function MK(e){return`${e}.lock`}async function OK(e){try{let t=JSON.parse(await SA(Dh(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function Lh(e){await sl(e,{recursive:!0,force:!0}).catch(()=>{return})}function en(){let e=process.env[IK]?.trim();if(e)return e;return"sdk-v1-0982e787428525296f7c82ef42aff77c3cee5087192bf30b19f8018599e7f0ab".trim()||`source-${String(lr.version)}`}function Hh(){let e=Number(process.env[PK]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735549231)?1790735549231:void 0}function go(e,t=en()){let n=CK(e);if(!n.compatible)return n;let r=e.buildId?.trim();if(!r)return{compatible:!1,reason:"missing_build"};if(r!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function fA(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function hA(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((r)=>Number(r));if(n.length===0||n.some((r)=>!Number.isInteger(r)||r<0))return;return n}function LK(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let r=e[n]??0,o=t[n]??0;if(r!==o)return r<o?-1:1}return 0}function qa(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=fA(e.buildEpochMs),s=fA(t.buildEpochMs);if(o!==void 0&&s!==void 0&&o!==s)return o<s?-1:1;let i=hA(e.coreVersion),a=hA(t.coreVersion);if(i&&a){let d=LK(i,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function za(){return{buildId:en(),buildEpochMs:Hh(),coreVersion:String(lr.version)}}function Ls(e,t){let n=t?.self??za(),r=go(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return qa(n,e)<=0}function fo(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${xK(e)}`,n=process.env[kK]?.trim()||Dh(ja(),"locks","hub","owners",`${EK(t)}.json`);return{ownerId:t,discoveryPath:n}}function Lle(e=`hub-${Date.now().toString(36)}`){return fo(e)}async function $e(e){try{let t=JSON.parse(await SA(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function il(e,t){await Uh(e,async()=>{let n=bA(e);await Nh(n,{recursive:!0});let r=`${e}.${process.pid}.${yA(6).toString("hex")}.tmp`,o;try{o=await pA(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
539
+ `)[0]??o);return iK(s,50)}return}function dK(e){let t=0;for(let n of e)t+=ol(n.metrics?.cost)??0;return t}function cK(e){let t,n;for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(!t)t=Rt(o.modelInfo?.provider);if(!n)n=Rt(o.modelInfo?.id);if(t&&n)break}return{provider:t,model:n}}function uK(e){return Rt(e?.provider)??Rt(e?.provider&&typeof e.provider==="object"&&!Array.isArray(e.provider)?e.provider.id:void 0)}function lK(e){return Rt(e?.model)??Rt(e?.model&&typeof e.model==="object"&&!Array.isArray(e.model)?e.model.id:void 0)}function xh(e,t){let n=Z1(e.metadata),r=Wa(t?.title)??Wa(n?.title),o=ol(t?.totalCost)??ol(n?.totalCost),s=n||r!==void 0||o!==void 0?{...n??{},...r!==void 0?{title:r}:{},...o!==void 0?{totalCost:o}:{}}:void 0;return{...e,provider:Rt(t?.provider)??Rt(e.provider)??uK(n)??"",model:Rt(t?.model)??Rt(e.model)??lK(n)??"",metadata:s}}function pK(e){let t=e.content;if(!Array.isArray(t))return!1;return t.some((n)=>!!n&&typeof n==="object"&&n.type==="tool-call")}function mK(e,t){if(e.status!=="running"||e.interactive!==!0)return!1;let n=t.at(-1);return n?.role==="assistant"&&!pK(n)}async function gK(e,t){return await Promise.all(t.map(async(n)=>{if(n.status!=="running"||n.interactive!==!0)return n;let r=await e.readSessionMessages(n.sessionId);return mK(n,r)?{...n,status:"idle"}:n}))}async function fK(e,t){return await Promise.all(t.map(async(n)=>{let r=xh(n),o=Boolean(Wa(r.metadata?.title)),s=Boolean(Rt(r.provider)),i=Boolean(Rt(r.model)),a=ol(r.metadata?.totalCost),d=a!==void 0&&a>0;if(o&&s&&i&&d)return r;let c=await e.readSessionMessages(n.sessionId);if(c.length===0)return r;let u=cK(c),l=dK(c);return xh(n,{title:o?void 0:aK(c),provider:s?void 0:u.provider,model:i?void 0:u.model,totalCost:d||l<=0?void 0:l})}))}async function Oh(e,t={}){let n=_h(t.limit),r=t.includeSubagents===!0,o=await oK(e,n,{includeSubagents:r}),s=t.includeManifestFallback===!0&&o.length<n?await rK(Math.min(Math.max(n*2,100),500)):[],i=new Map;for(let c of[...o,...s]){if(i.has(c.sessionId))continue;i.set(c.sessionId,c)}let a=s.length===0?o:Array.from(i.values()).sort((c,u)=>u.startedAt.localeCompare(c.startedAt)).slice(0,n),d=await gK(e,a);if(t.hydrate===!1)return d.map((c)=>xh(c));return await fK(e,d)}async function hK(e){let t=e.trim();if(!t)return;let n=uA(lA(),t,`${t}.json`),r=await cA(n,"utf8").catch(()=>{return});if(!r)return;try{let o=mt.safeParse(JSON.parse(r));return o.success?o.data.messages_path:void 0}catch{return}}async function yK(e,t={}){let n=new Map;return await Oh({listSessions:async(o,s)=>{let i=await e.listSessions(o,s);n.clear();for(let a of i)n.set(a.sessionId,a);return i.map(Fa)},readSessionMessages:async(o)=>{let s=n.get(o)?.messagesPath??await hK(o);return await Sr(s)}},t)}import{captureSdkError as h_}from"@cline/shared";import{createSessionId as xG,ensureLoopbackProxyBypass as HA,isHubProtocolCompatible as _G,resolveClineBuildEnv as MG,resolveHubCommandTimeoutMs as OG}from"@cline/shared";import LG from"ws";import{spawn as YK}from"node:child_process";import{closeSync as QK,mkdirSync as ZK,openSync as eG,readFileSync as tG,unlinkSync as nG}from"node:fs";import{basename as rG,dirname as oG,join as sG}from"node:path";import{fileURLToPath as iG}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as aG,isBunEmbeddedModulePath as dG,isHubDaemonProcess as EA,resolveClineBuildEnv as xA,withResolvedClineBuildEnv as cG}from"@cline/shared";import{createHash as SK,randomBytes as yA}from"node:crypto";import{existsSync as bK}from"node:fs";import{mkdir as Nh,open as pA,readFile as SA,rename as vK,rm as sl,writeFile as TK}from"node:fs/promises";import{dirname as bA,join as Dh}from"node:path";import{ensureLoopbackProxyBypass as wK,isHubProtocolCompatible as CK}from"@cline/shared";import{resolveClineDataDir as ja,resolveClineDir as Mle}from"@cline/shared/storage";var kK="CLINE_HUB_DISCOVERY_PATH",IK="CLINE_HUB_BUILD_ID",PK="CLINE_HUB_BUILD_EPOCH_MS",AK=30000,RK=15000,mA=100;function EK(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function xK(e){return SK("sha256").update(e).digest("hex").slice(0,12)}function _K(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function vA(){return yA(32).toString("hex")}function gA(e){return new Promise((t)=>setTimeout(t,e))}function MK(e){return`${e}.lock`}async function OK(e){try{let t=JSON.parse(await SA(Dh(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function Lh(e){await sl(e,{recursive:!0,force:!0}).catch(()=>{return})}function en(){let e=process.env[IK]?.trim();if(e)return e;return"sdk-v1-814d0cfa563d6988b7812b459881e191a794af2da082cd021d824a3bcb05b043".trim()||`source-${String(lr.version)}`}function Hh(){let e=Number(process.env[PK]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735496846)?1790735496846:void 0}function go(e,t=en()){let n=CK(e);if(!n.compatible)return n;let r=e.buildId?.trim();if(!r)return{compatible:!1,reason:"missing_build"};if(r!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function fA(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function hA(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((r)=>Number(r));if(n.length===0||n.some((r)=>!Number.isInteger(r)||r<0))return;return n}function LK(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let r=e[n]??0,o=t[n]??0;if(r!==o)return r<o?-1:1}return 0}function qa(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=fA(e.buildEpochMs),s=fA(t.buildEpochMs);if(o!==void 0&&s!==void 0&&o!==s)return o<s?-1:1;let i=hA(e.coreVersion),a=hA(t.coreVersion);if(i&&a){let d=LK(i,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function za(){return{buildId:en(),buildEpochMs:Hh(),coreVersion:String(lr.version)}}function Ls(e,t){let n=t?.self??za(),r=go(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return qa(n,e)<=0}function fo(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${xK(e)}`,n=process.env[kK]?.trim()||Dh(ja(),"locks","hub","owners",`${EK(t)}.json`);return{ownerId:t,discoveryPath:n}}function Lle(e=`hub-${Date.now().toString(36)}`){return fo(e)}async function $e(e){try{let t=JSON.parse(await SA(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function il(e,t){await Uh(e,async()=>{let n=bA(e);await Nh(n,{recursive:!0});let r=`${e}.${process.pid}.${yA(6).toString("hex")}.tmp`,o;try{o=await pA(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
540
540
  `,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await vK(r,e);let s;try{s=await pA(n,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await o?.close().catch(()=>{return}),await sl(r,{force:!0}).catch(()=>{return}),s}})}async function En(e){await Uh(e,async()=>{await sl(e,{force:!0}).catch(()=>{return})})}async function TA(e,t){return await Uh(e,async()=>{if((await $e(e))?.hubId!==t)return!1;return await sl(e,{force:!0}),!0})}async function wA(e,t,n){let r=MK(e);await Nh(bA(r),{recursive:!0});let o=Date.now()+RK;while(!0){try{await Nh(r,{recursive:!1})}catch(s){if((s instanceof Error&&"code"in s?String(s.code):"")!=="EEXIST")throw s;let a=await OK(r);if(!a){if(Date.now()>=o){await Lh(r);continue}await gA(mA);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!_K(a.pid)||d>AK){await Lh(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await gA(mA);continue}try{return await TK(Dh(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
541
541
  `,"utf8"),await n()}finally{await Lh(r)}}}function Uh(e,t){return wA(`${e}.mutation`,"discovery mutation",t)}function al(e,t){return wA(e,"startup",t)}async function xn(e,t){wK();try{let n=await fetch(t?.authToken?NK(e):CA(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let r=await n.json();if(typeof r.protocolVersion!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string")return;return{protocolVersion:r.protocolVersion,minClientProtocolVersion:typeof r.minClientProtocolVersion==="string"?r.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof r.maxClientProtocolVersion==="string"?r.maxClientProtocolVersion:void 0,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof r.coreVersion==="string"?r.coreVersion:void 0,buildId:typeof r.buildId==="string"?r.buildId:void 0,buildEpochMs:typeof r.buildEpochMs==="number"?r.buildEpochMs:void 0,host:r.host,port:r.port,url:r.url,hubId:typeof r.hubId==="string"?r.hubId:void 0,authToken:typeof r.authToken==="string"?r.authToken:void 0,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:typeof r.startedAt==="string"?r.startedAt:void 0,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:void 0}}catch{return}}function _n(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function CA(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function NK(e){let t=new URL(CA(e));return t.pathname="/status",t.toString()}function Nle(e){return bK(e)}import{CLINE_HUB_DEV_PORT as DK,CLINE_HUB_PORT as HK,resolveClineBuildEnv as UK}from"@cline/shared";var FK="CLINE_HUB_HOST",BK="CLINE_HUB_PORT",$K="CLINE_HUB_PATHNAME",WK="127.0.0.1",jK=HK,qK="/hub";function kA(e){return UK(e)==="development"?DK:jK}function zK(e={}){return(e.env??process.env)[FK]?.trim()||WK}function dl(e={}){let n=(e.env??process.env)[BK]?.trim();if(!n)return kA(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return kA(e);return r}function KK(e={}){return(e.env??process.env)[$K]?.trim()||qK}function ho(e={},t={}){return{host:e.host??zK(t),port:e.port??dl(t),pathname:e.pathname??KK(t)}}import{join as GK}from"node:path";var VK="shared:cline",JK="CLINE_HUB_DISCOVERY_PATH",XK="hub-production";function Wle(e){let t=fr(e.trim());return fo(`workspace:${t||e.trim()}`)}function jt(e=VK){return fo(`${e}@${en()}`)}function tn(){return{ownerId:XK,discoveryPath:process.env[JK]?.trim()||GK(ja(),"locks","hub","production.json")}}var IA=15000,uG=200,PA=3000,lG=100,pG=[100,250,500,1000,2000],mG="--cline-hub-daemon",gG=3,fG=60000,$h=new Map,Zle={resetRetireAttempts(){$h.clear()},resolveDaemonEntryArgs:MA};function hG(e,t=Date.now()){let n=$h.get(e);if(!n||t-n.windowStartedAt>fG)return $h.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=gG}function yG(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function SG(){try{let e=sG(ja(),"logs","hub-daemon.log");return ZK(oG(e),{recursive:!0}),{fd:eG(e,"a"),logPath:e}}catch{return}}function _A(){return xA()==="production"?tn():jt()}function Ka(e){return Ls(e)}function bG(e){try{let t=JSON.parse(tG(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function Fh(e){try{nG(`${e}.superseded`)}catch{}}function AA(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Ns(e,t){try{return await xn(e,{authToken:t})}catch{return}}async function RA(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Ns(e))?.url)return!0;await new Promise((o)=>setTimeout(o,lG))}return!1}async function Ds(e,t){if(!hG(e.url))return!1;await yo(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Va(e.url,e.authToken).catch(()=>!1);let n=await RA(e.url,PA);if(!n&&e.pid&&vG(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await RA(e.url,PA)}if(n)await En(t).catch(()=>{return});return n}function vG(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Wh(e){try{return(await Us(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function Bh(e,t){if(Ka(e))return"reusable";let n=await yo(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await Wh(e)){if(n)await yo(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Ds(e,t);if(!r&&n)await yo(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function TG(e){if(xA()!=="production")return;let t=jt();if(t.discoveryPath===e.discoveryPath)return;let n=await $e(t.discoveryPath);if(n?.url)await Ds(n,t.discoveryPath);else await En(t.discoveryPath).catch(()=>{return})}function wG(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return iG(new URL(`./entry.${e}`,import.meta.url))}function MA(e,t){if(dG(e))return[mG];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function CG(e,t){let n=wG(),r=process.execPath?.trim();if(!r)throw Error("unable to resolve runtime executable for hub daemon");let o=rG(r).toLowerCase().includes("bun"),s=MA(n,o);return{launcher:r,args:[...s,"--cwd",e,...yG(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...cG(process.env),CLINE_NO_INTERACTIVE:"1",[aG]:"1"}}}function kG(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function IG(e,t={}){if(EA())return;let n=CG(e,t),r=SG();try{YK(n.launcher,n.args,{detached:!0,stdio:r?["ignore",r.fd,r.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(r)QK(r.fd)}}async function PG(e,t={}){for(let n=0;;n++)try{IG(e,t);return}catch(r){let o=pG[n];if(!kG(r)||o===void 0)throw r;await new Promise((s)=>setTimeout(s,o))}}function OA(e,t={}){if(EA())return;Ga(e,t).catch(()=>{})}async function AG(e,t,n={}){let r=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=ho(n),s=_n(o.host,o.port,o.pathname),i=(g)=>{if(!r)Hs(g.url,g.authToken);return g};await TG(e).catch(()=>{return});let a=await $e(e.discoveryPath),d=a?.url?void 0:bG(e.discoveryPath),c=!1;if(a?.url){let g=a.authToken;if(!g)c=!0,await Ds(a,e.discoveryPath);else{let f=await Ns(a.url,g);if(f?.url&&Ka(f)&&await Et(f.url,{authToken:g}))return Fh(e.discoveryPath),i({url:f.url,authToken:g});if(f?.url){if(await Bh({...f,authToken:g},e.discoveryPath)==="deferred_busy"&&await Et(f.url,{authToken:g}))return i({url:f.url,authToken:g})}else await En(e.discoveryPath).catch(()=>{return})}}let u=await Ns(s);if(u?.url){let g=AA(u,a??d,s);if(Ka(u)){let h=[u.authToken,a?.authToken,d?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0);for(let S of h){if(!await Et(u.url,{authToken:S}))continue;let b={hubId:u.hubId??`repaired-${u.port}`,protocolVersion:u.protocolVersion,minClientProtocolVersion:u.minClientProtocolVersion,maxClientProtocolVersion:u.maxClientProtocolVersion,capabilities:u.capabilities,coreVersion:u.coreVersion,buildId:u.buildId,authToken:S,host:u.host,port:u.port,url:u.url,pid:u.pid??a?.pid??d?.pid,startedAt:u.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await il(e.discoveryPath,b)}catch{}return Fh(e.discoveryPath),i({url:u.url,authToken:S})}throw Error(`A compatible Cline Hub is already running at ${s}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${c?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let f=await Bh(g,e.discoveryPath);if(f==="deferred_busy"){for(let h of[g.authToken,a?.authToken].filter((y)=>typeof y==="string"&&y.trim().length>0))if(await Et(u.url,{authToken:h}))return i({url:u.url,authToken:h});if(n.allowPortFallback!==!0&&o.port!==0)throw Error(`An older Cline Hub is running at ${s} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(f==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is already running at ${s} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let p=n.allowPortFallback===!0&&o.port!==0?{...o,port:0}:o;await PG(t,{...p,manageConnectors:n.manageConnectors});let m=Date.now()+IA;while(Date.now()<m){let g=await $e(e.discoveryPath);if(g?.url&&g.authToken){let h=await Ns(g.url,g.authToken);if(h?.url&&Ka(h)&&await Et(h.url,{authToken:g.authToken}))return Fh(e.discoveryPath),i({url:h.url,authToken:g.authToken})}let f=await Ns(s);if(f?.url&&!Ka(f)){let h=AA(f,g??d,s),y=await Bh(h,e.discoveryPath);if(y==="deferred_busy"&&g?.authToken&&await Et(f.url,{authToken:g.authToken}))return i({url:f.url,authToken:g.authToken});if(y==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is still running at ${s} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((h)=>setTimeout(h,uG))}throw Error(`Timed out after ${IA}ms waiting for detached hub startup.`)}async function Ga(e,t={}){let n=_A();return await al(n.discoveryPath,async()=>AG(n,e,t))}var RG=5000,EG=500;async function epe(e={}){let t=_A(),n=e.workspaceRoot??process.cwd(),r=await $e(t.discoveryPath),o=r?.url?await Ns(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await Ga(n)};let s={...o,authToken:o.authToken??r?.authToken,pid:o.pid??r?.pid};if(go(o).compatible)return{outcome:"already_current",url:o.url,authToken:s.authToken};if(qa(za(),o)<=0)return{outcome:"hub_not_older",url:o.url,authToken:s.authToken};if(!await yo(s.url,s.authToken,e.reason??"hub upgrade requested").catch(()=>!1))throw Error(`The running Cline Hub at ${s.url} did not accept a drain request, so it was not replaced. It is replaced automatically once idle when a Cline client next starts, or run 'cline doctor fix' to stop it now.`);let a=async()=>{await yo(s.url,s.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},d=Date.now()+(e.waitForIdleMs??RG),c;for(;;){try{if(c=(await Us(s.url,s.authToken)).activeSessionCount,c===0)break}catch{}if(Date.now()>=d)break;await new Promise((p)=>setTimeout(p,EG))}if(c!==0&&e.force!==!0)return await a(),{outcome:"still_busy",url:s.url,authToken:s.authToken,...c!==void 0?{activeSessionCount:c}:{}};if(!await Ds(s,t.discoveryPath))throw await a(),Error(`The running Cline Hub at ${s.url} could not be stopped. Run 'cline doctor fix' to stop stale hub daemons, then try again.`);return{outcome:"replaced",...await Ga(n),activeSessionCount:c??0}}function Gh(){return MG()==="production"?tn():jt()}function NG(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function UA(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return UA(e.data);return String(e)}function DG(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function LA(e){let t=e,n=DG(t.reason);return new Ve("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:qh,{closeCode:t.code,closeReason:n||void 0})}function NA(e,t){if(e instanceof Ve)return e;if(e instanceof Error)return new Ve("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new Ve("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new Ve("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new Ve("hub_connect_failed",r?`Failed to connect to hub at ${t.toString()} (${r} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var jh="*",cl=8000,HG="cline-hub-auth.",FA=new Map,BA=new Set,UG=3000,FG=3000,BG=100,qh="Hub connection closed",$G=250,WG=5000,DA=0.5;class Ve extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function jG(e){return e instanceof Ve}class ul extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function $A(e,t){return e instanceof ul&&e.code==="hub_command_timeout"&&(t===void 0||e.command===t)}function Vh(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let r=Jh(e.toString());return r?FA.get(r):void 0}function qG(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function Jh(e){if(!qG(e))return;let t=new URL(Fs(e));return t.search="",t.hash="",t.toString()}function zh(e){let t=Jh(e);return!!t&&BA.has(t)}function Hs(e,t){let n=Jh(e);if(n){if(BA.add(n),t?.trim())FA.set(n,t)}return e}class Mn{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new Ve("hub_connection_closed",qh);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||Vh(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,r=this.openSocket(e,t,n),o;this.connectPromise=r.then(async(i)=>{if(o=i,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(lr.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{i.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let a of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(a));this.reconnectAttempt=0});let s=this.connectPromise;try{await s}catch(i){if(this.connectPromise===s)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=NA(i,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw i}}async openSocket(e,t,n){let r=this.options.resolveConnectionHeaders,o;if(r){let d;try{o=await Promise.race([Promise.resolve().then(()=>r()),new Promise((c,u)=>{d=setTimeout(()=>{u(new Ve("hub_connect_timeout",`Timed out resolving hub connection headers after ${cl}ms`))},cl)})])}catch(c){let u=c instanceof Ve?c:new Ve("hub_connect_failed",c instanceof Error?c.message:String(c));if(n===this.connectGeneration)this.lastCloseError=u;throw u}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new Ve("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let s=o?new LG(e.toString(),{headers:{...o}}):new(NG())(e.toString(),t?[`${HG}${t}`]:void 0);this.socket=s;let i=!1,a=new Promise((d,c)=>{let u=!1,l=setTimeout(()=>{if(u)return;u=!0,i=!0;let p=new Ve("hub_connect_timeout",`Timed out connecting to hub after ${cl}ms`);if(this.socket===s)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{s.close()}catch{}c(p)},cl);s.addEventListener("open",()=>{if(u)return;u=!0,clearTimeout(l),d()}),s.addEventListener("error",(p)=>{if(u)return;u=!0,clearTimeout(l);let m=NA(p,e);if(this.socket===s)this.lastCloseError=m,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;c(m)}),s.addEventListener("close",(p)=>{if(u)return;u=!0,clearTimeout(l);let m=i?this.lastCloseError:LA(p);if(this.socket===s){if(!i)this.lastCloseError=m,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}c(m)})});return s.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(UA(d)))}),s.addEventListener("close",(d)=>{if(this.socket!==s)return;if(!i)this.lastCloseError=LA(d),this.sawSocketClose=!0;this.registered=!1;for(let c of this.pendingReplies.values())c.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await a,s}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,r={listener:e,sessionId:n};return this.listeners.add(r),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(r))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,r){let o=0,s=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,r)}catch(i){if(!s||o>=1||!await this.recoverLocalHubTransport(i))throw i;o+=1}}async commandOnce(e,t,n,r,o=!0){if(o)await this.connect();r?.beforeDispatch?.();let s=xG("hubreq_");r?.onDispatch?.(s);let i=OG(e,r?.timeoutMs),a=new Promise((c,u)=>{let l=i===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(s))return;u(new ul(e,"hub_command_timeout",`Hub command ${e} timed out after ${i}ms (hub=${this.currentUrl}, requestId=${s}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},i);this.pendingReplies.set(s,{resolve:(p)=>{if(l)clearTimeout(l);c(p)},reject:(p)=>{if(l)clearTimeout(l);u(p)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:s,clientId:this.clientId,sessionId:n,timeoutMs:i,payload:t}})}catch(c){throw this.pendingReplies.delete(s),c}let d=await a;if(!d.ok){if(d.error?.code===Pa){let c=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new co(c,d.error.message)}throw new ul(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!zh(this.currentUrl)||!jG(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Ja({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,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 e=Math.min($G*2**this.reconnectAttempt,WG),t=Math.round(e*(1-DA)+Math.random()*e*DA);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!zh(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Ja({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new Ve("hub_connection_closed",qh);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.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(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new Ve("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),r=(this.subscriptionCounts.get(n)??0)+t;if(r<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,r),t>0&&r===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??jh}subscriptionSessionIdFromKey(e){return e===jh?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let r of[jh,n]){if(!r||!this.subscriptionCounts.has(r))continue;let o=this.lastEventSequenceByKey.get(r)??0;if(t>o)this.lastEventSequenceByKey.set(r,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Fs(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function Et(e,t){let n=new Mn({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function Kh(e,t){let n=Fs(e),r=await xn(n,{authToken:t?.authToken});if(!r)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=en(),s=go(r,o);if(!s.compatible&&!Ls(r))return{status:s.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!_G(r).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await Et(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}async function zG(e){let t=Date.now()+FG;while(Date.now()<t){if(!(await xn(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,BG))}return!1}function KG(e,t){try{return Fs(e)===Fs(t)}catch{return!1}}function WA(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,r=new Set;for(let o of t){if(!o||typeof o!=="object")continue;let s=o.participants;if(!Array.isArray(s)||s.length===0)continue;n+=1;for(let i of s){let a=i&&typeof i==="object"?i.clientId:void 0;if(typeof a==="string"&&a.trim())r.add(a)}}return{activeSessionCount:n,participantClientCount:r.size}}function cpe(e){return WA(e).activeSessionCount>0}async function Us(e,t,n){let r=new Mn({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await r.command("session.list",{limit:500},void 0,{timeoutMs:UG});return WA(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function jA(e,t,n){try{return(await Us(e,t,n)).activeSessionCount===0}catch{return!1}}async function GG(e,t){let n=`${e.discoveryPath}.superseded`,r=await $e(n);if(!r?.url||!r.authToken)return;let o=await Kh(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await jA(o.url,r.authToken,t))return;return Hs(o.url,r.authToken)}async function Xh(e={}){if(e.endpoint?.trim()){let o=await Kh(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=Gh(),n=await $e(t.discoveryPath);if(!n?.url)return await GG(t,e);let r=await Kh(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return Hs(r.url,n.authToken);if(r.status==="protocol_mismatch")await En(t.discoveryPath).catch(()=>{return});return}async function Ja(e={}){let t=await Xh(e);if(t&&await Et(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Ga(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function yo(e,t,n,r){HA();let o=new URL(e),s=t?.trim()||Vh(o);if(o.protocol==="ws:")o.protocol="http:";else if(o.protocol==="wss:")o.protocol="https:";if(o.pathname="/drain",o.hash="",n)o.searchParams.set("reason",n);if(r?.off)o.searchParams.set("off","1");return(await fetch(o,{method:"POST",headers:s?{authorization:`Bearer ${s}`}:void 0})).ok}async function Va(e,t){HA();let n=new URL(e),r=t?.trim()||Vh(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:r?{authorization:`Bearer ${r}`}:void 0})).ok}async function VG(e=Gh()){let t=await $e(e.discoveryPath);if(!t?.url)return!1;try{if(await Va(t.url,t.authToken))return!0}catch{}return!1}async function qA(e){if(!zh(e.url))return;let t=Gh(),n=await $e(t.discoveryPath);if(!n?.url||!KG(n.url,e.url))return;if(!await jA(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await VG())return;if(!await zG(n.url))return;return await En(t.discoveryPath).catch(()=>{return}),await Ja({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveProviderRequestHeaders as nV}from"@cline/llms";import{captureSdkError as Zh,createSessionId as YA,HUB_CHECKPOINT_CAPABILITY as rV,HUB_COMPACTION_CAPABILITY as oV,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as sV,HUB_HOOK_CAPABILITY_PREFIX as iV,HUB_MISTAKE_LIMIT_CAPABILITY as aV,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as dV,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as cV,isGeneratedMedia as uV,isHubToolExecutorName as lV}from"@cline/shared";wt();import{createHash as JG}from"node:crypto";import{formatDisplayUserInput as zA}from"@cline/shared";import{z as nn}from"zod";function XG(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let t=e;if(t.role!=="user"&&t.role!=="assistant")return!1;return typeof t.content==="string"||Array.isArray(t.content)}var YG=nn.custom(XG),ll=nn.object({version:nn.literal(1),updated_at:nn.string().datetime(),conversation_id:nn.string().min(1).optional(),source_message_count:nn.number().int().nonnegative(),source_prefix_hash:nn.string().min(1).optional(),source_last_message_key:nn.string().min(1).optional(),messages:nn.array(YG),system_prompt:nn.string().optional()});function KA(e){return e.filter((t)=>t.metadata?.displayOnly!==!0)}function Yh(e){return JSON.parse(JSON.stringify(e))}function GA(e){if(e.role!=="user")return e;if(typeof e.content==="string")return{...e,content:zA(e.content)};return{...e,content:e.content.map((t)=>t.type==="text"?{...t,text:zA(t.text)}:t)}}function VA(e){if(e.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function QG(e){let t=GA(e);return VA(t.role),[["role",t.role],["content",t.content],["agent",t.agent??null],["sessionId",t.sessionId??null],["metadata",t.metadata??null],["modelInfo",t.modelInfo??null],["metrics",t.metrics??null]]}function JA(e){if(!e)return"";let t=GA(e);if(typeof t.id==="string"&&t.id.trim())return`id:${t.id.trim()}`;if(VA(t.role),typeof t.ts==="number"&&Number.isFinite(t.ts))return`ts:${t.role}:${t.ts}`;return`content:${t.role}:${JSON.stringify(t.content)}`}function XA(e,t=e.length){let n=JG("sha256");n.update(`cline-session-compaction-source-v2
542
542
  `),n.update(`${t}
@@ -1,4 +1,4 @@
1
- import{homedir as Wn}from"node:os";import{claimHubDaemonProcess as $n}from"@cline/shared";import{setHomeDirIfUnset as Gn}from"@cline/shared/storage";import{createSessionId as hn,ensureLoopbackProxyBypass as Ae,isHubProtocolCompatible as gn,resolveClineBuildEnv as bn,resolveHubCommandTimeoutMs as yn}from"@cline/shared";import wn from"ws";var H={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.88-nightly.1790735522",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",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:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","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:*","@modelcontextprotocol/sdk":"^1.29.0","@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:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var re="session_not_found";class F extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}import{spawn as Dt}from"node:child_process";import{closeSync as At,mkdirSync as Lt,openSync as Ut,readFileSync as Mt,unlinkSync as Nt}from"node:fs";import{basename as Bt,dirname as Ft,join as Vt}from"node:path";import{fileURLToPath as Wt}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as $t,isBunEmbeddedModulePath as Gt,isHubDaemonProcess as jt,resolveClineBuildEnv as Te,withResolvedClineBuildEnv as qt}from"@cline/shared";import{createHash as Ye,randomBytes as Xe}from"node:crypto";import{mkdir as W,open as ie,readFile as de,rename as Ze,rm as I,writeFile as Qe}from"node:fs/promises";import{dirname as le,join as G}from"node:path";import{ensureLoopbackProxyBypass as et,isHubProtocolCompatible as tt}from"@cline/shared";import{resolveClineDataDir as P,resolveClineDir as Qn}from"@cline/shared/storage";var nt="CLINE_HUB_DISCOVERY_PATH",ot="CLINE_HUB_BUILD_ID",rt="CLINE_HUB_BUILD_EPOCH_MS",it=30000,st=15000,se=100;function at(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ct(e){return Ye("sha256").update(e).digest("hex").slice(0,12)}function ut(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function ae(e){return new Promise((t)=>setTimeout(t,e))}function dt(e){return`${e}.lock`}async function lt(e){try{let t=JSON.parse(await de(G(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function V(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[ot]?.trim();if(e)return e;return"sdk-v1-0982e787428525296f7c82ef42aff77c3cee5087192bf30b19f8018599e7f0ab".trim()||`source-${String(H.version)}`}function pt(){let e=Number(process.env[rt]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735549231)?1790735549231:void 0}function x(e,t=k()){let n=tt(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ce(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ue(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function ft(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function pe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ce(e.buildEpochMs),i=ce(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let a=ue(e.coreVersion),u=ue(t.coreVersion);if(a&&u){let c=ft(a,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function fe(){return{buildId:k(),buildEpochMs:pt(),coreVersion:String(H.version)}}function O(e,t){let n=t?.self??fe(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return pe(n,e)<=0}function me(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${ct(e)}`,n=process.env[nt]?.trim()||G(P(),"locks","hub","owners",`${at(t)}.json`);return{ownerId:t,discoveryPath:n}}async function b(e){try{let t=JSON.parse(await de(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function he(e,t){await j(e,async()=>{let n=le(e);await W(n,{recursive:!0});let o=`${e}.${process.pid}.${Xe(6).toString("hex")}.tmp`,r;try{r=await ie(o,"wx",384),await r.writeFile(`${JSON.stringify(t,null,2)}
1
+ import{homedir as Wn}from"node:os";import{claimHubDaemonProcess as $n}from"@cline/shared";import{setHomeDirIfUnset as Gn}from"@cline/shared/storage";import{createSessionId as hn,ensureLoopbackProxyBypass as Ae,isHubProtocolCompatible as gn,resolveClineBuildEnv as bn,resolveHubCommandTimeoutMs as yn}from"@cline/shared";import wn from"ws";var H={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.88",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",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:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","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:*","@modelcontextprotocol/sdk":"^1.29.0","@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:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var re="session_not_found";class F extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}import{spawn as Dt}from"node:child_process";import{closeSync as At,mkdirSync as Lt,openSync as Ut,readFileSync as Mt,unlinkSync as Nt}from"node:fs";import{basename as Bt,dirname as Ft,join as Vt}from"node:path";import{fileURLToPath as Wt}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as $t,isBunEmbeddedModulePath as Gt,isHubDaemonProcess as jt,resolveClineBuildEnv as Te,withResolvedClineBuildEnv as qt}from"@cline/shared";import{createHash as Ye,randomBytes as Xe}from"node:crypto";import{mkdir as W,open as ie,readFile as de,rename as Ze,rm as I,writeFile as Qe}from"node:fs/promises";import{dirname as le,join as G}from"node:path";import{ensureLoopbackProxyBypass as et,isHubProtocolCompatible as tt}from"@cline/shared";import{resolveClineDataDir as P,resolveClineDir as Qn}from"@cline/shared/storage";var nt="CLINE_HUB_DISCOVERY_PATH",ot="CLINE_HUB_BUILD_ID",rt="CLINE_HUB_BUILD_EPOCH_MS",it=30000,st=15000,se=100;function at(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ct(e){return Ye("sha256").update(e).digest("hex").slice(0,12)}function ut(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function ae(e){return new Promise((t)=>setTimeout(t,e))}function dt(e){return`${e}.lock`}async function lt(e){try{let t=JSON.parse(await de(G(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function V(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[ot]?.trim();if(e)return e;return"sdk-v1-814d0cfa563d6988b7812b459881e191a794af2da082cd021d824a3bcb05b043".trim()||`source-${String(H.version)}`}function pt(){let e=Number(process.env[rt]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735496846)?1790735496846:void 0}function x(e,t=k()){let n=tt(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ce(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ue(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function ft(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function pe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ce(e.buildEpochMs),i=ce(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let a=ue(e.coreVersion),u=ue(t.coreVersion);if(a&&u){let c=ft(a,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function fe(){return{buildId:k(),buildEpochMs:pt(),coreVersion:String(H.version)}}function O(e,t){let n=t?.self??fe(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return pe(n,e)<=0}function me(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${ct(e)}`,n=process.env[nt]?.trim()||G(P(),"locks","hub","owners",`${at(t)}.json`);return{ownerId:t,discoveryPath:n}}async function b(e){try{let t=JSON.parse(await de(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function he(e,t){await j(e,async()=>{let n=le(e);await W(n,{recursive:!0});let o=`${e}.${process.pid}.${Xe(6).toString("hex")}.tmp`,r;try{r=await ie(o,"wx",384),await r.writeFile(`${JSON.stringify(t,null,2)}
2
2
  `,{encoding:"utf8"}),await r.sync(),await r.close(),r=void 0,await Ze(o,e);let i;try{i=await ie(n,"r"),await i.sync()}catch{}finally{await i?.close().catch(()=>{return})}}catch(i){throw await r?.close().catch(()=>{return}),await I(o,{force:!0}).catch(()=>{return}),i}})}async function C(e){await j(e,async()=>{await I(e,{force:!0}).catch(()=>{return})})}async function ge(e,t){return await j(e,async()=>{if((await b(e))?.hubId!==t)return!1;return await I(e,{force:!0}),!0})}async function be(e,t,n){let o=dt(e);await W(le(o),{recursive:!0});let r=Date.now()+st;while(!0){try{await W(o,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let u=await lt(o);if(!u){if(Date.now()>=r){await V(o);continue}await ae(se);continue}let c=Date.now()-Date.parse(u.acquiredAt);if(!ut(u.pid)||c>it){await V(o);continue}if(Date.now()>=r)throw Error(`Timed out waiting for hub ${t} lock ${o}`);await ae(se);continue}try{return await Qe(G(o,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
3
  `,"utf8"),await n()}finally{await V(o)}}}function j(e,t){return be(`${e}.mutation`,"discovery mutation",t)}function ye(e,t){return be(e,"startup",t)}async function D(e,t){et();try{let n=await fetch(t?.authToken?mt(e):ve(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let o=await n.json();if(typeof o.protocolVersion!=="string"||typeof o.host!=="string"||typeof o.port!=="number"||typeof o.url!=="string")return;return{protocolVersion:o.protocolVersion,minClientProtocolVersion:typeof o.minClientProtocolVersion==="string"?o.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof o.maxClientProtocolVersion==="string"?o.maxClientProtocolVersion:void 0,capabilities:Array.isArray(o.capabilities)?o.capabilities.filter((r)=>typeof r==="string"):void 0,coreVersion:typeof o.coreVersion==="string"?o.coreVersion:void 0,buildId:typeof o.buildId==="string"?o.buildId:void 0,buildEpochMs:typeof o.buildEpochMs==="number"?o.buildEpochMs:void 0,host:o.host,port:o.port,url:o.url,hubId:typeof o.hubId==="string"?o.hubId:void 0,authToken:typeof o.authToken==="string"?o.authToken:void 0,pid:typeof o.pid==="number"?o.pid:void 0,startedAt:typeof o.startedAt==="string"?o.startedAt:void 0,updatedAt:typeof o.updatedAt==="string"?o.updatedAt:void 0}}catch{return}}function we(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function ve(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function mt(e){let t=new URL(ve(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as ht,CLINE_HUB_PORT as gt,resolveClineBuildEnv as bt}from"@cline/shared";var yt="CLINE_HUB_HOST",wt="CLINE_HUB_PORT",vt="CLINE_HUB_PATHNAME",St="127.0.0.1",kt=gt,Ct="/hub";function Se(e){return bt(e)==="development"?ht:kt}function Ht(e={}){return(e.env??process.env)[yt]?.trim()||St}function Pt(e={}){let n=(e.env??process.env)[wt]?.trim();if(!n)return Se(e);let o=Number.parseInt(n,10);if(!Number.isInteger(o)||o<1||o>65535)return Se(e);return o}function _t(e={}){return(e.env??process.env)[vt]?.trim()||Ct}function ke(e={},t={}){return{host:e.host??Ht(t),port:e.port??Pt(t),pathname:e.pathname??_t(t)}}import{join as Et}from"node:path";import{execFile as Rt}from"node:child_process";import{promisify as Tt}from"node:util";import{processWorkspaceInfo as ao}from"@cline/shared";import uo from"simple-git";var lo=Tt(Rt);var It="shared:cline",xt="CLINE_HUB_DISCOVERY_PATH",Ot="hub-production";function _(e=It){return me(`${e}@${k()}`)}function A(){return{ownerId:Ot,discoveryPath:process.env[xt]?.trim()||Et(P(),"locks","hub","production.json")}}var Ce=15000,Kt=200,He=3000,zt=100,Jt=[100,250,500,1000,2000],Yt="--cline-hub-daemon",Xt=3,Zt=60000,Pe=new Map;function Qt(e,t=Date.now()){let n=Pe.get(e);if(!n||t-n.windowStartedAt>Zt)return Pe.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Xt}function en(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function tn(){try{let e=Vt(P(),"logs","hub-daemon.log");return Lt(Ft(e),{recursive:!0}),{fd:Ut(e,"a"),logPath:e}}catch{return}}function nn(){return Te()==="production"?A():_()}function R(e){return O(e)}function on(e){try{let t=JSON.parse(Mt(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function q(e){try{Nt(`${e}.superseded`)}catch{}}function _e(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function T(e,t){try{return await D(e,{authToken:t})}catch{return}}async function Re(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await T(e))?.url)return!0;await new Promise((r)=>setTimeout(r,zt))}return!1}async function z(e,t){if(!Qt(e.url))return!1;await E(e.url,e.authToken,"retired by newer install").catch(()=>!1),await M(e.url,e.authToken).catch(()=>!1);let n=await Re(e.url,He);if(!n&&e.pid&&rn(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Re(e.url,He)}if(n)await C(t).catch(()=>{return});return n}function rn(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function sn(e){try{return(await J(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function K(e,t){if(R(e))return"reusable";let n=await E(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await sn(e)){if(n)await E(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let o=await z(e,t);if(!o&&n)await E(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return o?"retired":"failed"}async function an(e){if(Te()!=="production")return;let t=_();if(t.discoveryPath===e.discoveryPath)return;let n=await b(t.discoveryPath);if(n?.url)await z(n,t.discoveryPath);else await C(t.discoveryPath).catch(()=>{return})}function cn(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return Wt(new URL(`./entry.${e}`,import.meta.url))}function un(e,t){if(Gt(e))return[Yt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function dn(e,t){let n=cn(),o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let r=Bt(o).toLowerCase().includes("bun"),i=un(n,r);return{launcher:o,args:[...i,"--cwd",e,...en(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...qt(process.env),CLINE_NO_INTERACTIVE:"1",[$t]:"1"}}}function ln(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function pn(e,t={}){if(jt())return;let n=dn(e,t),o=tn();try{Dt(n.launcher,n.args,{detached:!0,stdio:o?["ignore",o.fd,o.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(o)At(o.fd)}}async function fn(e,t={}){for(let n=0;;n++)try{pn(e,t);return}catch(o){let r=Jt[n];if(!ln(o)||r===void 0)throw o;await new Promise((i)=>setTimeout(i,r))}}async function mn(e,t,n={}){let o=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),r=ke(n),i=we(r.host,r.port,r.pathname),a=(l)=>{if(!o)U(l.url,l.authToken);return l};await an(e).catch(()=>{return});let u=await b(e.discoveryPath),c=u?.url?void 0:on(e.discoveryPath),d=!1;if(u?.url){let l=u.authToken;if(!l)d=!0,await z(u,e.discoveryPath);else{let p=await T(u.url,l);if(p?.url&&R(p)&&await y(p.url,{authToken:l}))return q(e.discoveryPath),a({url:p.url,authToken:l});if(p?.url){if(await K({...p,authToken:l},e.discoveryPath)==="deferred_busy"&&await y(p.url,{authToken:l}))return a({url:p.url,authToken:l})}else await C(e.discoveryPath).catch(()=>{return})}}let s=await T(i);if(s?.url){let l=_e(s,u??c,i);if(R(s)){let h=[s.authToken,u?.authToken,c?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0);for(let S of h){if(!await y(s.url,{authToken:S}))continue;let ze={hubId:s.hubId??`repaired-${s.port}`,protocolVersion:s.protocolVersion,minClientProtocolVersion:s.minClientProtocolVersion,maxClientProtocolVersion:s.maxClientProtocolVersion,capabilities:s.capabilities,coreVersion:s.coreVersion,buildId:s.buildId,authToken:S,host:s.host,port:s.port,url:s.url,pid:s.pid??u?.pid??c?.pid,startedAt:s.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await he(e.discoveryPath,ze)}catch{}return q(e.discoveryPath),a({url:s.url,authToken:S})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${d?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let p=await K(l,e.discoveryPath);if(p==="deferred_busy"){for(let h of[l.authToken,u?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0))if(await y(s.url,{authToken:h}))return a({url:s.url,authToken:h});if(n.allowPortFallback!==!0&&r.port!==0)throw Error(`An older Cline Hub is running at ${i} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(p==="failed"&&n.allowPortFallback!==!0&&r.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let g=n.allowPortFallback===!0&&r.port!==0?{...r,port:0}:r;await fn(t,{...g,manageConnectors:n.manageConnectors});let w=Date.now()+Ce;while(Date.now()<w){let l=await b(e.discoveryPath);if(l?.url&&l.authToken){let h=await T(l.url,l.authToken);if(h?.url&&R(h)&&await y(h.url,{authToken:l.authToken}))return q(e.discoveryPath),a({url:h.url,authToken:l.authToken})}let p=await T(i);if(p?.url&&!R(p)){let h=_e(p,l??c,i),v=await K(h,e.discoveryPath);if(v==="deferred_busy"&&l?.authToken&&await y(p.url,{authToken:l.authToken}))return a({url:p.url,authToken:l.authToken});if(v==="failed"&&n.allowPortFallback!==!0&&r.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((h)=>setTimeout(h,Kt))}throw Error(`Timed out after ${Ce}ms waiting for detached hub startup.`)}async function L(e,t={}){let n=nn();return await ye(n.discoveryPath,async()=>mn(n,e,t))}function vn(){return bn()==="production"?A():_()}function Sn(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Le(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return Le(e.data);return String(e)}function kn(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function Ee(e){let t=e,n=kn(t.reason);return new f("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:X,{closeCode:t.code,closeReason:n||void 0})}function Ie(e,t){if(e instanceof f)return e;if(e instanceof Error)return new f("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new f("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new f("hub_connect_failed",n);let o=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new f("hub_connect_failed",o?`Failed to connect to hub at ${t.toString()} (${o} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var Y="*",N=8000,Cn="cline-hub-auth.",Ue=new Map,Me=new Set,Hn=3000;var X="Hub connection closed",Pn=250,_n=5000,xe=0.5;class f extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Rn(e){return e instanceof f}class Z extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function ee(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let o=te(e.toString());return o?Ue.get(o):void 0}function Tn(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function te(e){if(!Tn(e))return;let t=new URL(Ne(e));return t.search="",t.hash="",t.toString()}function Oe(e){let t=te(e);return!!t&&Me.has(t)}function U(e,t){let n=te(e);if(n){if(Me.add(n),t?.trim())Ue.set(n,t)}return e}class ne{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new f("hub_connection_closed",X);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||ee(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,o=this.openSocket(e,t,n),r;this.connectPromise=o.then(async(a)=>{if(r=a,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(H.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{a.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let u of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(u));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(a){if(this.connectPromise===i)this.connectPromise=void 0;if(r&&this.socket===r){this.lastCloseError=Ie(a,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{r.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw a}}async openSocket(e,t,n){let o=this.options.resolveConnectionHeaders,r;if(o){let c;try{r=await Promise.race([Promise.resolve().then(()=>o()),new Promise((d,s)=>{c=setTimeout(()=>{s(new f("hub_connect_timeout",`Timed out resolving hub connection headers after ${N}ms`))},N)})])}catch(d){let s=d instanceof f?d:new f("hub_connect_failed",d instanceof Error?d.message:String(d));if(n===this.connectGeneration)this.lastCloseError=s;throw s}finally{clearTimeout(c)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(r&&Object.keys(r).some((c)=>c.toLowerCase()==="sec-websocket-protocol")){let c=new f("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=c;throw c}let i=r?new wn(e.toString(),{headers:{...r}}):new(Sn())(e.toString(),t?[`${Cn}${t}`]:void 0);this.socket=i;let a=!1,u=new Promise((c,d)=>{let s=!1,m=setTimeout(()=>{if(s)return;s=!0,a=!0;let g=new f("hub_connect_timeout",`Timed out connecting to hub after ${N}ms`);if(this.socket===i)this.lastCloseError=g,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}d(g)},N);i.addEventListener("open",()=>{if(s)return;s=!0,clearTimeout(m),c()}),i.addEventListener("error",(g)=>{if(s)return;s=!0,clearTimeout(m);let w=Ie(g,e);if(this.socket===i)this.lastCloseError=w,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;d(w)}),i.addEventListener("close",(g)=>{if(s)return;s=!0,clearTimeout(m);let w=a?this.lastCloseError:Ee(g);if(this.socket===i){if(!a)this.lastCloseError=w,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}d(w)})});return i.addEventListener("message",(c)=>{this.handleFrame(JSON.parse(Le(c)))}),i.addEventListener("close",(c)=>{if(this.socket!==i)return;if(!a)this.lastCloseError=Ee(c),this.sawSocketClose=!0;this.registered=!1;for(let d of this.pendingReplies.values())d.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await u,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,o={listener:e,sessionId:n};return this.listeners.add(o),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(o))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,o){let r=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,o)}catch(a){if(!i||r>=1||!await this.recoverLocalHubTransport(a))throw a;r+=1}}async commandOnce(e,t,n,o,r=!0){if(r)await this.connect();o?.beforeDispatch?.();let i=hn("hubreq_");o?.onDispatch?.(i);let a=yn(e,o?.timeoutMs),u=new Promise((d,s)=>{let m=a===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;s(new Z(e,"hub_command_timeout",`Hub command ${e} timed out after ${a}ms (hub=${this.currentUrl}, requestId=${i}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},a);this.pendingReplies.set(i,{resolve:(g)=>{if(m)clearTimeout(m);d(g)},reject:(g)=>{if(m)clearTimeout(m);s(g)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:a,payload:t}})}catch(d){throw this.pendingReplies.delete(i),d}let c=await u;if(!c.ok){if(c.error?.code===re){let d=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new F(d,c.error.message)}throw new Z(e,c.error?.code,c.error?.message??`Hub command ${e} failed`)}return c}async recoverLocalHubTransport(e){if(!Oe(this.currentUrl)||!Rn(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await De({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,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 e=Math.min(Pn*2**this.reconnectAttempt,_n),t=Math.round(e*(1-xe)+Math.random()*e*xe);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Oe(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await De({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new f("hub_connection_closed",X);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.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(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new f("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),o=(this.subscriptionCounts.get(n)??0)+t;if(o<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,o),t>0&&o===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??Y}subscriptionSessionIdFromKey(e){return e===Y?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let o of[Y,n]){if(!o||!this.subscriptionCounts.has(o))continue;let r=this.lastEventSequenceByKey.get(o)??0;if(t>r)this.lastEventSequenceByKey.set(o,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Ne(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function y(e,t){let n=new ne({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function Q(e,t){let n=Ne(e),o=await D(n,{authToken:t?.authToken});if(!o)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let r=k(),i=x(o,r);if(!i.compatible&&!O(o))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!gn(o).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await y(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function En(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,o=new Set;for(let r of t){if(!r||typeof r!=="object")continue;let i=r.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let a of i){let u=a&&typeof a==="object"?a.clientId:void 0;if(typeof u==="string"&&u.trim())o.add(u)}}return{activeSessionCount:n,participantClientCount:o.size}}async function J(e,t,n){let o=new ne({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let r=await o.command("session.list",{limit:500},void 0,{timeoutMs:Hn});return En(r.payload)}finally{await o.dispose().catch(()=>{return})}}async function In(e,t,n){try{return(await J(e,t,n)).activeSessionCount===0}catch{return!1}}async function xn(e,t){let n=`${e.discoveryPath}.superseded`,o=await b(n);if(!o?.url||!o.authToken)return;let r=await Q(o.url,{authToken:o.authToken});if(r.status!=="compatible")return;if(await In(r.url,o.authToken,t))return;return U(r.url,o.authToken)}async function On(e={}){if(e.endpoint?.trim()){let r=await Q(e.endpoint);return r.status==="compatible"?r.url:void 0}let t=vn(),n=await b(t.discoveryPath);if(!n?.url)return await xn(t,e);let o=await Q(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(o.status==="compatible")return U(o.url,n.authToken);if(o.status==="protocol_mismatch")await C(t.discoveryPath).catch(()=>{return});return}async function De(e={}){let t=await On(e);if(t&&await y(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await L(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function E(e,t,n,o){Ae();let r=new URL(e),i=t?.trim()||ee(r);if(r.protocol==="ws:")r.protocol="http:";else if(r.protocol==="wss:")r.protocol="https:";if(r.pathname="/drain",r.hash="",n)r.searchParams.set("reason",n);if(o?.off)r.searchParams.set("off","1");return(await fetch(r,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function M(e,t){Ae();let n=new URL(e),o=t?.trim()||ee(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:o?{authorization:`Bearer ${o}`}:void 0})).ok}import{spawn as Dn}from"node:child_process";import{userInfo as An}from"node:os";import{basename as Ln,delimiter as B}from"node:path";var oe="__CLINE_SIDECAR_PATH_START__",Fe="__CLINE_SIDECAR_PATH_END__",Ve=5000,Un=`/bin/sh -c 'printf "%s%s%s" "${oe}" "$PATH" "${Fe}"'`,Be="CLINE_SIDECAR_SKIP_SHELL_PATH";function We(e){return e==="darwin"?"/bin/zsh":"/bin/bash"}function Mn(e,t){try{let n=An().shell?.trim();if(n)return n}catch{}return t.SHELL?.trim()||We(e)}function Nn(e,t){let n=Ln(e);if(n==="csh"||n==="tcsh")return{args:["-c",t],argv0:`-${n}`};return{args:["-i","-l","-c",t]}}function Bn(e){let t=e.indexOf(oe);if(t===-1)return;let n=e.indexOf(Fe,t);if(n===-1)return;let o=e.slice(t+oe.length,n).trim();return o.length>0?o:void 0}function Fn(e,t){let n=[...e.split(B),...t.split(B)].map((o)=>o.trim()).filter((o)=>o.length>0);return Array.from(new Set(n)).join(B)}function Vn(e,t=Ve){return new Promise((n)=>{let o=Nn(e,Un),r=Dn(e,o.args,{argv0:o.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),i="",a=0,u=()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}},c=!1,d=(m)=>{if(c)return;c=!0,clearTimeout(s),r.stdout?.destroy(),u(),n(m)},s=setTimeout(()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}d(void 0)},t);r.stdout?.on("data",(m)=>{if(c)return;if(a+=m.length,a>65536){d(void 0);return}i+=m.toString("utf8")}),r.on("error",()=>d(void 0)),r.on("close",()=>d(Bn(i)))})}async function $e(e){let t=e?.platform??process.platform,n=e?.env??process.env;if(t==="win32")return{status:"skipped",reason:"windows"};if(n[Be]?.trim())return{status:"skipped",reason:Be};let o=e?.userShell??Mn(t,n),r=e?.fallbackShell??We(t),i=e?.timeoutMs??Ve,a=o===r?[[o,i]]:[[o,i],[r,i/2]];for(let[u,c]of a){let d=await Vn(u,c);if(!d)continue;let s=Fn(d,n.PATH??"");return n.PATH=s,{status:"applied",pathEntries:s.split(B).length,shell:u}}return{status:"failed",shell:o}}var Ge={readHubDiscovery:b,clearHubDiscoveryIfOwned:ge,probeProcess:(e)=>{process.kill(e,0)},requestHubShutdown:M,ensureDetachedHubServer:L,claimHubDaemonProcess:$n,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:$e,setHomeDirIfUnset:Gn,homeDir:Wn,cwd:()=>process.cwd(),env:process.env,writeOutput:(e)=>process.stdout.write(e)};function je(e,t){let n=e.indexOf(t);return(n>=0?e[n+1]:void 0)?.trim()||void 0}function qe(e,t){let n=je(e,"--discovery-path");if(!n)throw Error("--discovery-path is required for remote Hub management");return t.env.CLINE_HUB_DISCOVERY_PATH=n,n}async function jn(e=process.argv,t=Ge){t.setHomeDirIfUnset(t.homeDir()),await t.ensureLoginShellPath();let n=je(e,"--cwd")??t.cwd();qe(e,t);let o=await t.ensureDetachedHubServer(n,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});t.writeOutput(`${JSON.stringify({...o,cwd:n,platform:process.platform,arch:process.arch})}
4
4
  `)}async function Ke(e=process.argv,t=Ge){if(e.includes("--remote-hub-stop")){let n=qe(e,t),o=await t.readHubDiscovery(n);if(o&&typeof o.pid==="number"&&Number.isInteger(o.pid)&&o.pid>0)try{t.probeProcess(o.pid)}catch(r){if(r?.code==="ESRCH")return await t.clearHubDiscoveryIfOwned(n,o.hubId),!0}if(o&&!await t.requestHubShutdown(o.url,o.authToken))throw Error("Remote Hub shutdown failed");return!0}if(e.includes("--remote-hub-ensure"))return await jn(e,t),!0;if(t.claimHubDaemonProcess())return await t.loadHubDaemon(),!0;return!1}(async()=>{if(!await Ke())throw Error("A remote helper command is required")})().catch((e)=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
@@ -1,4 +1,4 @@
1
- import{homedir as Vn}from"node:os";import{claimHubDaemonProcess as Wn}from"@cline/shared";import{setHomeDirIfUnset as $n}from"@cline/shared/storage";import{createSessionId as mn,ensureLoopbackProxyBypass as Ae,isHubProtocolCompatible as hn,resolveClineBuildEnv as bn,resolveHubCommandTimeoutMs as gn}from"@cline/shared";import yn from"ws";var H={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.88-nightly.1790735522",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",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:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","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:*","@modelcontextprotocol/sdk":"^1.29.0","@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:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var re="session_not_found";class F extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}import{spawn as Ot}from"node:child_process";import{closeSync as Dt,mkdirSync as At,openSync as Lt,readFileSync as Ut,unlinkSync as Mt}from"node:fs";import{basename as Nt,dirname as Bt,join as Ft}from"node:path";import{fileURLToPath as Vt}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as Wt,isBunEmbeddedModulePath as $t,isHubDaemonProcess as Gt,resolveClineBuildEnv as Te,withResolvedClineBuildEnv as jt}from"@cline/shared";import{createHash as Je,randomBytes as Ye}from"node:crypto";import{mkdir as W,open as ie,readFile as de,rename as Xe,rm as I,writeFile as Ze}from"node:fs/promises";import{dirname as le,join as G}from"node:path";import{ensureLoopbackProxyBypass as Qe,isHubProtocolCompatible as et}from"@cline/shared";import{resolveClineDataDir as P,resolveClineDir as Zn}from"@cline/shared/storage";var tt="CLINE_HUB_DISCOVERY_PATH",nt="CLINE_HUB_BUILD_ID",ot="CLINE_HUB_BUILD_EPOCH_MS",rt=30000,it=15000,se=100;function st(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function at(e){return Je("sha256").update(e).digest("hex").slice(0,12)}function ct(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function ae(e){return new Promise((t)=>setTimeout(t,e))}function ut(e){return`${e}.lock`}async function dt(e){try{let t=JSON.parse(await de(G(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function V(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[nt]?.trim();if(e)return e;return"sdk-v1-0982e787428525296f7c82ef42aff77c3cee5087192bf30b19f8018599e7f0ab".trim()||`source-${String(H.version)}`}function lt(){let e=Number(process.env[ot]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735549231)?1790735549231:void 0}function x(e,t=k()){let n=et(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ce(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ue(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function pt(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function pe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ce(e.buildEpochMs),i=ce(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let a=ue(e.coreVersion),u=ue(t.coreVersion);if(a&&u){let c=pt(a,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function fe(){return{buildId:k(),buildEpochMs:lt(),coreVersion:String(H.version)}}function O(e,t){let n=t?.self??fe(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return pe(n,e)<=0}function me(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${at(e)}`,n=process.env[tt]?.trim()||G(P(),"locks","hub","owners",`${st(t)}.json`);return{ownerId:t,discoveryPath:n}}async function g(e){try{let t=JSON.parse(await de(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function he(e,t){await j(e,async()=>{let n=le(e);await W(n,{recursive:!0});let o=`${e}.${process.pid}.${Ye(6).toString("hex")}.tmp`,r;try{r=await ie(o,"wx",384),await r.writeFile(`${JSON.stringify(t,null,2)}
1
+ import{homedir as Vn}from"node:os";import{claimHubDaemonProcess as Wn}from"@cline/shared";import{setHomeDirIfUnset as $n}from"@cline/shared/storage";import{createSessionId as mn,ensureLoopbackProxyBypass as Ae,isHubProtocolCompatible as hn,resolveClineBuildEnv as bn,resolveHubCommandTimeoutMs as gn}from"@cline/shared";import yn from"ws";var H={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.88",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",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:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","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:*","@modelcontextprotocol/sdk":"^1.29.0","@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:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var re="session_not_found";class F extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}import{spawn as Ot}from"node:child_process";import{closeSync as Dt,mkdirSync as At,openSync as Lt,readFileSync as Ut,unlinkSync as Mt}from"node:fs";import{basename as Nt,dirname as Bt,join as Ft}from"node:path";import{fileURLToPath as Vt}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as Wt,isBunEmbeddedModulePath as $t,isHubDaemonProcess as Gt,resolveClineBuildEnv as Te,withResolvedClineBuildEnv as jt}from"@cline/shared";import{createHash as Je,randomBytes as Ye}from"node:crypto";import{mkdir as W,open as ie,readFile as de,rename as Xe,rm as I,writeFile as Ze}from"node:fs/promises";import{dirname as le,join as G}from"node:path";import{ensureLoopbackProxyBypass as Qe,isHubProtocolCompatible as et}from"@cline/shared";import{resolveClineDataDir as P,resolveClineDir as Zn}from"@cline/shared/storage";var tt="CLINE_HUB_DISCOVERY_PATH",nt="CLINE_HUB_BUILD_ID",ot="CLINE_HUB_BUILD_EPOCH_MS",rt=30000,it=15000,se=100;function st(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function at(e){return Je("sha256").update(e).digest("hex").slice(0,12)}function ct(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function ae(e){return new Promise((t)=>setTimeout(t,e))}function ut(e){return`${e}.lock`}async function dt(e){try{let t=JSON.parse(await de(G(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function V(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[nt]?.trim();if(e)return e;return"sdk-v1-814d0cfa563d6988b7812b459881e191a794af2da082cd021d824a3bcb05b043".trim()||`source-${String(H.version)}`}function lt(){let e=Number(process.env[ot]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735496846)?1790735496846:void 0}function x(e,t=k()){let n=et(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ce(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ue(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function pt(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function pe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ce(e.buildEpochMs),i=ce(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let a=ue(e.coreVersion),u=ue(t.coreVersion);if(a&&u){let c=pt(a,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function fe(){return{buildId:k(),buildEpochMs:lt(),coreVersion:String(H.version)}}function O(e,t){let n=t?.self??fe(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return pe(n,e)<=0}function me(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${at(e)}`,n=process.env[tt]?.trim()||G(P(),"locks","hub","owners",`${st(t)}.json`);return{ownerId:t,discoveryPath:n}}async function g(e){try{let t=JSON.parse(await de(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function he(e,t){await j(e,async()=>{let n=le(e);await W(n,{recursive:!0});let o=`${e}.${process.pid}.${Ye(6).toString("hex")}.tmp`,r;try{r=await ie(o,"wx",384),await r.writeFile(`${JSON.stringify(t,null,2)}
2
2
  `,{encoding:"utf8"}),await r.sync(),await r.close(),r=void 0,await Xe(o,e);let i;try{i=await ie(n,"r"),await i.sync()}catch{}finally{await i?.close().catch(()=>{return})}}catch(i){throw await r?.close().catch(()=>{return}),await I(o,{force:!0}).catch(()=>{return}),i}})}async function C(e){await j(e,async()=>{await I(e,{force:!0}).catch(()=>{return})})}async function be(e,t){return await j(e,async()=>{if((await g(e))?.hubId!==t)return!1;return await I(e,{force:!0}),!0})}async function ge(e,t,n){let o=ut(e);await W(le(o),{recursive:!0});let r=Date.now()+it;while(!0){try{await W(o,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let u=await dt(o);if(!u){if(Date.now()>=r){await V(o);continue}await ae(se);continue}let c=Date.now()-Date.parse(u.acquiredAt);if(!ct(u.pid)||c>rt){await V(o);continue}if(Date.now()>=r)throw Error(`Timed out waiting for hub ${t} lock ${o}`);await ae(se);continue}try{return await Ze(G(o,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
3
  `,"utf8"),await n()}finally{await V(o)}}}function j(e,t){return ge(`${e}.mutation`,"discovery mutation",t)}function ye(e,t){return ge(e,"startup",t)}async function D(e,t){Qe();try{let n=await fetch(t?.authToken?ft(e):ve(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let o=await n.json();if(typeof o.protocolVersion!=="string"||typeof o.host!=="string"||typeof o.port!=="number"||typeof o.url!=="string")return;return{protocolVersion:o.protocolVersion,minClientProtocolVersion:typeof o.minClientProtocolVersion==="string"?o.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof o.maxClientProtocolVersion==="string"?o.maxClientProtocolVersion:void 0,capabilities:Array.isArray(o.capabilities)?o.capabilities.filter((r)=>typeof r==="string"):void 0,coreVersion:typeof o.coreVersion==="string"?o.coreVersion:void 0,buildId:typeof o.buildId==="string"?o.buildId:void 0,buildEpochMs:typeof o.buildEpochMs==="number"?o.buildEpochMs:void 0,host:o.host,port:o.port,url:o.url,hubId:typeof o.hubId==="string"?o.hubId:void 0,authToken:typeof o.authToken==="string"?o.authToken:void 0,pid:typeof o.pid==="number"?o.pid:void 0,startedAt:typeof o.startedAt==="string"?o.startedAt:void 0,updatedAt:typeof o.updatedAt==="string"?o.updatedAt:void 0}}catch{return}}function we(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function ve(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function ft(e){let t=new URL(ve(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as mt,CLINE_HUB_PORT as ht,resolveClineBuildEnv as bt}from"@cline/shared";var gt="CLINE_HUB_HOST",yt="CLINE_HUB_PORT",wt="CLINE_HUB_PATHNAME",vt="127.0.0.1",St=ht,kt="/hub";function Se(e){return bt(e)==="development"?mt:St}function Ct(e={}){return(e.env??process.env)[gt]?.trim()||vt}function Ht(e={}){let n=(e.env??process.env)[yt]?.trim();if(!n)return Se(e);let o=Number.parseInt(n,10);if(!Number.isInteger(o)||o<1||o>65535)return Se(e);return o}function Pt(e={}){return(e.env??process.env)[wt]?.trim()||kt}function ke(e={},t={}){return{host:e.host??Ct(t),port:e.port??Ht(t),pathname:e.pathname??Pt(t)}}import{join as Tt}from"node:path";import{execFile as _t}from"node:child_process";import{promisify as Rt}from"node:util";import{processWorkspaceInfo as so}from"@cline/shared";import co from"simple-git";var uo=Rt(_t);var Et="shared:cline",It="CLINE_HUB_DISCOVERY_PATH",xt="hub-production";function _(e=Et){return me(`${e}@${k()}`)}function A(){return{ownerId:xt,discoveryPath:process.env[It]?.trim()||Tt(P(),"locks","hub","production.json")}}var Ce=15000,qt=200,He=3000,Kt=100,zt=[100,250,500,1000,2000],Jt="--cline-hub-daemon",Yt=3,Xt=60000,Pe=new Map;function Zt(e,t=Date.now()){let n=Pe.get(e);if(!n||t-n.windowStartedAt>Xt)return Pe.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Yt}function Qt(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function en(){try{let e=Ft(P(),"logs","hub-daemon.log");return At(Bt(e),{recursive:!0}),{fd:Lt(e,"a"),logPath:e}}catch{return}}function tn(){return Te()==="production"?A():_()}function R(e){return O(e)}function nn(e){try{let t=JSON.parse(Ut(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function q(e){try{Mt(`${e}.superseded`)}catch{}}function _e(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function T(e,t){try{return await D(e,{authToken:t})}catch{return}}async function Re(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await T(e))?.url)return!0;await new Promise((r)=>setTimeout(r,Kt))}return!1}async function z(e,t){if(!Zt(e.url))return!1;await E(e.url,e.authToken,"retired by newer install").catch(()=>!1),await M(e.url,e.authToken).catch(()=>!1);let n=await Re(e.url,He);if(!n&&e.pid&&on(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Re(e.url,He)}if(n)await C(t).catch(()=>{return});return n}function on(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function rn(e){try{return(await J(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function K(e,t){if(R(e))return"reusable";let n=await E(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await rn(e)){if(n)await E(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let o=await z(e,t);if(!o&&n)await E(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return o?"retired":"failed"}async function sn(e){if(Te()!=="production")return;let t=_();if(t.discoveryPath===e.discoveryPath)return;let n=await g(t.discoveryPath);if(n?.url)await z(n,t.discoveryPath);else await C(t.discoveryPath).catch(()=>{return})}function an(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return Vt(new URL(`./entry.${e}`,import.meta.url))}function cn(e,t){if($t(e))return[Jt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function un(e,t){let n=an(),o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let r=Nt(o).toLowerCase().includes("bun"),i=cn(n,r);return{launcher:o,args:[...i,"--cwd",e,...Qt(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...jt(process.env),CLINE_NO_INTERACTIVE:"1",[Wt]:"1"}}}function dn(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function ln(e,t={}){if(Gt())return;let n=un(e,t),o=en();try{Ot(n.launcher,n.args,{detached:!0,stdio:o?["ignore",o.fd,o.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(o)Dt(o.fd)}}async function pn(e,t={}){for(let n=0;;n++)try{ln(e,t);return}catch(o){let r=zt[n];if(!dn(o)||r===void 0)throw o;await new Promise((i)=>setTimeout(i,r))}}async function fn(e,t,n={}){let o=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),r=ke(n),i=we(r.host,r.port,r.pathname),a=(l)=>{if(!o)U(l.url,l.authToken);return l};await sn(e).catch(()=>{return});let u=await g(e.discoveryPath),c=u?.url?void 0:nn(e.discoveryPath),d=!1;if(u?.url){let l=u.authToken;if(!l)d=!0,await z(u,e.discoveryPath);else{let p=await T(u.url,l);if(p?.url&&R(p)&&await y(p.url,{authToken:l}))return q(e.discoveryPath),a({url:p.url,authToken:l});if(p?.url){if(await K({...p,authToken:l},e.discoveryPath)==="deferred_busy"&&await y(p.url,{authToken:l}))return a({url:p.url,authToken:l})}else await C(e.discoveryPath).catch(()=>{return})}}let s=await T(i);if(s?.url){let l=_e(s,u??c,i);if(R(s)){let h=[s.authToken,u?.authToken,c?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0);for(let S of h){if(!await y(s.url,{authToken:S}))continue;let Ke={hubId:s.hubId??`repaired-${s.port}`,protocolVersion:s.protocolVersion,minClientProtocolVersion:s.minClientProtocolVersion,maxClientProtocolVersion:s.maxClientProtocolVersion,capabilities:s.capabilities,coreVersion:s.coreVersion,buildId:s.buildId,authToken:S,host:s.host,port:s.port,url:s.url,pid:s.pid??u?.pid??c?.pid,startedAt:s.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await he(e.discoveryPath,Ke)}catch{}return q(e.discoveryPath),a({url:s.url,authToken:S})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${d?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let p=await K(l,e.discoveryPath);if(p==="deferred_busy"){for(let h of[l.authToken,u?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0))if(await y(s.url,{authToken:h}))return a({url:s.url,authToken:h});if(n.allowPortFallback!==!0&&r.port!==0)throw Error(`An older Cline Hub is running at ${i} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(p==="failed"&&n.allowPortFallback!==!0&&r.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let b=n.allowPortFallback===!0&&r.port!==0?{...r,port:0}:r;await pn(t,{...b,manageConnectors:n.manageConnectors});let w=Date.now()+Ce;while(Date.now()<w){let l=await g(e.discoveryPath);if(l?.url&&l.authToken){let h=await T(l.url,l.authToken);if(h?.url&&R(h)&&await y(h.url,{authToken:l.authToken}))return q(e.discoveryPath),a({url:h.url,authToken:l.authToken})}let p=await T(i);if(p?.url&&!R(p)){let h=_e(p,l??c,i),v=await K(h,e.discoveryPath);if(v==="deferred_busy"&&l?.authToken&&await y(p.url,{authToken:l.authToken}))return a({url:p.url,authToken:l.authToken});if(v==="failed"&&n.allowPortFallback!==!0&&r.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((h)=>setTimeout(h,qt))}throw Error(`Timed out after ${Ce}ms waiting for detached hub startup.`)}async function L(e,t={}){let n=tn();return await ye(n.discoveryPath,async()=>fn(n,e,t))}function wn(){return bn()==="production"?A():_()}function vn(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Le(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return Le(e.data);return String(e)}function Sn(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function Ee(e){let t=e,n=Sn(t.reason);return new f("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:X,{closeCode:t.code,closeReason:n||void 0})}function Ie(e,t){if(e instanceof f)return e;if(e instanceof Error)return new f("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new f("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new f("hub_connect_failed",n);let o=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new f("hub_connect_failed",o?`Failed to connect to hub at ${t.toString()} (${o} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var Y="*",N=8000,kn="cline-hub-auth.",Ue=new Map,Me=new Set,Cn=3000;var X="Hub connection closed",Hn=250,Pn=5000,xe=0.5;class f extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function _n(e){return e instanceof f}class Z extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function ee(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let o=te(e.toString());return o?Ue.get(o):void 0}function Rn(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function te(e){if(!Rn(e))return;let t=new URL(Ne(e));return t.search="",t.hash="",t.toString()}function Oe(e){let t=te(e);return!!t&&Me.has(t)}function U(e,t){let n=te(e);if(n){if(Me.add(n),t?.trim())Ue.set(n,t)}return e}class ne{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new f("hub_connection_closed",X);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||ee(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,o=this.openSocket(e,t,n),r;this.connectPromise=o.then(async(a)=>{if(r=a,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(H.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{a.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let u of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(u));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(a){if(this.connectPromise===i)this.connectPromise=void 0;if(r&&this.socket===r){this.lastCloseError=Ie(a,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{r.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw a}}async openSocket(e,t,n){let o=this.options.resolveConnectionHeaders,r;if(o){let c;try{r=await Promise.race([Promise.resolve().then(()=>o()),new Promise((d,s)=>{c=setTimeout(()=>{s(new f("hub_connect_timeout",`Timed out resolving hub connection headers after ${N}ms`))},N)})])}catch(d){let s=d instanceof f?d:new f("hub_connect_failed",d instanceof Error?d.message:String(d));if(n===this.connectGeneration)this.lastCloseError=s;throw s}finally{clearTimeout(c)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(r&&Object.keys(r).some((c)=>c.toLowerCase()==="sec-websocket-protocol")){let c=new f("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=c;throw c}let i=r?new yn(e.toString(),{headers:{...r}}):new(vn())(e.toString(),t?[`${kn}${t}`]:void 0);this.socket=i;let a=!1,u=new Promise((c,d)=>{let s=!1,m=setTimeout(()=>{if(s)return;s=!0,a=!0;let b=new f("hub_connect_timeout",`Timed out connecting to hub after ${N}ms`);if(this.socket===i)this.lastCloseError=b,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}d(b)},N);i.addEventListener("open",()=>{if(s)return;s=!0,clearTimeout(m),c()}),i.addEventListener("error",(b)=>{if(s)return;s=!0,clearTimeout(m);let w=Ie(b,e);if(this.socket===i)this.lastCloseError=w,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;d(w)}),i.addEventListener("close",(b)=>{if(s)return;s=!0,clearTimeout(m);let w=a?this.lastCloseError:Ee(b);if(this.socket===i){if(!a)this.lastCloseError=w,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}d(w)})});return i.addEventListener("message",(c)=>{this.handleFrame(JSON.parse(Le(c)))}),i.addEventListener("close",(c)=>{if(this.socket!==i)return;if(!a)this.lastCloseError=Ee(c),this.sawSocketClose=!0;this.registered=!1;for(let d of this.pendingReplies.values())d.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await u,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,o={listener:e,sessionId:n};return this.listeners.add(o),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(o))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,o){let r=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,o)}catch(a){if(!i||r>=1||!await this.recoverLocalHubTransport(a))throw a;r+=1}}async commandOnce(e,t,n,o,r=!0){if(r)await this.connect();o?.beforeDispatch?.();let i=mn("hubreq_");o?.onDispatch?.(i);let a=gn(e,o?.timeoutMs),u=new Promise((d,s)=>{let m=a===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;s(new Z(e,"hub_command_timeout",`Hub command ${e} timed out after ${a}ms (hub=${this.currentUrl}, requestId=${i}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},a);this.pendingReplies.set(i,{resolve:(b)=>{if(m)clearTimeout(m);d(b)},reject:(b)=>{if(m)clearTimeout(m);s(b)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:a,payload:t}})}catch(d){throw this.pendingReplies.delete(i),d}let c=await u;if(!c.ok){if(c.error?.code===re){let d=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new F(d,c.error.message)}throw new Z(e,c.error?.code,c.error?.message??`Hub command ${e} failed`)}return c}async recoverLocalHubTransport(e){if(!Oe(this.currentUrl)||!_n(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await De({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,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 e=Math.min(Hn*2**this.reconnectAttempt,Pn),t=Math.round(e*(1-xe)+Math.random()*e*xe);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Oe(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await De({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new f("hub_connection_closed",X);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.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(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new f("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),o=(this.subscriptionCounts.get(n)??0)+t;if(o<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,o),t>0&&o===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??Y}subscriptionSessionIdFromKey(e){return e===Y?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let o of[Y,n]){if(!o||!this.subscriptionCounts.has(o))continue;let r=this.lastEventSequenceByKey.get(o)??0;if(t>r)this.lastEventSequenceByKey.set(o,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Ne(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function y(e,t){let n=new ne({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function Q(e,t){let n=Ne(e),o=await D(n,{authToken:t?.authToken});if(!o)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let r=k(),i=x(o,r);if(!i.compatible&&!O(o))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!hn(o).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await y(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function Tn(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,o=new Set;for(let r of t){if(!r||typeof r!=="object")continue;let i=r.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let a of i){let u=a&&typeof a==="object"?a.clientId:void 0;if(typeof u==="string"&&u.trim())o.add(u)}}return{activeSessionCount:n,participantClientCount:o.size}}async function J(e,t,n){let o=new ne({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let r=await o.command("session.list",{limit:500},void 0,{timeoutMs:Cn});return Tn(r.payload)}finally{await o.dispose().catch(()=>{return})}}async function En(e,t,n){try{return(await J(e,t,n)).activeSessionCount===0}catch{return!1}}async function In(e,t){let n=`${e.discoveryPath}.superseded`,o=await g(n);if(!o?.url||!o.authToken)return;let r=await Q(o.url,{authToken:o.authToken});if(r.status!=="compatible")return;if(await En(r.url,o.authToken,t))return;return U(r.url,o.authToken)}async function xn(e={}){if(e.endpoint?.trim()){let r=await Q(e.endpoint);return r.status==="compatible"?r.url:void 0}let t=wn(),n=await g(t.discoveryPath);if(!n?.url)return await In(t,e);let o=await Q(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(o.status==="compatible")return U(o.url,n.authToken);if(o.status==="protocol_mismatch")await C(t.discoveryPath).catch(()=>{return});return}async function De(e={}){let t=await xn(e);if(t&&await y(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await L(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function E(e,t,n,o){Ae();let r=new URL(e),i=t?.trim()||ee(r);if(r.protocol==="ws:")r.protocol="http:";else if(r.protocol==="wss:")r.protocol="https:";if(r.pathname="/drain",r.hash="",n)r.searchParams.set("reason",n);if(o?.off)r.searchParams.set("off","1");return(await fetch(r,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function M(e,t){Ae();let n=new URL(e),o=t?.trim()||ee(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:o?{authorization:`Bearer ${o}`}:void 0})).ok}import{spawn as On}from"node:child_process";import{userInfo as Dn}from"node:os";import{basename as An,delimiter as B}from"node:path";var oe="__CLINE_SIDECAR_PATH_START__",Fe="__CLINE_SIDECAR_PATH_END__",Ve=5000,Ln=`/bin/sh -c 'printf "%s%s%s" "${oe}" "$PATH" "${Fe}"'`,Be="CLINE_SIDECAR_SKIP_SHELL_PATH";function We(e){return e==="darwin"?"/bin/zsh":"/bin/bash"}function Un(e,t){try{let n=Dn().shell?.trim();if(n)return n}catch{}return t.SHELL?.trim()||We(e)}function Mn(e,t){let n=An(e);if(n==="csh"||n==="tcsh")return{args:["-c",t],argv0:`-${n}`};return{args:["-i","-l","-c",t]}}function Nn(e){let t=e.indexOf(oe);if(t===-1)return;let n=e.indexOf(Fe,t);if(n===-1)return;let o=e.slice(t+oe.length,n).trim();return o.length>0?o:void 0}function Bn(e,t){let n=[...e.split(B),...t.split(B)].map((o)=>o.trim()).filter((o)=>o.length>0);return Array.from(new Set(n)).join(B)}function Fn(e,t=Ve){return new Promise((n)=>{let o=Mn(e,Ln),r=On(e,o.args,{argv0:o.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),i="",a=0,u=()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}},c=!1,d=(m)=>{if(c)return;c=!0,clearTimeout(s),r.stdout?.destroy(),u(),n(m)},s=setTimeout(()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}d(void 0)},t);r.stdout?.on("data",(m)=>{if(c)return;if(a+=m.length,a>65536){d(void 0);return}i+=m.toString("utf8")}),r.on("error",()=>d(void 0)),r.on("close",()=>d(Nn(i)))})}async function $e(e){let t=e?.platform??process.platform,n=e?.env??process.env;if(t==="win32")return{status:"skipped",reason:"windows"};if(n[Be]?.trim())return{status:"skipped",reason:Be};let o=e?.userShell??Un(t,n),r=e?.fallbackShell??We(t),i=e?.timeoutMs??Ve,a=o===r?[[o,i]]:[[o,i],[r,i/2]];for(let[u,c]of a){let d=await Fn(u,c);if(!d)continue;let s=Bn(d,n.PATH??"");return n.PATH=s,{status:"applied",pathEntries:s.split(B).length,shell:u}}return{status:"failed",shell:o}}var Ge={readHubDiscovery:g,clearHubDiscoveryIfOwned:be,probeProcess:(e)=>{process.kill(e,0)},requestHubShutdown:M,ensureDetachedHubServer:L,claimHubDaemonProcess:Wn,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:$e,setHomeDirIfUnset:$n,homeDir:Vn,cwd:()=>process.cwd(),env:process.env,writeOutput:(e)=>process.stdout.write(e)};function je(e,t){let n=e.indexOf(t);return(n>=0?e[n+1]:void 0)?.trim()||void 0}function qe(e,t){let n=je(e,"--discovery-path");if(!n)throw Error("--discovery-path is required for remote Hub management");return t.env.CLINE_HUB_DISCOVERY_PATH=n,n}async function Gn(e=process.argv,t=Ge){t.setHomeDirIfUnset(t.homeDir()),await t.ensureLoginShellPath();let n=je(e,"--cwd")??t.cwd();qe(e,t);let o=await t.ensureDetachedHubServer(n,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});t.writeOutput(`${JSON.stringify({...o,cwd:n,platform:process.platform,arch:process.arch})}
4
4
  `)}async function qo(e=process.argv,t=Ge){if(e.includes("--remote-hub-stop")){let n=qe(e,t),o=await t.readHubDiscovery(n);if(o&&typeof o.pid==="number"&&Number.isInteger(o.pid)&&o.pid>0)try{t.probeProcess(o.pid)}catch(r){if(r?.code==="ESRCH")return await t.clearHubDiscoveryIfOwned(n,o.hubId),!0}if(o&&!await t.requestHubShutdown(o.url,o.authToken))throw Error("Remote Hub shutdown failed");return!0}if(e.includes("--remote-hub-ensure"))return await Gn(e,t),!0;if(t.claimHubDaemonProcess())return await t.loadHubDaemon(),!0;return!1}export{qo as runRemoteHelperEntrypoint,Gn as runRemoteHubEnsure};