@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/hub/index.js CHANGED
@@ -307,9 +307,9 @@ ${JSON.stringify(r,null,2)}`}startClaimLeaseHeartbeat(e){let t=Math.max(1000,Mat
307
307
  scheduled_for = COALESCE(?, scheduled_for),
308
308
  updated_at = ?
309
309
  WHERE run_id = ? AND claim_token = ?`).run(e.releaseAttempt?1:0,e.error??null,e.scheduledFor??null,t,e.runId,e.claimToken).changes??0)>0}attachSessionIdToRun(e,t,n){return(this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ? AND claim_token = ? AND status = 'running'").run(t,Ae(),e,n).changes??0)===1}attachReportPathToRun(e,t){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(t,Ae(),e)}}function Li(e){return e?new Date(e).getTime():void 0}function fE(e){let t=e.metadata?{...e.metadata}:void 0;if(t)delete t.__hubScheduleCreatedBy,delete t.__hubScheduleCwd,delete t.__hubRuntimeOptions;return t}function Do(e){let t=e.metadata;return{scheduleId:e.externalId,name:e.title,cronPattern:e.triggerKind==="one_off"?Ho:e.scheduleExpr??"",timezone:e.triggerKind==="schedule"?e.timezone:void 0,prompt:e.prompt??"",workspaceRoot:e.workspaceRoot??"",cwd:typeof t?.__hubScheduleCwd==="string"?t.__hubScheduleCwd:void 0,modelSelection:e.providerId||e.modelId?{providerId:e.providerId??"",modelId:e.modelId??""}:void 0,enabled:e.enabled&&!e.removed&&e.parseStatus==="valid",mode:e.mode==="plan"?"plan":e.mode==="act"?"act":"yolo",systemPrompt:e.systemPrompt,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,maxParallel:e.maxParallel??1,createdAt:new Date(e.createdAt).getTime(),updatedAt:new Date(e.updatedAt).getTime(),nextRunAt:Li(e.nextRunAt),lastRunAt:Li(e.lastRunAt),createdBy:typeof t?.__hubScheduleCreatedBy==="string"?t.__hubScheduleCreatedBy:void 0,tags:e.tags,runtimeOptions:t?.__hubRuntimeOptions&&typeof t.__hubRuntimeOptions==="object"&&!Array.isArray(t.__hubRuntimeOptions)?t.__hubRuntimeOptions:void 0,metadata:fE(e)}}function hE(e){switch(e){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function Mc(e,t){return{executionId:e.runId,scheduleId:t,sessionId:e.sessionId,triggeredAt:new Date(e.scheduledFor??e.createdAt).getTime(),startedAt:Li(e.startedAt),endedAt:Li(e.completedAt),status:hE(e.status),errorMessage:e.error}}class Ni{store;materializer;runner;started=!1;disposed=!1;constructor(e){this.store=new No({dbPath:e.dbPath}),this.materializer=new Ro({store:this.store}),this.runner=new _o({store:this.store,materializer:this.materializer,runtimeHandlers:e.runtimeHandlers,eventPublisher:e.eventPublisher,workspaceRoot:"",specs:e.specs,logger:e.logger,telemetry:e.telemetry,pollIntervalMs:e.pollIntervalMs,claimLeaseSeconds:e.claimLeaseSeconds,globalMaxConcurrency:e.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule(e){let t=e.cronPattern===Ho?e.timezone:e.timezone?.trim()||Intl.DateTimeFormat().resolvedOptions().timeZone;if(this.validateScheduleTiming(e.cronPattern,t,e.metadata,!0),!e.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return Do(this.store.createHubSchedule({...e,timezone:t}))}getSchedule(e){let t=this.store.getHubSchedule(e);return t?Do(t):void 0}listSchedules(e={}){return this.store.listHubSchedules(e).map((t)=>Do(t))}updateSchedule(e,t){let n=this.store.getHubSchedule(e);if(!n)return;let r=t.workspaceRoot!==void 0?t.workspaceRoot.trim():n.workspaceRoot,o=t.enabled??n.enabled,s=Do(n),i=t.cronPattern??s.cronPattern;if(i.trim()===Ho&&typeof t.timezone==="string"&&t.timezone.trim())throw Error("timezone is only supported for recurring schedules");if(this.validateScheduleTiming(i,i.trim()===Ho?void 0:t.timezone===null?void 0:t.timezone??s.timezone,t.metadata??s.metadata,o),o&&!r)throw Error("workspaceRoot is required for enabled schedules");let a=this.store.updateHubSchedule(e,{...t,scheduleId:e});return a?Do(a):void 0}validateScheduleTiming(e,t,n,r){if(e.trim()!==Ho){Kf(e),Pc(t);return}if(t?.trim())throw Error("timezone is only supported for recurring schedules");let o=n?.[gE];if(typeof o!=="number"||!Number.isFinite(o)||r&&o<=Date.now())throw Error("runAt must be a future timestamp")}deleteSchedule(e){return this.store.deleteHubSchedule(e)}pauseSchedule(e){return this.updateSchedule(e,{scheduleId:e,enabled:!1})}resumeSchedule(e){return this.updateSchedule(e,{scheduleId:e,enabled:!0})}async triggerScheduleNow(e){let t=this.store.enqueueHubScheduleRun(e,"manual");if(!t)return;await this.runner.tick();let n=this.store.getRun(t.runId)??t;return Mc(n,e)}triggerScheduleNowDetached(e){let t=this.store.enqueueHubScheduleRun(e,"manual");if(!t)return;return this.runner.tick().catch(()=>{return}),Mc(t,e)}listScheduleExecutions(e){let t=e.scheduleId?this.store.getHubSchedule(e.scheduleId):void 0,n={specId:t?.specId,limit:e.limit};return this.store.listRuns(n).map((o)=>{let s=t??this.store.getSpec(o.specId);if(!s||s.source!=="hub-schedule")return;return Mc(o,s.externalId)}).filter((o)=>{if(!o)return!1;return!e.status||o.status===e.status})}getScheduleStats(e){let t=this.listScheduleExecutions({scheduleId:e,limit:1e4});if(t.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let n=0,r=0,o=0,s;for(let i of t){if(i.status==="success"||i.status==="completed")n+=1;if(!s&&i.status!=="success"&&i.status!=="completed")s=i;if(i.startedAt&&i.endedAt)o+=i.endedAt-i.startedAt,r+=1}return{totalRuns:t.length,successRate:n/t.length,avgDurationSeconds:r>0?o/r/1000:0,lastFailure:s}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((e)=>{let t=this.store.getSpec(e.specId);if(!t||t.source!=="hub-schedule"||!e.sessionId)return[];return[{executionId:e.runId,scheduleId:t.externalId,sessionId:e.sessionId,startedAt:e.startedAt??new Date().toISOString(),timeoutAt:t.timeoutSeconds&&e.startedAt?new Date(new Date(e.startedAt).getTime()+t.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(e=20){let t={triggerKind:"schedule",enabled:!0,limit:e};return this.store.listSpecs(t).flatMap((n)=>n.source==="hub-schedule"&&n.nextRunAt?[{spec:n,nextRunAt:n.nextRunAt}]:[]).sort((n,r)=>String(n.nextRunAt).localeCompare(String(r.nextRunAt))).slice(0,e).map(({spec:n,nextRunAt:r})=>({scheduleId:n.externalId,name:n.title,nextRunAt:r}))}}import{realpathSync as Lc,statSync as yE}from"node:fs";import{isAbsolute as rh,relative as SE,sep as oh}from"node:path";import{ONE_TIME_SCHEDULE_CRON_PATTERN as sh,ONE_TIME_SCHEDULE_RUN_AT_METADATA_KEY as ih}from"@cline/shared";import{z as he}from"zod";var bE=he.enum(["create","update","list","get","pause","resume","delete","run_now"]),vE=he.object({provider_id:he.string().min(1),model_id:he.string().min(1).optional()}),Mr=he.object({operation:bE,schedule_id:he.string().min(1).optional(),schedule_type:he.enum(["once","recurring"]).optional(),name:he.string().min(1).optional(),prompt:he.string().min(1).optional(),run_at:he.string().datetime({offset:!0}).optional(),cron_pattern:he.string().min(1).optional(),timezone:he.string().min(1).nullable().optional().describe("IANA timezone for recurring schedules. Omit unless the user explicitly requests a timezone; new schedules default to the local timezone. Updates preserve the existing timezone when omitted."),enabled:he.boolean().optional(),mode:he.enum(["act","plan","yolo"]).optional(),system_prompt:he.string().nullable().optional(),max_iterations:he.number().int().positive().nullable().optional(),timeout_seconds:he.number().int().positive().nullable().optional(),max_parallel:he.number().int().positive().max(32).optional(),tags:he.array(he.string().min(1)).optional(),model_selection:vE.optional(),limit:he.number().int().positive().max(200).optional()});function Pr(e,t,n,r){if(!ah.has(t.operation))return;dn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.scheduled.${t.operation}`,success:r,agentId:n.agentId})}var ah=new Set(["create","update","pause","resume","delete","run_now"]);function xr(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Nc(e,t){try{let n=Lc.native(e);if(!yE(n).isDirectory())throw Error("not a directory");return n}catch{throw Error(`${t} does not resolve to an existing safe path`)}}function TE(e,t){try{return Lc.native(e)===Lc.native(t)}catch{return!1}}function dh(e,t,n){let r=SE(e,t);if(r===".."||r.startsWith(`..${oh}`)||rh(r))throw Error(`${n} is outside the workspace scope`)}function ch(e,t,n){return Nc(rh(t)?t:`${e}${oh}${t}`,n)}function wE(e){let t=Nc(e.workspaceRoot,"workspaceRoot"),n=e.cwd?ch(t,e.cwd,"cwd"):t;return dh(t,n,"cwd"),{...e,workspaceRoot:t,cwd:n}}function _r(e,t){if(!e)throw Error("schedule does not exist");if(!TE(e.workspaceRoot,t.workspaceRoot))throw Error("schedule is outside this session's workspace scope");let n=Nc(e.workspaceRoot,"schedule workspaceRoot");if(e.cwd){let r=ch(n,e.cwd,"schedule cwd");dh(n,r,"schedule cwd")}}function nh(e){if(!e)return;return{providerId:e.provider_id.trim(),modelId:e.model_id?.trim()||void 0}}function Oc(e){if(!e)return;return[...new Set(e.map((t)=>t.trim()).filter(Boolean))]}function uh(e){let t=Date.parse(xr(e,"run_at"));if(!Number.isFinite(t))throw Error("run_at must be an ISO timestamp");if(t<=Date.now())throw Error("run_at must be in the future");return t}function kE(e){if(e.schedule_type==="once"){if(e.cron_pattern)throw Error("cron_pattern cannot be used with a one-time schedule");if(e.timezone)throw Error("timezone is encoded in run_at for a one-time schedule");return{cronPattern:sh,metadata:{[ih]:uh(e.run_at)}}}if(e.schedule_type==="recurring"){if(e.run_at)throw Error("run_at cannot be used with a recurring schedule");return{cronPattern:xr(e.cron_pattern,"cron_pattern"),timezone:e.timezone?.trim()||void 0}}throw Error("schedule_type is required for create")}function CE(e){if(e.run_at&&e.cron_pattern)throw Error("run_at and cron_pattern cannot be updated together");if(e.schedule_type==="once"||e.run_at){if(e.cron_pattern)throw Error("cron_pattern cannot be used with a one-time schedule");if(e.timezone)throw Error("timezone is encoded in run_at for a one-time schedule");return{cronPattern:sh,timezone:null,metadata:{[ih]:uh(e.run_at)}}}if(e.schedule_type==="recurring"||e.cron_pattern)return{cronPattern:xr(e.cron_pattern,"cron_pattern"),timezone:e.timezone===null?null:e.timezone?.trim()||void 0};return{timezone:e.timezone===null?null:e.timezone?.trim()||void 0}}function Uo(e){return xr(e.schedule_id,"schedule_id")}async function Dc(e,t,n){let r=Mr.safeParse(t);if(!r.success)return{ok:!1,error:{code:"invalid_schedule_input",message:r.error.issues[0]?.message??"Invalid schedule input"}};let o=r.data;try{if(!n.sessionId)throw Error("tasks requires a Hub session");let s=await e.resolveSessionDefaults(n.sessionId);if(!s?.workspaceRoot.trim())throw Error("tasks could not resolve the current workspace");let i=wE(s);if(ah.has(o.operation)&&!i.interactive)throw Error("schedule mutations require an interactive user session");switch(o.operation){case"create":{let a=e.schedules.createSchedule({name:xr(o.name,"name"),...kE(o),prompt:xr(o.prompt,"prompt"),workspaceRoot:i.workspaceRoot,cwd:i.cwd,modelSelection:nh(o.model_selection)??i.modelSelection,enabled:o.enabled,mode:o.mode??"yolo",systemPrompt:o.system_prompt??void 0,maxIterations:o.max_iterations??void 0,timeoutSeconds:o.timeout_seconds??void 0,maxParallel:o.max_parallel??1,createdBy:`agent:${n.agentId}`,tags:Oc(o.tags)});return e.publish?.("schedule.created",{schedule:a},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:a}}case"update":{let a=Uo(o);_r(e.schedules.getSchedule(a),i);let d=e.schedules.updateSchedule(a,{scheduleId:a,...CE(o),name:o.name?.trim()||void 0,prompt:o.prompt?.trim()||void 0,modelSelection:nh(o.model_selection),enabled:o.enabled,mode:o.mode,systemPrompt:o.system_prompt,maxIterations:o.max_iterations,timeoutSeconds:o.timeout_seconds,maxParallel:o.max_parallel,tags:Oc(o.tags)});if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.updated",{schedule:d},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"list":{let a=e.schedules.listSchedules({enabled:o.enabled,tags:Oc(o.tags),workspaceRoot:i.workspaceRoot,limit:o.limit??50}).filter((d)=>{try{return _r(d,i),!0}catch{return!1}}).slice(0,o.limit??50);return{ok:!0,operation:o.operation,schedules:a}}case"get":{let a=e.schedules.getSchedule(Uo(o));return _r(a,i),{ok:!0,operation:o.operation,schedule:a}}case"pause":case"resume":{let a=Uo(o);_r(e.schedules.getSchedule(a),i);let d=o.operation==="pause"?e.schedules.pauseSchedule(a):e.schedules.resumeSchedule(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.updated",{schedule:d},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"delete":{let a=Uo(o);_r(e.schedules.getSchedule(a),i);let d=e.schedules.deleteSchedule(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.deleted",{deleted:d,scheduleId:a},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,deleted:d}}case"run_now":{let a=Uo(o);_r(e.schedules.getSchedule(a),i);let d=e.schedules.triggerScheduleNowDetached(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.triggered",{execution:d},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,execution:d}}}}catch(s){return Pr(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"schedule_operation_failed",message:s instanceof Error?s.message:String(s)}}}}import{LangfuseAttributesSpanProcessor as JE}from"@cline/llms";import{markOtlpTraceRelayProvider as YE}from"@cline/shared";import{metrics as QE,trace as ZE}from"@opentelemetry/api";import{logs as eP}from"@opentelemetry/api-logs";import{OTLPLogExporter as tP}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as nP}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as rP}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as oP}from"@opentelemetry/resources";import{BatchLogRecordProcessor as sP,ConsoleLogRecordExporter as iP,LoggerProvider as aP}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as dP,MeterProvider as cP,PeriodicExportingMetricReader as Eh}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as uP,ConsoleSpanExporter as lP,SimpleSpanProcessor as pP}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as mP}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as gP,ATTR_SERVICE_VERSION as fP}from"@opentelemetry/semantic-conventions";import{mkdirSync as IE,readFileSync as AE,statSync as RE,writeFileSync as EE}from"node:fs";import{dirname as PE}from"node:path";import{CONFIGURABLE_MODEL_TOOL_NAMES as lh}from"@cline/shared";import{resolveGlobalSettingsPath as ph}from"@cline/shared/storage";import{z as Ue}from"zod";var Hc=Ue.preprocess((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string").map((t)=>t.trim()).filter(Boolean):void 0,Ue.array(Ue.string()).optional()).transform((e)=>{if(!e)return;let t=[...new Set(e)].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}),_E=Ue.enum(["basic","agentic"]).catch("agentic"),xE=Ue.partialRecord(Ue.enum(lh),Ue.object({enabled:Ue.boolean()}).strip()).optional(),ME=Ue.enum(["plan","act"]),Uc=Ue.object({telemetryOptOut:Ue.boolean().default(!1).catch(!1),autoUpdateEnabled:Ue.boolean().default(!0).catch(!0),compactionStrategy:_E.optional(),compactionEnabled:Ue.boolean().optional().catch(void 0),planActMode:ME.optional().catch(void 0),toolAutoApprove:Ue.boolean().optional().catch(void 0),tuiTheme:Ue.string().optional().catch(void 0),disabledTools:Hc.optional(),tools:xE,disabledPlugins:Hc.optional(),disabledAgentPlugins:Hc.optional()}).strip().transform((e)=>{let t={autoUpdateEnabled:e.autoUpdateEnabled,telemetryOptOut:e.telemetryOptOut};if(e.compactionStrategy)t.compactionStrategy=e.compactionStrategy;if(e.compactionEnabled!==void 0)t.compactionEnabled=e.compactionEnabled;if(e.planActMode)t.planActMode=e.planActMode;if(e.toolAutoApprove!==void 0)t.toolAutoApprove=e.toolAutoApprove;if(e.tuiTheme?.trim())t.tuiTheme=e.tuiTheme.trim();if(e.disabledTools?.length)t.disabledTools=e.disabledTools;if(e.tools&&Object.keys(e.tools).length>0)t.tools=e.tools;if(e.disabledPlugins?.length)t.disabledPlugins=e.disabledPlugins;if(e.disabledAgentPlugins?.length)t.disabledAgentPlugins=e.disabledAgentPlugins;return t});function Di(){return Uc.parse({})}var Hi;function OE(){Hi=void 0}function LE(e){if(e.disabledTools)Object.freeze(e.disabledTools);if(e.tools){for(let t of Object.values(e.tools))Object.freeze(t);Object.freeze(e.tools)}if(e.disabledPlugins)Object.freeze(e.disabledPlugins);if(e.disabledAgentPlugins)Object.freeze(e.disabledAgentPlugins);return Object.freeze(e)}function NE(e){let t;try{t=AE(e,"utf8")}catch{return{value:Di(),loadFailed:!0}}try{let n=Uc.safeParse(JSON.parse(t));return n.success?{value:n.data,loadFailed:!1}:{value:Di(),loadFailed:!0}}catch{return{value:Di(),loadFailed:!0}}}function mh(){let e=ph(),t=RE(e,{throwIfNoEntry:!1}),n=t?.mtimeMs??0,r=t?.size??0,o=Hi;if(o&&o.path===e&&o.mtimeMs===n&&o.size===r)return o;let s=t?NE(e):{value:Di(),loadFailed:!1},i=LE(s.value);return Hi={path:e,mtimeMs:n,size:r,value:i,loadFailed:s.loadFailed},Hi}function at(){return mh().value}function Fo(e,t={}){let n=ph(),r=at();IE(PE(n),{recursive:!0});let o=Uc.parse(e);if(!r.telemetryOptOut&&o.telemetryOptOut)sf(t.telemetry);EE(n,`${JSON.stringify(o,null,2)}
310
- `,"utf8"),OE()}function gh(){return at().telemetryOptOut}function Nn(e){return new Set(e??at().disabledTools??[])}function fh(e){return new Set(e??at().disabledPlugins??[])}function Bo(e){return new Set(e??at().disabledAgentPlugins??[])}function hh(e){return lh.includes(e)}function DE(){let e=mh();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function Fc(e){return DE()[e]?.enabled===!0}function HE(e,t){let n=at();Fo({...n,tools:{...n.tools,[e]:{enabled:t}}})}function yh(e){if(hh(e)){let o=Fc(e);return HE(e,!o),o}let t=at(),n=new Set(t.disabledTools??[]),r=n.has(e);if(r)n.delete(e);else n.add(e);return Fo({...t,disabledTools:[...n]}),!r}function UE(e,t){let n=[...new Set(e.map((i)=>i.trim()).filter(Boolean))];if(n.length===0)return;let r=at(),o=Nn(r.disabledTools),s={...r.tools};for(let i of n){if(hh(i)){s[i]={enabled:!t};continue}if(t)o.add(i);else o.delete(i)}Fo({...r,disabledTools:[...o],tools:s})}function Sh(e,t){return UE([e],t),t}function bh(e,t){let n=e.trim();if(!n)return;let r=at(),o=fh(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Fo({...r,disabledPlugins:[...o]})}function vh(e,t){let n=e.trim();if(!n)return;let r=at(),o=Bo(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Fo({...r,disabledAgentPlugins:[...o]})}function Th(e,t){let n=fh(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r))}function Dn(e,t){let n=Nn(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r.name))}function wh(e,t){if(!e||e.length===0)return e;let n=Nn(t);if(n.size===0)return e;return e.map((r)=>{if(!r.setup)return r;return{...r,setup:(o,s)=>r.setup?.({...o,registerTool:(i)=>{if(!n.has(i.name))o.registerTool(i)}},s)}})}import{existsSync as FE,mkdirSync as BE,readFileSync as $E,writeFileSync as WE}from"node:fs";import{resolve as jE}from"node:path";import{resolveSessionDataDir as qE}from"@cline/shared/storage";import{nanoid as zE}from"nanoid";import*as KE from"node-machine-id";var GE="machine-id",kh,Ch=!1;function Ih(){if(!Ch)kh=Ah(),Ch=!0;return kh??Rh()}function $o(e){let t=e?.trim();if(t)return t;let n=Ah();if(n)return n;return Rh()}function VE(){let e=KE;return e.machineIdSync??e.default?.machineIdSync}function Ah(){try{let e=VE();if(!e)return;return e().trim()||void 0}catch{return}}function Rh(){let e=qE(),t=jE(e,GE);try{if(FE(t)){let r=$E(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${zE()}`;try{BE(e,{recursive:!0}),WE(t,n,"utf8")}catch{}return n}class Bc{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(e){this.name=e.name??"OpenTelemetryAdapter",this.metadata={...e.metadata},this.meterProvider=e.meterProvider,this.loggerProvider=e.loggerProvider,this.meter=e.meterProvider?.getMeter("cline")??null,this.logger=e.loggerProvider?.getLogger("cline")??null,this.enabled=e.enabled??!0,this.distinctId=e.distinctId,this.commonProperties=e.commonProperties?{...e.commonProperties}:{}}emit(e,t){if(!this.isEnabled())return;this.emitLog(e,t,!1)}emitRequired(e,t){this.emitLog(e,t,!0)}recordCounter(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.counters.get(e);if(!s)s=this.meter.createCounter(e,r?{description:r}:void 0),this.counters.set(e,s);s.add(t,this.flattenProperties(this.buildAttributes(n)))}recordHistogram(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.histograms.get(e);if(!s)s=this.meter.createHistogram(e,r?{description:r}:void 0),this.histograms.set(e,s);s.record(t,this.flattenProperties(this.buildAttributes(n)))}recordGauge(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.buildAttributes(n),i=JSON.stringify(s),a=this.gaugeValues.get(e);if(t===null){if(a){if(a.delete(i),a.size===0)this.gaugeValues.delete(e),this.gauges.delete(e)}return}let d=a;if(!d)d=new Map,this.gaugeValues.set(e,d);if(!this.gauges.has(e)){let c=this.meter.createObservableGauge(e,r?{description:r}:void 0);c.addCallback((u)=>{for(let l of this.snapshotGaugeSeries(e))u.observe(l.value,this.flattenProperties(l.attributes))}),this.gauges.set(e,c)}d.set(i,{value:t,attributes:s})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(e){this.distinctId=e}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(e,t,n){if(!this.logger)return;let r=this.flattenProperties(this.buildAttributes(t,n));this.logger.emit({severityText:"INFO",body:e,attributes:r})}buildAttributes(e,t=!1){return{...this.commonProperties,...this.metadata,...e,...this.distinctId?{distinct_id:this.distinctId}:{},...t?{_required:!0}:{}}}snapshotGaugeSeries(e){let t=this.gaugeValues.get(e);if(!t)return[];return Array.from(t.values(),(n)=>({value:n.value,attributes:n.attributes?{...n.attributes}:void 0}))}flattenProperties(e,t="",n=new WeakSet,r=0){if(!e)return{};let o={},s=100,i=10;for(let[a,d]of Object.entries(e)){if(a==="__proto__"||a==="constructor"||a==="prototype")continue;let c=t?`${t}.${a}`:a;if(d===null||d===void 0){o[c]=String(d);continue}if(Array.isArray(d)){let u=d.length>s?d.slice(0,s):d;try{o[c]=JSON.stringify(u)}catch{o[c]="[UnserializableArray]"}if(d.length>s)o[`${c}_truncated`]=!0,o[`${c}_original_length`]=d.length;continue}if(typeof d==="object"){if(d instanceof Date){o[c]=d.toISOString();continue}if(d instanceof Error){o[c]=d.message;continue}if(n.has(d)){o[c]="[Circular]";continue}if(r>=i){o[c]="[MaxDepthExceeded]";continue}n.add(d),Object.assign(o,this.flattenProperties(d,c,n,r+1));continue}if(XE(d)){o[c]=d;continue}try{o[c]=JSON.stringify(d)}catch{o[c]=String(d)}}return o}}function XE(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class $c{name;logger;enabled;constructor(e={}){this.name=e.name??"TelemetryLoggerSink",this.logger=e.logger,this.enabled=e.enabled??!0}emit(e,t){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:e,properties:t})}emitRequired(e,t){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:e,properties:t})}recordCounter(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:e,value:t,attributes:n,description:r,required:o===!0})}recordHistogram(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:e,value:t,attributes:n,description:r,required:o===!0})}recordGauge(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:e,value:t,attributes:n,description:r,required:o===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class Ui{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new $c({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??Ih(),this.commonProperties={...e.commonProperties??{}}}addAdapter(e){this.adapters.push(e)}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return this.adapters.some((e)=>e.isEnabled())}capture(e){let t=this.buildAttributes(e.properties);for(let n of this.adapters)n.emit(e.event,t)}captureRequired(e,t){let n=this.buildAttributes(t);for(let r of this.adapters)r.emitRequired(e,n)}recordCounter(e,t,n,r,o=!1){let s=this.buildAttributes(n);for(let i of this.adapters)i.recordCounter(e,t,s,r,o)}recordHistogram(e,t,n,r,o=!1){let s=this.buildAttributes(n);for(let i of this.adapters)i.recordHistogram(e,t,s,r,o)}recordGauge(e,t,n,r,o=!1){let s=this.buildAttributes(n);for(let i of this.adapters)i.recordGauge(e,t,s,r,o)}async flush(){await Promise.all(this.adapters.map((e)=>e.flush()))}async dispose(){await Promise.all(this.adapters.map((e)=>e.dispose()))}buildAttributes(e){let t=typeof e?.distinct_id==="string"&&e.distinct_id.trim()?e.distinct_id.trim():this.distinctId,n={...this.commonProperties,...this.metadata,...e,...t?{distinct_id:t}:{},device_id:this.deviceId};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}}class Ph{distinctId;metadata;commonProperties;constructor(e={}){this.distinctId=e.distinctId,this.metadata={...e.metadata??{}},this.commonProperties={...e.commonProperties??{}}}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return!1}capture(e){this.resolveProperties(e.properties)}captureRequired(e,t){this.resolveProperties(t)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(e){let t=typeof e?.distinct_id==="string"&&e.distinct_id.trim()?e.distinct_id.trim():this.distinctId,n={...this.commonProperties,...this.metadata,...e,...t?{distinct_id:t}:{}};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}}class _h{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=oP({[gP]:e.serviceName??"cline",...e.serviceVersion?{[fP]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)QE.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)eP.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return ZE.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new Bc({...e,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(e){let t=this.createAdapter({name:e.name,enabled:this.options.enabled,metadata:e.metadata});return new Ui({...e,adapters:[t],distinctId:$o(e.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(e){let t=Wc(this.options.metricsExporter);if(t.length===0)return null;let n=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),r=Math.min(30000,Math.floor(n*0.8)),o=t.map((s)=>vP(s,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:n,timeout:r})).filter((s)=>s!==null);if(o.length===0)return null;return new cP({resource:e,readers:o})}createTracerProvider(e){let t=Wc(this.options.tracesExporter);if(t.length===0)return null;let n=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,r=this.options.otlpTracesHeaders??this.options.otlpHeaders,o=[],s=!1;for(let a of t){let d=bP(a,{endpoint:n,headers:r,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(d){if(o.push(d),a!=="console")s=!0}}if(o.length===0)return null;let i=new mP({resource:e,spanProcessors:s?[new JE,...o]:o});if(s)YE(i);return i}createLoggerProvider(e){let t=Wc(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=SP(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new sP(o,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((r)=>r!==null);if(n.length===0)return null;return new aP({resource:e,processors:n})}}function hP(e){let t=new _h(e),n=t.createTelemetryService(e),r=()=>{n.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:e.enabled??!0,logsExporter:Array.isArray(e.logsExporter)?e.logsExporter.join(","):e.logsExporter,metricsExporter:Array.isArray(e.metricsExporter)?e.metricsExporter.join(","):e.metricsExporter,tracesExporter:Array.isArray(e.tracesExporter)?e.tracesExporter.join(","):e.tracesExporter,otlpProtocol:e.otlpProtocol,hasOtlpEndpoint:Boolean(e.otlpEndpoint),serviceName:e.serviceName,serviceVersion:e.serviceVersion})};if(!e.deferProviderCreatedEvent)r();return{provider:t,telemetry:n,emitProviderCreated:r}}function xh(e){if(gh())return{telemetry:new Ph(e)};if(e.enabled!==!0)return{telemetry:new Ui({...e,distinctId:$o(e.distinctId)})};return hP(e)}function yP(e){let{telemetry:t,provider:n,emitProviderCreated:r}=xh(e);return{telemetry:t,provider:n,flush:async()=>{let i=n;if(i&&typeof i.forceFlush==="function")try{await i.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([t.dispose(),n?.dispose()])},...e.deferProviderCreatedEvent&&r?{emitProviderCreated:r}:{}}}function Wc(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function SP(e,t){if(e==="console")return new iP;if(!t.endpoint)return null;let n=jc(t.endpoint,"/v1/logs");return new tP({url:n,headers:t.headers})}function bP(e,t){if(e==="console")return new pP(new lP);if(!t.endpoint)return null;let n=jc(t.endpoint,"/v1/traces");return new uP(new rP({url:n,headers:t.headers}))}function vP(e,t){if(e==="console")return new Eh({exporter:new dP,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=jc(t.endpoint,"/v1/metrics");return new Eh({exporter:new nP({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function jc(e,t){let n=new URL(e),r=n.pathname.endsWith("/")?n.pathname.slice(0,-1):n.pathname;return n.pathname=r.endsWith(t)?r:`${r}${t}`,n.toString()}import{createTool as IP,zodToJsonSchema as AP}from"@cline/shared";import{z as xt}from"zod";import{resolve as Mh}from"node:path";import{z as Y}from"zod";var Oh=Y.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),TP=Y.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),Lh=Y.union([Y.literal(0),Y.literal(1),Y.literal(2),Y.literal(3),Y.literal(4),Y.literal(5)]),wP=Y.object({provider_id:Y.string().min(1),model_id:Y.string().min(1).optional()}),Fi=Y.object({operation:Y.enum(["create","update","list","get"]),task_id:Y.string().min(1).optional(),expected_revision:Y.number().int().positive().optional(),type:Oh.optional(),title:Y.string().min(1).optional(),description:Y.string().nullable().optional(),instructions:Y.string().min(1).optional(),scope:Y.enum(["workspace","global"]).optional(),workspace_root:Y.string().min(1).nullable().optional(),cwd:Y.string().min(1).nullable().optional(),resource_paths:Y.array(Y.string().min(1)).optional(),priority:Lh.optional(),assignee:Y.string().min(1).nullable().optional(),model_selection:wP.nullable().optional(),mode:Y.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Y.string().nullable().optional(),max_iterations:Y.number().int().positive().nullable().optional(),timeout_seconds:Y.number().int().positive().nullable().optional(),available_at:Y.string().datetime().optional(),expires_at:Y.string().datetime().optional(),automation_eligible:Y.boolean().optional(),statuses:Y.array(TP).optional(),types:Y.array(Oh).optional(),priorities:Y.array(Lh).optional(),limit:Y.number().int().positive().max(500).optional()}),kP=new Set(["create","update"]);function qc(e,t,n,r){if(!kP.has(t.operation))return;dn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.todo.${t.operation}`,success:r,agentId:n.agentId})}function Or(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Nh(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function Hh(e,t){return Mh(e)===Mh(t)}function Dh(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!Hh(e.workspaceRoot,t.workspaceRoot))throw Error("task is outside this session's workspace scope");return}if(e.scope!=="global")throw Error("task is outside this session's global scope")}function CP(e,t){let n=t.workspaceRoot?"workspace":"global";if(e.scope&&e.scope!==n)throw Error(`this session can only manage ${n} tasks`);if(e.workspace_root!==void 0){if(!t.workspaceRoot||e.workspace_root===null||!Hh(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function Uh(e,t,n){let r=Fi.safeParse(t);if(!r.success)return{ok:!1,error:{code:"invalid_task_input",message:r.error.issues[0]?.message??"Invalid task input"}};let o=r.data,s={kind:"agent",id:n.agentId,agentId:n.agentId,sessionId:n.sessionId};try{if(!n.sessionId)throw Error("tasks requires a Hub session");let i=await e.resolveSessionDefaults(n.sessionId);if(!i)throw Error("tasks could not resolve the current session");let a=CP(o,i);switch(o.operation){case"create":{let d={type:Or(o.type,"type"),title:Or(o.title,"title"),description:o.description??void 0,instructions:Or(o.instructions,"instructions"),scope:a,workspaceRoot:i.workspaceRoot,cwd:a==="workspace"?(o.cwd??i.cwd)?.trim()||void 0:void 0,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee??void 0,modelSelection:Nh(o.model_selection)??i.modelSelection,mode:o.mode??void 0,systemPrompt:o.system_prompt??void 0,maxIterations:o.max_iterations??void 0,timeoutSeconds:o.timeout_seconds??void 0,availableAt:o.available_at,expiresAt:Or(o.expires_at,"expires_at"),automationEligible:o.automation_eligible,createdBy:s,originSessionId:n.sessionId,originTaskId:i.originTaskId},c={ok:!0,operation:o.operation,task:await e.manager.createTask(d)};return qc(e,o,n,!0),c}case"update":{let d=Or(o.task_id,"task_id");if(Dh(await e.manager.getTask(d),i),!o.expected_revision)throw Error("expected_revision is required for update");let c={ok:!0,operation:o.operation,task:await e.manager.updateTask({taskId:d,expectedRevision:o.expected_revision,type:o.type,title:o.title,description:o.description,instructions:o.instructions,scope:a,workspaceRoot:i.workspaceRoot??null,cwd:o.cwd,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee,modelSelection:Nh(o.model_selection),mode:o.mode,systemPrompt:o.system_prompt,maxIterations:o.max_iterations,timeoutSeconds:o.timeout_seconds,availableAt:o.available_at,expiresAt:o.expires_at,automationEligible:o.automation_eligible,updatedBy:s})};return qc(e,o,n,!0),c}case"list":{let d={statuses:o.statuses,types:o.types,scope:a,workspaceRoot:i.workspaceRoot,priorities:o.priorities,automationEligible:o.automation_eligible,limit:o.limit};return{ok:!0,operation:o.operation,tasks:await e.manager.listTasks(d)}}case"get":{let d=await e.manager.getTask(Or(o.task_id,"task_id"));return Dh(d,i),{ok:!0,operation:o.operation,task:d}}}}catch(i){return qc(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:i instanceof Error?i.message:String(i)}}}}var Wo="tasks",Fh='# Tasks\n\nUse the `tasks` tool to manage durable Todo items and explicitly requested scheduled agent work.\n\n- Use `kind: "todo"` for meaningful follow-ups, handoffs, ideas, reminders, and other work that should remain visible after this session. This includes useful work you identify and suggest proactively. Agent-created Todos require user approval; Todos created directly by the user are approved immediately. Todo `available_at` controls availability in the list; it never schedules execution.\n- Use `kind: "scheduled"` only when the user explicitly asks Cline to execute work once at a future time or on a recurrence. One-time schedules require an exact future ISO 8601 `run_at` with an offset or Z. Recurring schedules require a five-field `cron_pattern` and default to the local timezone. Omit `timezone` unless the user explicitly requests a different timezone; never guess EST, UTC, or another zone. When a timezone is requested, use its IANA name (for example, America/New_York) so daylight-saving changes are handled.\n- "Remind me" is ambiguous: ask whether the user wants a reviewed Todo note or an agent to execute work at that time when intent is unclear.\n- Never create both kinds for the same request unless the user explicitly requests both. Check existing items before creating a likely duplicate.\n- Todo instructions and scheduled prompts must be self-contained. Include the goal, constraints, relevant project context, and expected output.\n- Scheduled sessions run in the user\'s schedules home workspace, not this conversation\'s folder. Include absolute paths in the scheduled `prompt` for any project files or repositories the work must touch.\n- Never approve or start a Todo yourself. Only mutate schedules from an interactive user session, and only update, pause, resume, delete, or run one immediately when the user asks.',RP="# Tasks\n\nUse the `tasks` tool only when the user explicitly asks Cline to execute work once at a future time or on a recurrence. Always pass `kind: \"scheduled\"`.\n\n- One-time schedules require an exact future ISO 8601 `run_at` with an offset or Z. Recurring schedules require a five-field `cron_pattern` and default to the local timezone. Omit `timezone` unless the user explicitly requests a different timezone; never guess EST, UTC, or another zone. When a timezone is requested, use its IANA name (for example, America/New_York) so daylight-saving changes are handled.\n- Never create a schedule proactively. Check existing schedules before creating a likely duplicate.\n- Make the scheduled `prompt` self-contained because it runs in a new unattended session in the user's schedules home workspace, not this conversation's folder. Include the goal, constraints, expected output, and absolute paths for any project files or repositories the work must touch.\n- Only update, pause, resume, delete, or run a schedule immediately when the user asks for that action.",EP=Fi.extend({kind:xt.literal("todo")}).strict(),Bh=Mr.extend({kind:xt.literal("scheduled")}).strict(),$h=xt.discriminatedUnion("kind",[EP,Bh]),PP=xt.discriminatedUnion("kind",[Bh]),Wh=["create","update","list","get","pause","resume","delete","run_now"],_P=xt.object({...Mr.shape,...Fi.shape,kind:xt.enum(["todo","scheduled"]),operation:xt.enum(Wh)}).strict(),xP=xt.object({...Mr.shape,kind:xt.enum(["scheduled"]),operation:xt.enum(Wh)}).strict();function zc(e){let t=e.todo;return IP({name:Wo,description:t?'Create and manage reviewed Todo items or explicitly requested scheduled agent work. Use kind "todo" for durable Agenda items that require user or automation approval. Use kind "scheduled" for one-time or recurring autonomous execution. Todo available_at is not an execution timer; schedules use run_at or cron_pattern.':'Create and manage explicitly requested scheduled agent work with kind "scheduled". One-time schedules use a future ISO 8601 run_at; recurring schedules use a five-field cron_pattern.',inputSchema:AP(t?_P:xP),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?$h:PP).safeParse(n);if(!o.success)return{ok:!1,kind:typeof n==="object"&&n!==null&&"kind"in n&&(n.kind==="todo"||n.kind==="scheduled")?n.kind:void 0,error:{code:"invalid_tasks_input",message:o.error.issues[0]?.message??"Invalid tasks input"}};if(o.data.kind==="todo"){if(!t)return{ok:!1,kind:"todo",error:{code:"invalid_tasks_input",message:'kind "todo" is not available in this session'}};return{kind:"todo",...await Uh(t,o.data,r)}}return{kind:"scheduled",...await Dc(e.scheduled,o.data,r)}}})}function Kc(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?RP:Fh,whenToolAvailable:Wo})}}}import{createSessionId as q_,ensureLoopbackProxyBypass as gy,isHubProtocolCompatible as z_,resolveClineBuildEnv as K_,resolveHubCommandTimeoutMs as G_}from"@cline/shared";import V_ from"ws";var Bi="0.0.88-nightly.1790735522";var ln={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Bi,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 $i="session_not_found";class Lr 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"}}function Wi(e){return e instanceof Lr||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as l_}from"node:child_process";import{closeSync as p_,mkdirSync as m_,openSync as g_,readFileSync as f_,unlinkSync as h_}from"node:fs";import{basename as y_,dirname as S_,join as b_}from"node:path";import{fileURLToPath as v_}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as T_,isBunEmbeddedModulePath as w_,isHubDaemonProcess as ay,resolveClineBuildEnv as dy,withResolvedClineBuildEnv as k_}from"@cline/shared";import{createHash as MP,randomBytes as Xh}from"node:crypto";import{existsSync as OP}from"node:fs";import{mkdir as Vc,open as qh,readFile as Jh,rename as LP,rm as ji,writeFile as NP}from"node:fs/promises";import{dirname as Yh,join as Xc}from"node:path";import{ensureLoopbackProxyBypass as DP,isHubProtocolCompatible as HP}from"@cline/shared";import{resolveClineDataDir as jo,resolveClineDir as iJ}from"@cline/shared/storage";var UP="CLINE_HUB_DISCOVERY_PATH",FP="CLINE_HUB_BUILD_ID",BP="CLINE_HUB_BUILD_EPOCH_MS",$P=30000,WP=15000,zh=100;function jP(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function qP(e){return MP("sha256").update(e).digest("hex").slice(0,12)}function zP(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 Qh(){return Xh(32).toString("hex")}function Kh(e){return new Promise((t)=>setTimeout(t,e))}function KP(e){return`${e}.lock`}async function GP(e){try{let t=JSON.parse(await Jh(Xc(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 Gc(e){await ji(e,{recursive:!0,force:!0}).catch(()=>{return})}function Mt(){let e=process.env[FP]?.trim();if(e)return e;return"sdk-v1-0982e787428525296f7c82ef42aff77c3cee5087192bf30b19f8018599e7f0ab".trim()||`source-${String(ln.version)}`}function Jc(){let e=Number(process.env[BP]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735549231)?1790735549231:void 0}function Hn(e,t=Mt()){let n=HP(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 Gh(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function Vh(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 VP(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 qo(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=Gh(e.buildEpochMs),s=Gh(t.buildEpochMs);if(o!==void 0&&s!==void 0&&o!==s)return o<s?-1:1;let i=Vh(e.coreVersion),a=Vh(t.coreVersion);if(i&&a){let d=VP(i,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function zo(){return{buildId:Mt(),buildEpochMs:Jc(),coreVersion:String(ln.version)}}function Nr(e,t){let n=t?.self??zo(),r=Hn(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return qo(n,e)<=0}function Un(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${qP(e)}`,n=process.env[UP]?.trim()||Xc(jo(),"locks","hub","owners",`${jP(t)}.json`);return{ownerId:t,discoveryPath:n}}function dJ(e=`hub-${Date.now().toString(36)}`){return Un(e)}async function Re(e){try{let t=JSON.parse(await Jh(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 qi(e,t){await Yc(e,async()=>{let n=Yh(e);await Vc(n,{recursive:!0});let r=`${e}.${process.pid}.${Xh(6).toString("hex")}.tmp`,o;try{o=await qh(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
310
+ `,"utf8"),OE()}function gh(){return at().telemetryOptOut}function Nn(e){return new Set(e??at().disabledTools??[])}function fh(e){return new Set(e??at().disabledPlugins??[])}function Bo(e){return new Set(e??at().disabledAgentPlugins??[])}function hh(e){return lh.includes(e)}function DE(){let e=mh();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function Fc(e){return DE()[e]?.enabled===!0}function HE(e,t){let n=at();Fo({...n,tools:{...n.tools,[e]:{enabled:t}}})}function yh(e){if(hh(e)){let o=Fc(e);return HE(e,!o),o}let t=at(),n=new Set(t.disabledTools??[]),r=n.has(e);if(r)n.delete(e);else n.add(e);return Fo({...t,disabledTools:[...n]}),!r}function UE(e,t){let n=[...new Set(e.map((i)=>i.trim()).filter(Boolean))];if(n.length===0)return;let r=at(),o=Nn(r.disabledTools),s={...r.tools};for(let i of n){if(hh(i)){s[i]={enabled:!t};continue}if(t)o.add(i);else o.delete(i)}Fo({...r,disabledTools:[...o],tools:s})}function Sh(e,t){return UE([e],t),t}function bh(e,t){let n=e.trim();if(!n)return;let r=at(),o=fh(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Fo({...r,disabledPlugins:[...o]})}function vh(e,t){let n=e.trim();if(!n)return;let r=at(),o=Bo(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Fo({...r,disabledAgentPlugins:[...o]})}function Th(e,t){let n=fh(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r))}function Dn(e,t){let n=Nn(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r.name))}function wh(e,t){if(!e||e.length===0)return e;let n=Nn(t);if(n.size===0)return e;return e.map((r)=>{if(!r.setup)return r;return{...r,setup:(o,s)=>r.setup?.({...o,registerTool:(i)=>{if(!n.has(i.name))o.registerTool(i)}},s)}})}import{existsSync as FE,mkdirSync as BE,readFileSync as $E,writeFileSync as WE}from"node:fs";import{resolve as jE}from"node:path";import{resolveSessionDataDir as qE}from"@cline/shared/storage";import{nanoid as zE}from"nanoid";import*as KE from"node-machine-id";var GE="machine-id",kh,Ch=!1;function Ih(){if(!Ch)kh=Ah(),Ch=!0;return kh??Rh()}function $o(e){let t=e?.trim();if(t)return t;let n=Ah();if(n)return n;return Rh()}function VE(){let e=KE;return e.machineIdSync??e.default?.machineIdSync}function Ah(){try{let e=VE();if(!e)return;return e().trim()||void 0}catch{return}}function Rh(){let e=qE(),t=jE(e,GE);try{if(FE(t)){let r=$E(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${zE()}`;try{BE(e,{recursive:!0}),WE(t,n,"utf8")}catch{}return n}class Bc{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(e){this.name=e.name??"OpenTelemetryAdapter",this.metadata={...e.metadata},this.meterProvider=e.meterProvider,this.loggerProvider=e.loggerProvider,this.meter=e.meterProvider?.getMeter("cline")??null,this.logger=e.loggerProvider?.getLogger("cline")??null,this.enabled=e.enabled??!0,this.distinctId=e.distinctId,this.commonProperties=e.commonProperties?{...e.commonProperties}:{}}emit(e,t){if(!this.isEnabled())return;this.emitLog(e,t,!1)}emitRequired(e,t){this.emitLog(e,t,!0)}recordCounter(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.counters.get(e);if(!s)s=this.meter.createCounter(e,r?{description:r}:void 0),this.counters.set(e,s);s.add(t,this.flattenProperties(this.buildAttributes(n)))}recordHistogram(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.histograms.get(e);if(!s)s=this.meter.createHistogram(e,r?{description:r}:void 0),this.histograms.set(e,s);s.record(t,this.flattenProperties(this.buildAttributes(n)))}recordGauge(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.buildAttributes(n),i=JSON.stringify(s),a=this.gaugeValues.get(e);if(t===null){if(a){if(a.delete(i),a.size===0)this.gaugeValues.delete(e),this.gauges.delete(e)}return}let d=a;if(!d)d=new Map,this.gaugeValues.set(e,d);if(!this.gauges.has(e)){let c=this.meter.createObservableGauge(e,r?{description:r}:void 0);c.addCallback((u)=>{for(let l of this.snapshotGaugeSeries(e))u.observe(l.value,this.flattenProperties(l.attributes))}),this.gauges.set(e,c)}d.set(i,{value:t,attributes:s})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(e){this.distinctId=e}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(e,t,n){if(!this.logger)return;let r=this.flattenProperties(this.buildAttributes(t,n));this.logger.emit({severityText:"INFO",body:e,attributes:r})}buildAttributes(e,t=!1){return{...this.commonProperties,...this.metadata,...e,...this.distinctId?{distinct_id:this.distinctId}:{},...t?{_required:!0}:{}}}snapshotGaugeSeries(e){let t=this.gaugeValues.get(e);if(!t)return[];return Array.from(t.values(),(n)=>({value:n.value,attributes:n.attributes?{...n.attributes}:void 0}))}flattenProperties(e,t="",n=new WeakSet,r=0){if(!e)return{};let o={},s=100,i=10;for(let[a,d]of Object.entries(e)){if(a==="__proto__"||a==="constructor"||a==="prototype")continue;let c=t?`${t}.${a}`:a;if(d===null||d===void 0){o[c]=String(d);continue}if(Array.isArray(d)){let u=d.length>s?d.slice(0,s):d;try{o[c]=JSON.stringify(u)}catch{o[c]="[UnserializableArray]"}if(d.length>s)o[`${c}_truncated`]=!0,o[`${c}_original_length`]=d.length;continue}if(typeof d==="object"){if(d instanceof Date){o[c]=d.toISOString();continue}if(d instanceof Error){o[c]=d.message;continue}if(n.has(d)){o[c]="[Circular]";continue}if(r>=i){o[c]="[MaxDepthExceeded]";continue}n.add(d),Object.assign(o,this.flattenProperties(d,c,n,r+1));continue}if(XE(d)){o[c]=d;continue}try{o[c]=JSON.stringify(d)}catch{o[c]=String(d)}}return o}}function XE(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class $c{name;logger;enabled;constructor(e={}){this.name=e.name??"TelemetryLoggerSink",this.logger=e.logger,this.enabled=e.enabled??!0}emit(e,t){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:e,properties:t})}emitRequired(e,t){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:e,properties:t})}recordCounter(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:e,value:t,attributes:n,description:r,required:o===!0})}recordHistogram(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:e,value:t,attributes:n,description:r,required:o===!0})}recordGauge(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:e,value:t,attributes:n,description:r,required:o===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class Ui{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new $c({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??Ih(),this.commonProperties={...e.commonProperties??{}}}addAdapter(e){this.adapters.push(e)}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return this.adapters.some((e)=>e.isEnabled())}capture(e){let t=this.buildAttributes(e.properties);for(let n of this.adapters)n.emit(e.event,t)}captureRequired(e,t){let n=this.buildAttributes(t);for(let r of this.adapters)r.emitRequired(e,n)}recordCounter(e,t,n,r,o=!1){let s=this.buildAttributes(n);for(let i of this.adapters)i.recordCounter(e,t,s,r,o)}recordHistogram(e,t,n,r,o=!1){let s=this.buildAttributes(n);for(let i of this.adapters)i.recordHistogram(e,t,s,r,o)}recordGauge(e,t,n,r,o=!1){let s=this.buildAttributes(n);for(let i of this.adapters)i.recordGauge(e,t,s,r,o)}async flush(){await Promise.all(this.adapters.map((e)=>e.flush()))}async dispose(){await Promise.all(this.adapters.map((e)=>e.dispose()))}buildAttributes(e){let t=typeof e?.distinct_id==="string"&&e.distinct_id.trim()?e.distinct_id.trim():this.distinctId,n={...this.commonProperties,...this.metadata,...e,...t?{distinct_id:t}:{},device_id:this.deviceId};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}}class Ph{distinctId;metadata;commonProperties;constructor(e={}){this.distinctId=e.distinctId,this.metadata={...e.metadata??{}},this.commonProperties={...e.commonProperties??{}}}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return!1}capture(e){this.resolveProperties(e.properties)}captureRequired(e,t){this.resolveProperties(t)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(e){let t=typeof e?.distinct_id==="string"&&e.distinct_id.trim()?e.distinct_id.trim():this.distinctId,n={...this.commonProperties,...this.metadata,...e,...t?{distinct_id:t}:{}};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}}class _h{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=oP({[gP]:e.serviceName??"cline",...e.serviceVersion?{[fP]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)QE.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)eP.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return ZE.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new Bc({...e,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(e){let t=this.createAdapter({name:e.name,enabled:this.options.enabled,metadata:e.metadata});return new Ui({...e,adapters:[t],distinctId:$o(e.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(e){let t=Wc(this.options.metricsExporter);if(t.length===0)return null;let n=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),r=Math.min(30000,Math.floor(n*0.8)),o=t.map((s)=>vP(s,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:n,timeout:r})).filter((s)=>s!==null);if(o.length===0)return null;return new cP({resource:e,readers:o})}createTracerProvider(e){let t=Wc(this.options.tracesExporter);if(t.length===0)return null;let n=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,r=this.options.otlpTracesHeaders??this.options.otlpHeaders,o=[],s=!1;for(let a of t){let d=bP(a,{endpoint:n,headers:r,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(d){if(o.push(d),a!=="console")s=!0}}if(o.length===0)return null;let i=new mP({resource:e,spanProcessors:s?[new JE,...o]:o});if(s)YE(i);return i}createLoggerProvider(e){let t=Wc(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=SP(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new sP(o,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((r)=>r!==null);if(n.length===0)return null;return new aP({resource:e,processors:n})}}function hP(e){let t=new _h(e),n=t.createTelemetryService(e),r=()=>{n.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:e.enabled??!0,logsExporter:Array.isArray(e.logsExporter)?e.logsExporter.join(","):e.logsExporter,metricsExporter:Array.isArray(e.metricsExporter)?e.metricsExporter.join(","):e.metricsExporter,tracesExporter:Array.isArray(e.tracesExporter)?e.tracesExporter.join(","):e.tracesExporter,otlpProtocol:e.otlpProtocol,hasOtlpEndpoint:Boolean(e.otlpEndpoint),serviceName:e.serviceName,serviceVersion:e.serviceVersion})};if(!e.deferProviderCreatedEvent)r();return{provider:t,telemetry:n,emitProviderCreated:r}}function xh(e){if(gh())return{telemetry:new Ph(e)};if(e.enabled!==!0)return{telemetry:new Ui({...e,distinctId:$o(e.distinctId)})};return hP(e)}function yP(e){let{telemetry:t,provider:n,emitProviderCreated:r}=xh(e);return{telemetry:t,provider:n,flush:async()=>{let i=n;if(i&&typeof i.forceFlush==="function")try{await i.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([t.dispose(),n?.dispose()])},...e.deferProviderCreatedEvent&&r?{emitProviderCreated:r}:{}}}function Wc(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function SP(e,t){if(e==="console")return new iP;if(!t.endpoint)return null;let n=jc(t.endpoint,"/v1/logs");return new tP({url:n,headers:t.headers})}function bP(e,t){if(e==="console")return new pP(new lP);if(!t.endpoint)return null;let n=jc(t.endpoint,"/v1/traces");return new uP(new rP({url:n,headers:t.headers}))}function vP(e,t){if(e==="console")return new Eh({exporter:new dP,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=jc(t.endpoint,"/v1/metrics");return new Eh({exporter:new nP({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function jc(e,t){let n=new URL(e),r=n.pathname.endsWith("/")?n.pathname.slice(0,-1):n.pathname;return n.pathname=r.endsWith(t)?r:`${r}${t}`,n.toString()}import{createTool as IP,zodToJsonSchema as AP}from"@cline/shared";import{z as xt}from"zod";import{resolve as Mh}from"node:path";import{z as Y}from"zod";var Oh=Y.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),TP=Y.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),Lh=Y.union([Y.literal(0),Y.literal(1),Y.literal(2),Y.literal(3),Y.literal(4),Y.literal(5)]),wP=Y.object({provider_id:Y.string().min(1),model_id:Y.string().min(1).optional()}),Fi=Y.object({operation:Y.enum(["create","update","list","get"]),task_id:Y.string().min(1).optional(),expected_revision:Y.number().int().positive().optional(),type:Oh.optional(),title:Y.string().min(1).optional(),description:Y.string().nullable().optional(),instructions:Y.string().min(1).optional(),scope:Y.enum(["workspace","global"]).optional(),workspace_root:Y.string().min(1).nullable().optional(),cwd:Y.string().min(1).nullable().optional(),resource_paths:Y.array(Y.string().min(1)).optional(),priority:Lh.optional(),assignee:Y.string().min(1).nullable().optional(),model_selection:wP.nullable().optional(),mode:Y.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Y.string().nullable().optional(),max_iterations:Y.number().int().positive().nullable().optional(),timeout_seconds:Y.number().int().positive().nullable().optional(),available_at:Y.string().datetime().optional(),expires_at:Y.string().datetime().optional(),automation_eligible:Y.boolean().optional(),statuses:Y.array(TP).optional(),types:Y.array(Oh).optional(),priorities:Y.array(Lh).optional(),limit:Y.number().int().positive().max(500).optional()}),kP=new Set(["create","update"]);function qc(e,t,n,r){if(!kP.has(t.operation))return;dn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.todo.${t.operation}`,success:r,agentId:n.agentId})}function Or(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Nh(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function Hh(e,t){return Mh(e)===Mh(t)}function Dh(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!Hh(e.workspaceRoot,t.workspaceRoot))throw Error("task is outside this session's workspace scope");return}if(e.scope!=="global")throw Error("task is outside this session's global scope")}function CP(e,t){let n=t.workspaceRoot?"workspace":"global";if(e.scope&&e.scope!==n)throw Error(`this session can only manage ${n} tasks`);if(e.workspace_root!==void 0){if(!t.workspaceRoot||e.workspace_root===null||!Hh(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function Uh(e,t,n){let r=Fi.safeParse(t);if(!r.success)return{ok:!1,error:{code:"invalid_task_input",message:r.error.issues[0]?.message??"Invalid task input"}};let o=r.data,s={kind:"agent",id:n.agentId,agentId:n.agentId,sessionId:n.sessionId};try{if(!n.sessionId)throw Error("tasks requires a Hub session");let i=await e.resolveSessionDefaults(n.sessionId);if(!i)throw Error("tasks could not resolve the current session");let a=CP(o,i);switch(o.operation){case"create":{let d={type:Or(o.type,"type"),title:Or(o.title,"title"),description:o.description??void 0,instructions:Or(o.instructions,"instructions"),scope:a,workspaceRoot:i.workspaceRoot,cwd:a==="workspace"?(o.cwd??i.cwd)?.trim()||void 0:void 0,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee??void 0,modelSelection:Nh(o.model_selection)??i.modelSelection,mode:o.mode??void 0,systemPrompt:o.system_prompt??void 0,maxIterations:o.max_iterations??void 0,timeoutSeconds:o.timeout_seconds??void 0,availableAt:o.available_at,expiresAt:Or(o.expires_at,"expires_at"),automationEligible:o.automation_eligible,createdBy:s,originSessionId:n.sessionId,originTaskId:i.originTaskId},c={ok:!0,operation:o.operation,task:await e.manager.createTask(d)};return qc(e,o,n,!0),c}case"update":{let d=Or(o.task_id,"task_id");if(Dh(await e.manager.getTask(d),i),!o.expected_revision)throw Error("expected_revision is required for update");let c={ok:!0,operation:o.operation,task:await e.manager.updateTask({taskId:d,expectedRevision:o.expected_revision,type:o.type,title:o.title,description:o.description,instructions:o.instructions,scope:a,workspaceRoot:i.workspaceRoot??null,cwd:o.cwd,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee,modelSelection:Nh(o.model_selection),mode:o.mode,systemPrompt:o.system_prompt,maxIterations:o.max_iterations,timeoutSeconds:o.timeout_seconds,availableAt:o.available_at,expiresAt:o.expires_at,automationEligible:o.automation_eligible,updatedBy:s})};return qc(e,o,n,!0),c}case"list":{let d={statuses:o.statuses,types:o.types,scope:a,workspaceRoot:i.workspaceRoot,priorities:o.priorities,automationEligible:o.automation_eligible,limit:o.limit};return{ok:!0,operation:o.operation,tasks:await e.manager.listTasks(d)}}case"get":{let d=await e.manager.getTask(Or(o.task_id,"task_id"));return Dh(d,i),{ok:!0,operation:o.operation,task:d}}}}catch(i){return qc(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:i instanceof Error?i.message:String(i)}}}}var Wo="tasks",Fh='# Tasks\n\nUse the `tasks` tool to manage durable Todo items and explicitly requested scheduled agent work.\n\n- Use `kind: "todo"` for meaningful follow-ups, handoffs, ideas, reminders, and other work that should remain visible after this session. This includes useful work you identify and suggest proactively. Agent-created Todos require user approval; Todos created directly by the user are approved immediately. Todo `available_at` controls availability in the list; it never schedules execution.\n- Use `kind: "scheduled"` only when the user explicitly asks Cline to execute work once at a future time or on a recurrence. One-time schedules require an exact future ISO 8601 `run_at` with an offset or Z. Recurring schedules require a five-field `cron_pattern` and default to the local timezone. Omit `timezone` unless the user explicitly requests a different timezone; never guess EST, UTC, or another zone. When a timezone is requested, use its IANA name (for example, America/New_York) so daylight-saving changes are handled.\n- "Remind me" is ambiguous: ask whether the user wants a reviewed Todo note or an agent to execute work at that time when intent is unclear.\n- Never create both kinds for the same request unless the user explicitly requests both. Check existing items before creating a likely duplicate.\n- Todo instructions and scheduled prompts must be self-contained. Include the goal, constraints, relevant project context, and expected output.\n- Scheduled sessions run in the user\'s schedules home workspace, not this conversation\'s folder. Include absolute paths in the scheduled `prompt` for any project files or repositories the work must touch.\n- Never approve or start a Todo yourself. Only mutate schedules from an interactive user session, and only update, pause, resume, delete, or run one immediately when the user asks.',RP="# Tasks\n\nUse the `tasks` tool only when the user explicitly asks Cline to execute work once at a future time or on a recurrence. Always pass `kind: \"scheduled\"`.\n\n- One-time schedules require an exact future ISO 8601 `run_at` with an offset or Z. Recurring schedules require a five-field `cron_pattern` and default to the local timezone. Omit `timezone` unless the user explicitly requests a different timezone; never guess EST, UTC, or another zone. When a timezone is requested, use its IANA name (for example, America/New_York) so daylight-saving changes are handled.\n- Never create a schedule proactively. Check existing schedules before creating a likely duplicate.\n- Make the scheduled `prompt` self-contained because it runs in a new unattended session in the user's schedules home workspace, not this conversation's folder. Include the goal, constraints, expected output, and absolute paths for any project files or repositories the work must touch.\n- Only update, pause, resume, delete, or run a schedule immediately when the user asks for that action.",EP=Fi.extend({kind:xt.literal("todo")}).strict(),Bh=Mr.extend({kind:xt.literal("scheduled")}).strict(),$h=xt.discriminatedUnion("kind",[EP,Bh]),PP=xt.discriminatedUnion("kind",[Bh]),Wh=["create","update","list","get","pause","resume","delete","run_now"],_P=xt.object({...Mr.shape,...Fi.shape,kind:xt.enum(["todo","scheduled"]),operation:xt.enum(Wh)}).strict(),xP=xt.object({...Mr.shape,kind:xt.enum(["scheduled"]),operation:xt.enum(Wh)}).strict();function zc(e){let t=e.todo;return IP({name:Wo,description:t?'Create and manage reviewed Todo items or explicitly requested scheduled agent work. Use kind "todo" for durable Agenda items that require user or automation approval. Use kind "scheduled" for one-time or recurring autonomous execution. Todo available_at is not an execution timer; schedules use run_at or cron_pattern.':'Create and manage explicitly requested scheduled agent work with kind "scheduled". One-time schedules use a future ISO 8601 run_at; recurring schedules use a five-field cron_pattern.',inputSchema:AP(t?_P:xP),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?$h:PP).safeParse(n);if(!o.success)return{ok:!1,kind:typeof n==="object"&&n!==null&&"kind"in n&&(n.kind==="todo"||n.kind==="scheduled")?n.kind:void 0,error:{code:"invalid_tasks_input",message:o.error.issues[0]?.message??"Invalid tasks input"}};if(o.data.kind==="todo"){if(!t)return{ok:!1,kind:"todo",error:{code:"invalid_tasks_input",message:'kind "todo" is not available in this session'}};return{kind:"todo",...await Uh(t,o.data,r)}}return{kind:"scheduled",...await Dc(e.scheduled,o.data,r)}}})}function Kc(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?RP:Fh,whenToolAvailable:Wo})}}}import{createSessionId as q_,ensureLoopbackProxyBypass as gy,isHubProtocolCompatible as z_,resolveClineBuildEnv as K_,resolveHubCommandTimeoutMs as G_}from"@cline/shared";import V_ from"ws";var Bi="0.0.88";var ln={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Bi,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 $i="session_not_found";class Lr 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"}}function Wi(e){return e instanceof Lr||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as l_}from"node:child_process";import{closeSync as p_,mkdirSync as m_,openSync as g_,readFileSync as f_,unlinkSync as h_}from"node:fs";import{basename as y_,dirname as S_,join as b_}from"node:path";import{fileURLToPath as v_}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as T_,isBunEmbeddedModulePath as w_,isHubDaemonProcess as ay,resolveClineBuildEnv as dy,withResolvedClineBuildEnv as k_}from"@cline/shared";import{createHash as MP,randomBytes as Xh}from"node:crypto";import{existsSync as OP}from"node:fs";import{mkdir as Vc,open as qh,readFile as Jh,rename as LP,rm as ji,writeFile as NP}from"node:fs/promises";import{dirname as Yh,join as Xc}from"node:path";import{ensureLoopbackProxyBypass as DP,isHubProtocolCompatible as HP}from"@cline/shared";import{resolveClineDataDir as jo,resolveClineDir as i2}from"@cline/shared/storage";var UP="CLINE_HUB_DISCOVERY_PATH",FP="CLINE_HUB_BUILD_ID",BP="CLINE_HUB_BUILD_EPOCH_MS",$P=30000,WP=15000,zh=100;function jP(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function qP(e){return MP("sha256").update(e).digest("hex").slice(0,12)}function zP(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 Qh(){return Xh(32).toString("hex")}function Kh(e){return new Promise((t)=>setTimeout(t,e))}function KP(e){return`${e}.lock`}async function GP(e){try{let t=JSON.parse(await Jh(Xc(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 Gc(e){await ji(e,{recursive:!0,force:!0}).catch(()=>{return})}function Mt(){let e=process.env[FP]?.trim();if(e)return e;return"sdk-v1-814d0cfa563d6988b7812b459881e191a794af2da082cd021d824a3bcb05b043".trim()||`source-${String(ln.version)}`}function Jc(){let e=Number(process.env[BP]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735496846)?1790735496846:void 0}function Hn(e,t=Mt()){let n=HP(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 Gh(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function Vh(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 VP(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 qo(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=Gh(e.buildEpochMs),s=Gh(t.buildEpochMs);if(o!==void 0&&s!==void 0&&o!==s)return o<s?-1:1;let i=Vh(e.coreVersion),a=Vh(t.coreVersion);if(i&&a){let d=VP(i,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function zo(){return{buildId:Mt(),buildEpochMs:Jc(),coreVersion:String(ln.version)}}function Nr(e,t){let n=t?.self??zo(),r=Hn(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return qo(n,e)<=0}function Un(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${qP(e)}`,n=process.env[UP]?.trim()||Xc(jo(),"locks","hub","owners",`${jP(t)}.json`);return{ownerId:t,discoveryPath:n}}function d2(e=`hub-${Date.now().toString(36)}`){return Un(e)}async function Re(e){try{let t=JSON.parse(await Jh(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 qi(e,t){await Yc(e,async()=>{let n=Yh(e);await Vc(n,{recursive:!0});let r=`${e}.${process.pid}.${Xh(6).toString("hex")}.tmp`,o;try{o=await qh(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
311
311
  `,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await LP(r,e);let s;try{s=await qh(n,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await o?.close().catch(()=>{return}),await ji(r,{force:!0}).catch(()=>{return}),s}})}async function Gt(e){await Yc(e,async()=>{await ji(e,{force:!0}).catch(()=>{return})})}async function Zh(e,t){return await Yc(e,async()=>{if((await Re(e))?.hubId!==t)return!1;return await ji(e,{force:!0}),!0})}async function ey(e,t,n){let r=KP(e);await Vc(Yh(r),{recursive:!0});let o=Date.now()+WP;while(!0){try{await Vc(r,{recursive:!1})}catch(s){if((s instanceof Error&&"code"in s?String(s.code):"")!=="EEXIST")throw s;let a=await GP(r);if(!a){if(Date.now()>=o){await Gc(r);continue}await Kh(zh);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!zP(a.pid)||d>$P){await Gc(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await Kh(zh);continue}try{return await NP(Xc(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
312
- `,"utf8"),await n()}finally{await Gc(r)}}}function Yc(e,t){return ey(`${e}.mutation`,"discovery mutation",t)}function zi(e,t){return ey(e,"startup",t)}async function Vt(e,t){DP();try{let n=await fetch(t?.authToken?XP(e):ty(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 Xt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function ty(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function XP(e){let t=new URL(ty(e));return t.pathname="/status",t.toString()}function cJ(e){return OP(e)}import{CLINE_HUB_DEV_PORT as JP,CLINE_HUB_PORT as YP,resolveClineBuildEnv as QP}from"@cline/shared";var ZP="CLINE_HUB_HOST",e_="CLINE_HUB_PORT",t_="CLINE_HUB_PATHNAME",n_="127.0.0.1",r_=YP,o_="/hub";function ny(e){return QP(e)==="development"?JP:r_}function s_(e={}){return(e.env??process.env)[ZP]?.trim()||n_}function Ki(e={}){let n=(e.env??process.env)[e_]?.trim();if(!n)return ny(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return ny(e);return r}function i_(e={}){return(e.env??process.env)[t_]?.trim()||o_}function Fn(e={},t={}){return{host:e.host??s_(t),port:e.port??Ki(t),pathname:e.pathname??i_(t)}}import{join as a_}from"node:path";var d_="shared:cline",c_="CLINE_HUB_DISCOVERY_PATH",u_="hub-production";function hJ(e){let t=xn(e.trim());return Un(`workspace:${t||e.trim()}`)}function vt(e=d_){return Un(`${e}@${Mt()}`)}function Ot(){return{ownerId:u_,discoveryPath:process.env[c_]?.trim()||a_(jo(),"locks","hub","production.json")}}var ry=15000,C_=200,oy=3000,I_=100,A_=[100,250,500,1000,2000],R_="--cline-hub-daemon",E_=3,P_=60000,eu=new Map,RJ={resetRetireAttempts(){eu.clear()},resolveDaemonEntryArgs:uy};function __(e,t=Date.now()){let n=eu.get(e);if(!n||t-n.windowStartedAt>P_)return eu.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=E_}function x_(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function M_(){try{let e=b_(jo(),"logs","hub-daemon.log");return m_(S_(e),{recursive:!0}),{fd:g_(e,"a"),logPath:e}}catch{return}}function cy(){return dy()==="production"?Ot():vt()}function Ko(e){return Nr(e)}function O_(e){try{let t=JSON.parse(f_(`${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 Qc(e){try{h_(`${e}.superseded`)}catch{}}function sy(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Dr(e,t){try{return await Vt(e,{authToken:t})}catch{return}}async function iy(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Dr(e))?.url)return!0;await new Promise((o)=>setTimeout(o,I_))}return!1}async function Hr(e,t){if(!__(e.url))return!1;await Bn(e.url,e.authToken,"retired by newer install").catch(()=>!1),await nu(e.url,e.authToken).catch(()=>!1);let n=await iy(e.url,oy);if(!n&&e.pid&&L_(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await iy(e.url,oy)}if(n)await Gt(t).catch(()=>{return});return n}function L_(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function tu(e){try{return(await Fr(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function Zc(e,t){if(Ko(e))return"reusable";let n=await Bn(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await tu(e)){if(n)await Bn(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Hr(e,t);if(!r&&n)await Bn(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function N_(e){if(dy()!=="production")return;let t=vt();if(t.discoveryPath===e.discoveryPath)return;let n=await Re(t.discoveryPath);if(n?.url)await Hr(n,t.discoveryPath);else await Gt(t.discoveryPath).catch(()=>{return})}function D_(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return v_(new URL(`./entry.${e}`,import.meta.url))}function uy(e,t){if(w_(e))return[R_];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function H_(e,t){let n=D_(),r=process.execPath?.trim();if(!r)throw Error("unable to resolve runtime executable for hub daemon");let o=y_(r).toLowerCase().includes("bun"),s=uy(n,o);return{launcher:r,args:[...s,"--cwd",e,...x_(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...k_(process.env),CLINE_NO_INTERACTIVE:"1",[T_]:"1"}}}function U_(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 F_(e,t={}){if(ay())return;let n=H_(e,t),r=M_();try{l_(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)p_(r.fd)}}async function B_(e,t={}){for(let n=0;;n++)try{F_(e,t);return}catch(r){let o=A_[n];if(!U_(r)||o===void 0)throw r;await new Promise((s)=>setTimeout(s,o))}}function EJ(e,t={}){if(ay())return;Go(e,t).catch(()=>{})}async function $_(e,t,n={}){let r=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Fn(n),s=Xt(o.host,o.port,o.pathname),i=(g)=>{if(!r)Ur(g.url,g.authToken);return g};await N_(e).catch(()=>{return});let a=await Re(e.discoveryPath),d=a?.url?void 0:O_(e.discoveryPath),c=!1;if(a?.url){let g=a.authToken;if(!g)c=!0,await Hr(a,e.discoveryPath);else{let f=await Dr(a.url,g);if(f?.url&&Ko(f)&&await dt(f.url,{authToken:g}))return Qc(e.discoveryPath),i({url:f.url,authToken:g});if(f?.url){if(await Zc({...f,authToken:g},e.discoveryPath)==="deferred_busy"&&await dt(f.url,{authToken:g}))return i({url:f.url,authToken:g})}else await Gt(e.discoveryPath).catch(()=>{return})}}let u=await Dr(s);if(u?.url){let g=sy(u,a??d,s);if(Ko(u)){let h=[u.authToken,a?.authToken,d?.authToken].filter((y)=>typeof y==="string"&&y.trim().length>0);for(let y of h){if(!await dt(u.url,{authToken:y}))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:y,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 qi(e.discoveryPath,b)}catch{}return Qc(e.discoveryPath),i({url:u.url,authToken:y})}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 Zc(g,e.discoveryPath);if(f==="deferred_busy"){for(let h of[g.authToken,a?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0))if(await dt(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 B_(t,{...p,manageConnectors:n.manageConnectors});let m=Date.now()+ry;while(Date.now()<m){let g=await Re(e.discoveryPath);if(g?.url&&g.authToken){let h=await Dr(g.url,g.authToken);if(h?.url&&Ko(h)&&await dt(h.url,{authToken:g.authToken}))return Qc(e.discoveryPath),i({url:h.url,authToken:g.authToken})}let f=await Dr(s);if(f?.url&&!Ko(f)){let h=sy(f,g??d,s),S=await Zc(h,e.discoveryPath);if(S==="deferred_busy"&&g?.authToken&&await dt(f.url,{authToken:g.authToken}))return i({url:f.url,authToken:g.authToken});if(S==="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,C_))}throw Error(`Timed out after ${ry}ms waiting for detached hub startup.`)}async function Go(e,t={}){let n=cy();return await zi(n.discoveryPath,async()=>$_(n,e,t))}var W_=5000,j_=500;async function PJ(e={}){let t=cy(),n=e.workspaceRoot??process.cwd(),r=await Re(t.discoveryPath),o=r?.url?await Dr(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await Go(n)};let s={...o,authToken:o.authToken??r?.authToken,pid:o.pid??r?.pid};if(Hn(o).compatible)return{outcome:"already_current",url:o.url,authToken:s.authToken};if(qo(zo(),o)<=0)return{outcome:"hub_not_older",url:o.url,authToken:s.authToken};if(!await Bn(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 Bn(s.url,s.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},d=Date.now()+(e.waitForIdleMs??W_),c;for(;;){try{if(c=(await Fr(s.url,s.authToken)).activeSessionCount,c===0)break}catch{}if(Date.now()>=d)break;await new Promise((p)=>setTimeout(p,j_))}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 Hr(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 Go(n),activeSessionCount:c??0}}function du(){return K_()==="production"?Ot():vt()}function X_(){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 fy(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 fy(e.data);return String(e)}function J_(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 ly(e){let t=e,n=J_(t.reason);return new Oe("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:ou,{closeCode:t.code,closeReason:n||void 0})}function py(e,t){if(e instanceof Oe)return e;if(e instanceof Error)return new Oe("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new Oe("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 Oe("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new Oe("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 ru="*",Gi=8000,Y_="cline-hub-auth.",hy=new Map,yy=new Set,Q_=3000,Z_=3000,ex=100,ou="Hub connection closed",tx=250,nx=5000,my=0.5;class Oe extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function rx(e){return e instanceof Oe}class Vi extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function UJ(e,t){return e instanceof Vi&&e.code==="hub_command_timeout"&&(t===void 0||e.command===t)}function cu(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let r=uu(e.toString());return r?hy.get(r):void 0}function ox(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 uu(e){if(!ox(e))return;let t=new URL(Xi(e));return t.search="",t.hash="",t.toString()}function su(e){let t=uu(e);return!!t&&yy.has(t)}function Ur(e,t){let n=uu(e);if(n){if(yy.add(n),t?.trim())hy.set(n,t)}return e}class $n{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 Oe("hub_connection_closed",ou);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()||cu(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(ln.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=py(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 Oe("hub_connect_timeout",`Timed out resolving hub connection headers after ${Gi}ms`))},Gi)})])}catch(c){let u=c instanceof Oe?c:new Oe("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 Oe("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let s=o?new V_(e.toString(),{headers:{...o}}):new(X_())(e.toString(),t?[`${Y_}${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 Oe("hub_connect_timeout",`Timed out connecting to hub after ${Gi}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)},Gi);s.addEventListener("open",()=>{if(u)return;u=!0,clearTimeout(l),d()}),s.addEventListener("error",(p)=>{if(u)return;u=!0,clearTimeout(l);let m=py(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:ly(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(fy(d)))}),s.addEventListener("close",(d)=>{if(this.socket!==s)return;if(!i)this.lastCloseError=ly(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=q_("hubreq_");r?.onDispatch?.(s);let i=G_(e,r?.timeoutMs),a=new Promise((c,u)=>{let l=i===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(s))return;u(new Vi(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===$i){let c=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Lr(c,d.error.message)}throw new Vi(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!su(this.currentUrl)||!rx(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await au({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(tx*2**this.reconnectAttempt,nx),t=Math.round(e*(1-my)+Math.random()*e*my);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(!su(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await au({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 Oe("hub_connection_closed",ou);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 Oe("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??ru}subscriptionSessionIdFromKey(e){return e===ru?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[ru,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 Xi(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 dt(e,t){let n=new $n({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 iu(e,t){let n=Xi(e),r=await Vt(n,{authToken:t?.authToken});if(!r)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=Mt(),s=Hn(r,o);if(!s.compatible&&!Nr(r))return{status:s.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!z_(r).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await dt(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}async function sx(e){let t=Date.now()+Z_;while(Date.now()<t){if(!(await Vt(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,ex))}return!1}function ix(e,t){try{return Xi(e)===Xi(t)}catch{return!1}}function Sy(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 FJ(e){return Sy(e).activeSessionCount>0}async function Fr(e,t,n){let r=new $n({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:Q_});return Sy(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function by(e,t,n){try{return(await Fr(e,t,n)).activeSessionCount===0}catch{return!1}}async function ax(e,t){let n=`${e.discoveryPath}.superseded`,r=await Re(n);if(!r?.url||!r.authToken)return;let o=await iu(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await by(o.url,r.authToken,t))return;return Ur(o.url,r.authToken)}async function dx(e={}){if(e.endpoint?.trim()){let o=await iu(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=du(),n=await Re(t.discoveryPath);if(!n?.url)return await ax(t,e);let r=await iu(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return Ur(r.url,n.authToken);if(r.status==="protocol_mismatch")await Gt(t.discoveryPath).catch(()=>{return});return}async function au(e={}){let t=await dx(e);if(t&&await dt(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Go(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function Bn(e,t,n,r){gy();let o=new URL(e),s=t?.trim()||cu(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 nu(e,t){gy();let n=new URL(e),r=t?.trim()||cu(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 cx(e=du()){let t=await Re(e.discoveryPath);if(!t?.url)return!1;try{if(await nu(t.url,t.authToken))return!0}catch{}return!1}async function BJ(e){if(!su(e.url))return;let t=du(),n=await Re(t.discoveryPath);if(!n?.url||!ix(n.url,e.url))return;if(!await by(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await cx())return;if(!await sx(n.url))return;return await Gt(t.discoveryPath).catch(()=>{return}),await au({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveClineBuildEnv as ux}from"@cline/shared";function lx(e,t){if(e instanceof Error)return e;if(e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"&&e.message.trim())return Error(e.message.trim());let n=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return Error(n?`Failed to connect to hub at ${t} (${n} event before socket open).`:`Failed to connect to hub at ${t}.`)}var px="cline-hub-auth.";function mx(e){return e.host!==void 0||e.port!==void 0||e.pathname!==void 0}function gx(e,t){let n=new URL(e),r=new URL(t);return n.search="",n.hash="",r.search="",r.hash="",n.toString()===r.toString()}function vy(){return ux()==="production"?Ot():vt()}async function fx(e){let t=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),t)return t;let n=vy(),r=await Re(n.discoveryPath);if(r?.url&&gx(e.toString(),r.url))return r.authToken;return}async function hx(e={}){let t=Fn(e);if(!mx(e)){let n=vy(),r=await Re(n.discoveryPath);if(r?.url)return r.url}return Xt(t.host,t.port,t.pathname)}async function Ty(e){return await new Promise((t,n)=>{(async()=>{let r=new URL(e),o=await fx(r);r.hash="";let s=new WebSocket(r.toString(),o?[`${px}${o}`]:void 0),i=new Map,a=0;s.addEventListener("open",()=>{t({send(d){let c=d.requestId??`hub-client-${++a}`;return new Promise((u,l)=>{i.set(c,{resolve:u,reject:l});let p={kind:"command",envelope:{...d,requestId:c}};s.send(JSON.stringify(p))})},close(){s.close()}})}),s.addEventListener("message",(d)=>{let c=JSON.parse(String(d.data));if(c.kind==="reply"&&c.envelope.requestId){let u=i.get(c.envelope.requestId);if(u)i.delete(c.envelope.requestId),u.resolve(c.envelope)}}),s.addEventListener("close",()=>{for(let d of i.values())d.reject(Error("Hub connection closed"));i.clear()}),s.addEventListener("error",(d)=>{n(lx(d,e))})})().catch(n)})}async function KJ(e){try{return(await Ty(e)).close(),!0}catch{return!1}}async function GJ(e,t){let n=await hx(e),r=await Ty(n);try{return await r.send({version:t.version??"v1",clientId:t.clientId??"hub-client",...t})}finally{r.close()}}import{existsSync as yx}from"node:fs";import{isHubDaemonProcess as Sx,resolveClineBuildEnv as bx}from"@cline/shared";var vx=1e4,Tx="CLINE_HUB_BUILD_WATCH_INTERVAL_MS";function wx(){let e=Number(process.env[Tx]);return Number.isFinite(e)&&e>0?e:vx}async function kx(e,t){try{let n=await Fr(e.url,t);return{...e,activeSessionCount:n.activeSessionCount,participantClientCount:n.participantClientCount}}catch{return e}}function Cx(){return bx()==="production"?Ot():vt()}function Ix(e){try{return yx(`${e}.lock`)}catch{return!1}}async function Ax(){let e=Cx();if(Ix(e.discoveryPath))return;let t=await Re(e.discoveryPath).catch(()=>{return});if(!t?.url)return;let n=await Vt(t.url).catch(()=>{return});if(!n?.url)return;let r=Mt(),o=Hn(n,r);if(o.compatible)return;let s=(a)=>({url:n.url,reason:a,hubBuildId:n.buildId,hubCoreVersion:n.coreVersion,expectedBuildId:r});if(o.reason==="unsupported_protocol")return s("unsupported_protocol");let i=zo();if(i.coreVersion&&n.coreVersion&&i.coreVersion===n.coreVersion)return;if(qo(i,n)>0)return await kx(s("outdated_hub"),t.authToken);return s("build_mismatch")}function eY(e){if(Sx()||process.env.CLINE_HUB_PORT?.trim())return()=>{};let t=e.intervalMs??wx(),n,r,o=!1,s=setInterval(()=>{if(o)return;o=!0,Ax().then((i)=>{if(!i){n=void 0,r=void 0;return}let a=`${i.reason}:${i.hubBuildId??""}`;if(a===n)return;if(i.reason==="outdated_hub"&&r!==a){r=a;return}r=void 0,n=a,e.onMismatch(i)}).catch(()=>{return}).finally(()=>{o=!1})},t);return s.unref?.(),()=>{clearInterval(s)}}function lu(e){return e?JSON.parse(JSON.stringify(e)):{}}function Ji(e){let t=e?.session&&typeof e.session==="object"?e.session:void 0;if(!t)return;let n=t.metadata&&typeof t.metadata==="object"?lu(t.metadata):void 0;return{sessionId:typeof t.sessionId==="string"?t.sessionId:"",parentSessionId:typeof n?.parentSessionId==="string"?n.parentSessionId:void 0,status:typeof t.status==="string"?t.status:void 0,messagesPath:typeof n?.messagesPath==="string"?n.messagesPath:void 0,metadata:n}}function wy(e,t){return e.error?.message??`hub command failed: ${t}`}function Rx(e){let t=lu(e);if(typeof t.error==="string"&&t.error.trim())return{...t,error:t.error.trim()};let n=t.result&&typeof t.result==="object"?t.result:void 0;if(typeof n?.text==="string"&&n.text.trim())return{...t,error:n.text.trim()};let r=n?.error&&typeof n.error==="object"?n.error:void 0;if(typeof r?.message==="string"&&r.message.trim())return{...t,error:r.message.trim()};return t}function ky(e){let t=e?.sessionId;return typeof t==="string"&&t.trim()?t.trim():void 0}function Ex(e){let t=e?.checkpoint;if(!t||typeof t!=="object"||Array.isArray(t))throw Error("hub checkpoint restore returned no checkpoint");let n=t;if(typeof n.ref!=="string"||typeof n.createdAt!=="number"||typeof n.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return n}function Px(e){let t=lu(e.payload);if(e.event==="schedule.execution_completed")return{sessionId:e.sessionId?.trim()||ky(t)||"",eventType:"schedule.execution.completed",payload:t};if(e.event==="schedule.execution_failed")return{sessionId:e.sessionId?.trim()||ky(t)||"",eventType:"schedule.execution.failed",payload:t};let n=e.sessionId?.trim();if(!n)return;switch(e.event){case"iteration.started":return{sessionId:n,eventType:"runtime.chat.iteration_start",payload:t};case"iteration.finished":return{sessionId:n,eventType:"runtime.chat.iteration_end",payload:t};case"assistant.delta":return{sessionId:n,eventType:"runtime.chat.text_delta",payload:t};case"assistant.media":return{sessionId:n,eventType:"runtime.chat.media",payload:t};case"usage.updated":return{sessionId:n,eventType:"runtime.chat.usage",payload:t};case"session.notice":return{sessionId:n,eventType:"runtime.chat.notice",payload:t};case"tool.started":return{sessionId:n,eventType:"runtime.chat.tool_call_start",payload:t};case"tool.updated":return{sessionId:n,eventType:"runtime.chat.tool_call_update",payload:t};case"tool.finished":return{sessionId:n,eventType:"runtime.chat.tool_call_end",payload:t};case"approval.requested":return{sessionId:n,eventType:"approval.requested",payload:t};case"run.aborted":return{sessionId:n,eventType:"runtime.chat.aborted",payload:t};case"run.failed":return{sessionId:n,eventType:"runtime.chat.failed",payload:Rx(e.payload)};case"run.completed":return{sessionId:n,eventType:"runtime.chat.completed",payload:t};default:return}}class _x{client;constructor(e){this.client=new $n({url:e.address,authToken:e.authToken,clientId:e.clientId,clientType:e.clientType??"hub-session-client",displayName:e.displayName??"hub session client",workspaceRoot:e.workspaceRoot,cwd:e.cwd,metadata:e.metadata})}async connect(){await this.client.connect()}async taskCommand(e,t){return await this.client.connect(),(await this.client.command(e,t)).payload??{}}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(e){await this.client.connect();let t=await this.client.command("session.create",{workspaceRoot:e.workspaceRoot,cwd:e.cwd,sessionConfig:{providerId:e.provider,modelId:e.model,apiKey:e.apiKey,cwd:e.cwd??e.workspaceRoot,workspaceRoot:e.workspaceRoot,systemPrompt:e.systemPrompt??"",mode:e.mode??"act",rules:e.rules,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,enableTools:e.enableTools,enableSpawnAgent:e.enableSpawn!==!1,enableAgentTeams:e.enableTeams!==!1,disableMcpSettingsTools:e.disableMcpSettingsTools,agentPluginPaths:e.agentPluginPaths,missionLogIntervalSteps:e.missionStepInterval,missionLogIntervalMs:e.missionTimeIntervalMs},metadata:{source:e.source??"cli",provider:e.provider,model:e.model,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,prompt:void 0,interactive:e.interactive!==!1},runtimeOptions:{mode:e.mode,systemPrompt:e.systemPrompt,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,autoApproveTools:e.autoApproveTools,toolExecutors:e.toolExecutors,configExtensions:e.configExtensions},modelSelection:{provider:e.provider,model:e.model,apiKey:e.apiKey},toolPolicies:e.toolPolicies}),n=Ji(t.payload);if(!n?.sessionId)throw Error("hub session create returned no session id");return{sessionId:n.sessionId,startResult:{sessionId:n.sessionId,manifestPath:"",messagesPath:n.messagesPath??""}}}async sendRuntimeSession(e,t,n){return await this.client.connect(),{result:(await this.client.command("session.send_input",{prompt:t.prompt,mode:t.config.mode,attachments:t.attachments,delivery:t.delivery,timeoutSeconds:t.config.timeoutSeconds},e,n)).payload?.result}}async stopRuntimeSession(e){return await this.client.connect(),await this.client.command("session.detach",{sessionId:e},e),{applied:!0}}async abortRuntimeSession(e){return await this.client.connect(),await this.client.command("run.abort",{sessionId:e},e),{applied:!0}}async updateSession(e){return await this.client.connect(),await this.client.command("session.update",{sessionId:e.sessionId,metadata:e.metadata},e.sessionId),{updated:!0}}async getSession(e){await this.client.connect();let t;try{t=await this.client.command("session.get",void 0,e)}catch(n){if(Wi(n))return;throw n}return Ji(t.payload)}async readMessages(e){let t=e.trim();if(!t)return[];await this.client.connect();let n=await this.client.command("session.messages",{sessionId:t},t);if(!n.ok)throw Error(wy(n,"session.messages"));let r=n.payload?.messages;return Array.isArray(r)?r:[]}async restore(e){let t=e.sessionId.trim();if(!t)throw Error("sessionId is required");let n=e.restore?.messages!==!1;if(n&&!e.config)throw Error("config is required when restore.messages is true");await this.client.connect();let r=e.config,o=await this.client.command("session.restore",{sessionId:t,checkpointRunCount:e.checkpointRunCount,restore:e.restore,...r?{workspaceRoot:r.workspaceRoot,cwd:r.cwd,sessionConfig:{providerId:r.provider,modelId:r.model,apiKey:r.apiKey,cwd:r.cwd??r.workspaceRoot,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:r.mode??"act",rules:r.rules,maxIterations:r.maxIterations,enableTools:r.enableTools,enableSpawnAgent:r.enableSpawn!==!1,enableAgentTeams:r.enableTeams!==!1,disableMcpSettingsTools:r.disableMcpSettingsTools,agentPluginPaths:r.agentPluginPaths,missionLogIntervalSteps:r.missionStepInterval,missionLogIntervalMs:r.missionTimeIntervalMs},metadata:{source:r.source??"cli",provider:r.provider,model:r.model,enableTools:r.enableTools,enableSpawn:r.enableSpawn,enableTeams:r.enableTeams,prompt:void 0,interactive:r.interactive!==!1},runtimeOptions:{mode:r.mode,systemPrompt:r.systemPrompt,maxIterations:r.maxIterations,enableTools:r.enableTools,enableSpawn:r.enableSpawn,enableTeams:r.enableTeams,autoApproveTools:r.autoApproveTools,configExtensions:r.configExtensions},modelSelection:{provider:r.provider,model:r.model,apiKey:r.apiKey},toolPolicies:r.toolPolicies}:{}},t);if(!o.ok)throw Error(wy(o,"session.restore"));let s=Ji(o.payload);if(n&&!s?.sessionId)throw Error("hub checkpoint restore returned no session id");let i=Array.isArray(o.payload?.messages)?o.payload.messages:void 0,a=Ex(o.payload);return{sessionId:s?.sessionId,startResult:s?.sessionId?{sessionId:s.sessionId,manifestPath:"",messagesPath:s.messagesPath??""}:void 0,...i?{messages:i}:{},checkpoint:a}}async listSessions(e){await this.client.connect();let t=await this.client.command("session.list",{limit:e?.limit??200});return(Array.isArray(t.payload?.sessions)?t.payload?.sessions:[]).map((r)=>Ji({session:r})).filter((r)=>Boolean(r?.sessionId))}async searchSessions(e){await this.client.connect();let t=await this.client.command("session.search",e);return Array.isArray(t.payload?.hits)?t.payload.hits:[]}async deleteSession(e,t=!0){return await this.client.connect(),(await this.client.command("session.delete",{sessionId:e,deleteCheckpointRefs:t})).payload?.deleted===!0}async respondToolApproval(e){await this.client.connect(),await this.client.command("approval.respond",{approvalId:e.approvalId,approved:e.approved,payload:e.reason?{reason:e.reason}:void 0,responderClientId:e.responderClientId})}streamEvents(e,t){let n=new Set((e.sessionIds??[]).map((o)=>o.trim()).filter(Boolean)),r=this.client.subscribe((o)=>{let s=Px(o);if(!s)return;if(n.size>0&&!n.has(s.sessionId))return;t.onEvent?.(s)});return this.client.connect().catch((o)=>{t.onError?.(o instanceof Error?o:Error(String(o)))}),r}streamTeamProgress(e,t){let n=this.client.subscribe((r)=>{if(r.event!=="team.progress"||!r.payload)return;t.onProjection?.(r.payload)});return this.client.connect().catch((r)=>{t.onError?.(r instanceof Error?r:Error(String(r)))}),n}async createSchedule(e){return await this.client.connect(),(await this.client.command("schedule.create",e)).payload?.schedule}async listSchedules(e){await this.client.connect();let t=await this.client.command("schedule.list");return Array.isArray(t.payload?.schedules)?t.payload?.schedules:[]}async getSchedule(e){return await this.client.connect(),(await this.client.command("schedule.get",{scheduleId:e})).payload?.schedule}async updateSchedule(e,t){return await this.client.connect(),(await this.client.command("schedule.update",{scheduleId:e,...t})).payload?.schedule}async pauseSchedule(e){return await this.client.connect(),(await this.client.command("schedule.disable",{scheduleId:e})).payload?.schedule}async resumeSchedule(e){return await this.client.connect(),(await this.client.command("schedule.enable",{scheduleId:e})).payload?.schedule}async deleteSchedule(e){return await this.client.connect(),(await this.client.command("schedule.delete",{scheduleId:e})).payload?.deleted===!0}async triggerScheduleNow(e){return await this.client.connect(),(await this.client.command("schedule.trigger",{scheduleId:e})).payload?.execution}async listScheduleExecutions(e,t){await this.client.connect();let n=await this.client.command("schedule.list_executions",{scheduleId:e,limit:t});return Array.isArray(n.payload?.executions)?n.payload?.executions:[]}async getScheduleStats(){return await this.client.connect(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.client.connect();let e=await this.client.command("schedule.active");return Array.isArray(e.payload?.executions)?e.payload?.executions:[]}async getUpcomingScheduledRuns(e){await this.client.connect();let t=await this.client.command("schedule.upcoming",{limit:e});return Array.isArray(t.payload?.upcoming)?t.payload?.upcoming:[]}async createTask(e){return(await this.taskCommand("task.create",e)).task}async listTasks(e={}){let t=await this.taskCommand("task.list",e);return Array.isArray(t.tasks)?t.tasks:[]}async getTask(e){return(await this.taskCommand("task.get",{taskId:e})).task}async updateTask(e){return(await this.taskCommand("task.update",e)).task}async approveTask(e,t){return(await this.taskCommand("task.approve",{taskId:e,expectedRevision:t})).task}async cancelTask(e,t,n){return(await this.taskCommand("task.cancel",{taskId:e,reason:n,expectedRevision:t})).task}async runTask(e,t){return await this.taskCommand("task.run",{taskId:e,expectedRevision:t})}async getTaskAutomation(){return(await this.taskCommand("task.automation.get",{})).policy}async setTaskAutomation(e){return(await this.taskCommand("task.automation.set",{policy:e})).policy}}class xx{client;constructor(e){this.client=new $n({url:e.address,authToken:e.authToken,clientId:e.clientId,clientType:e.clientType??"hub-ui-client",displayName:e.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(e){await this.client.command("ui.notify",e)}async sendShowWindow(e){await this.client.command("ui.show_window",e??{})}async listClients(){let e=await this.client.command("client.list");return Array.isArray(e.payload?.clients)?e.payload.clients:[]}async listSessions(e=200){let t=await this.client.command("session.list",{limit:e});return Array.isArray(t.payload?.sessions)?t.payload.sessions:[]}async searchSessions(e){let t=await this.client.command("session.search",e);return Array.isArray(t.payload?.hits)?t.payload.hits:[]}async toggleSetting(e){let t=await this.client.command("settings.toggle",e);if(!t.ok)throw Error(t.error?.message??"settings.toggle failed");return t.payload}subscribeUI(e){return this.client.subscribe((t)=>{switch(t.event){case"ui.notify":e.onNotify?.(t.payload);break;case"ui.show_window":e.onShowWindow?.(t.payload);break;case"hub.client.registered":e.onClientRegistered?.(t.payload??{});break;case"hub.client.disconnected":e.onClientDisconnected?.(t.payload??{});break;case"session.created":e.onSessionCreated?.(t.payload??{});break;case"session.updated":e.onSessionUpdated?.(t.payload??{});break;case"session.detached":e.onSessionDetached?.(t.payload??{});break}})}}import{normalizeProviderId as Q1}from"@cline/llms";import{readdirSync as y1}from"node:fs";import{homedir as S1}from"node:os";import{isAbsolute as b1,join as Nm,resolve as Dm}from"node:path";import{captureSdkError as ft,createSessionId as v1,isLikelyAuthError as T1,normalizeUserInput as w1}from"@cline/shared";import{setHomeDirIfUnset as k1}from"@cline/shared/storage";import{decodeJwtPayload as AM,getClineEnvironmentConfig as zy}from"@cline/shared";import{decodeJwtPayload as Ux,getClineEnvironmentConfig as Fx}from"@cline/shared";import{createHash as Mx}from"node:crypto";var Ox;function Je(e){if(typeof e!=="string"||e.length===0)return"unset";return Mx("sha256").update(e).digest("hex").slice(0,8)}function ce(e){try{Ox?.debug(e)}catch{}}function Lx(){let e;return{promise:new Promise((n)=>{e=n}),resolve:e}}async function Wn(e){let t=await import("node:http"),n=e.host??"127.0.0.1",r=e.timeoutMs??300000,o=e.successHtml??Nx,s=Lx(),i=!1,a=null,d=null,c=null,u=(m)=>{if(i)return;i=!0,s.resolve(m)},l=()=>{if(a)clearTimeout(a),a=null;let m=c;if(c=null,d)d.close(),d.closeAllConnections?.(),d=null;if(m!==null&&e.onClose)Promise.resolve(e.onClose({host:n,port:m})).catch(()=>{})},p=async()=>(a=setTimeout(()=>{l(),u(null)},r),s.promise);for(let m of e.ports){let g=t.createServer((h,S)=>{try{let y=new URL(h.url||"",`http://${n}:${m}`);if(y.pathname!==e.callbackPath){S.statusCode=404,S.end("Not found");return}let b={url:y,code:y.searchParams.get("code")??void 0,state:y.searchParams.get("state")??void 0,provider:y.searchParams.get("provider")??void 0,error:y.searchParams.get("error")??void 0};if(b.error){S.statusCode=400,S.end(`Authentication failed: ${b.error}`),l(),u(b);return}if(!b.code){S.statusCode=400,S.end("Missing authorization code");return}if(e.expectedState&&b.state!==e.expectedState){S.statusCode=400,S.end("State mismatch");return}S.statusCode=200,S.setHeader("Content-Type","text/html; charset=utf-8"),S.end(o),l(),u(b)}catch{S.statusCode=500,S.end("Internal error")}}),f=await new Promise((h)=>{let S=(y)=>{g.off("error",S),h({bound:!1,error:y})};g.once("error",S),g.listen(m,n,()=>{g.off("error",S),d=g,h({bound:!0})})});if(f.error){if(f.error.code==="EADDRINUSE")continue;throw l(),f.error}if(f.bound){c=m;let h=`http://${n}:${m}${e.callbackPath}`;if(e.onListening)await Promise.resolve(e.onListening({host:n,port:m,callbackUrl:h})).catch(()=>{});return{callbackUrl:h,waitForCallback:p,cancelWait:()=>{l(),u(null)},close:()=>{l(),u(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var Nx=`<!DOCTYPE html>
312
+ `,"utf8"),await n()}finally{await Gc(r)}}}function Yc(e,t){return ey(`${e}.mutation`,"discovery mutation",t)}function zi(e,t){return ey(e,"startup",t)}async function Vt(e,t){DP();try{let n=await fetch(t?.authToken?XP(e):ty(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 Xt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function ty(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function XP(e){let t=new URL(ty(e));return t.pathname="/status",t.toString()}function c2(e){return OP(e)}import{CLINE_HUB_DEV_PORT as JP,CLINE_HUB_PORT as YP,resolveClineBuildEnv as QP}from"@cline/shared";var ZP="CLINE_HUB_HOST",e_="CLINE_HUB_PORT",t_="CLINE_HUB_PATHNAME",n_="127.0.0.1",r_=YP,o_="/hub";function ny(e){return QP(e)==="development"?JP:r_}function s_(e={}){return(e.env??process.env)[ZP]?.trim()||n_}function Ki(e={}){let n=(e.env??process.env)[e_]?.trim();if(!n)return ny(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return ny(e);return r}function i_(e={}){return(e.env??process.env)[t_]?.trim()||o_}function Fn(e={},t={}){return{host:e.host??s_(t),port:e.port??Ki(t),pathname:e.pathname??i_(t)}}import{join as a_}from"node:path";var d_="shared:cline",c_="CLINE_HUB_DISCOVERY_PATH",u_="hub-production";function h2(e){let t=xn(e.trim());return Un(`workspace:${t||e.trim()}`)}function vt(e=d_){return Un(`${e}@${Mt()}`)}function Ot(){return{ownerId:u_,discoveryPath:process.env[c_]?.trim()||a_(jo(),"locks","hub","production.json")}}var ry=15000,C_=200,oy=3000,I_=100,A_=[100,250,500,1000,2000],R_="--cline-hub-daemon",E_=3,P_=60000,eu=new Map,R2={resetRetireAttempts(){eu.clear()},resolveDaemonEntryArgs:uy};function __(e,t=Date.now()){let n=eu.get(e);if(!n||t-n.windowStartedAt>P_)return eu.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=E_}function x_(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function M_(){try{let e=b_(jo(),"logs","hub-daemon.log");return m_(S_(e),{recursive:!0}),{fd:g_(e,"a"),logPath:e}}catch{return}}function cy(){return dy()==="production"?Ot():vt()}function Ko(e){return Nr(e)}function O_(e){try{let t=JSON.parse(f_(`${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 Qc(e){try{h_(`${e}.superseded`)}catch{}}function sy(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Dr(e,t){try{return await Vt(e,{authToken:t})}catch{return}}async function iy(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Dr(e))?.url)return!0;await new Promise((o)=>setTimeout(o,I_))}return!1}async function Hr(e,t){if(!__(e.url))return!1;await Bn(e.url,e.authToken,"retired by newer install").catch(()=>!1),await nu(e.url,e.authToken).catch(()=>!1);let n=await iy(e.url,oy);if(!n&&e.pid&&L_(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await iy(e.url,oy)}if(n)await Gt(t).catch(()=>{return});return n}function L_(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function tu(e){try{return(await Fr(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function Zc(e,t){if(Ko(e))return"reusable";let n=await Bn(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await tu(e)){if(n)await Bn(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Hr(e,t);if(!r&&n)await Bn(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function N_(e){if(dy()!=="production")return;let t=vt();if(t.discoveryPath===e.discoveryPath)return;let n=await Re(t.discoveryPath);if(n?.url)await Hr(n,t.discoveryPath);else await Gt(t.discoveryPath).catch(()=>{return})}function D_(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return v_(new URL(`./entry.${e}`,import.meta.url))}function uy(e,t){if(w_(e))return[R_];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function H_(e,t){let n=D_(),r=process.execPath?.trim();if(!r)throw Error("unable to resolve runtime executable for hub daemon");let o=y_(r).toLowerCase().includes("bun"),s=uy(n,o);return{launcher:r,args:[...s,"--cwd",e,...x_(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...k_(process.env),CLINE_NO_INTERACTIVE:"1",[T_]:"1"}}}function U_(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 F_(e,t={}){if(ay())return;let n=H_(e,t),r=M_();try{l_(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)p_(r.fd)}}async function B_(e,t={}){for(let n=0;;n++)try{F_(e,t);return}catch(r){let o=A_[n];if(!U_(r)||o===void 0)throw r;await new Promise((s)=>setTimeout(s,o))}}function E2(e,t={}){if(ay())return;Go(e,t).catch(()=>{})}async function $_(e,t,n={}){let r=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Fn(n),s=Xt(o.host,o.port,o.pathname),i=(g)=>{if(!r)Ur(g.url,g.authToken);return g};await N_(e).catch(()=>{return});let a=await Re(e.discoveryPath),d=a?.url?void 0:O_(e.discoveryPath),c=!1;if(a?.url){let g=a.authToken;if(!g)c=!0,await Hr(a,e.discoveryPath);else{let f=await Dr(a.url,g);if(f?.url&&Ko(f)&&await dt(f.url,{authToken:g}))return Qc(e.discoveryPath),i({url:f.url,authToken:g});if(f?.url){if(await Zc({...f,authToken:g},e.discoveryPath)==="deferred_busy"&&await dt(f.url,{authToken:g}))return i({url:f.url,authToken:g})}else await Gt(e.discoveryPath).catch(()=>{return})}}let u=await Dr(s);if(u?.url){let g=sy(u,a??d,s);if(Ko(u)){let h=[u.authToken,a?.authToken,d?.authToken].filter((y)=>typeof y==="string"&&y.trim().length>0);for(let y of h){if(!await dt(u.url,{authToken:y}))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:y,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 qi(e.discoveryPath,b)}catch{}return Qc(e.discoveryPath),i({url:u.url,authToken:y})}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 Zc(g,e.discoveryPath);if(f==="deferred_busy"){for(let h of[g.authToken,a?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0))if(await dt(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 B_(t,{...p,manageConnectors:n.manageConnectors});let m=Date.now()+ry;while(Date.now()<m){let g=await Re(e.discoveryPath);if(g?.url&&g.authToken){let h=await Dr(g.url,g.authToken);if(h?.url&&Ko(h)&&await dt(h.url,{authToken:g.authToken}))return Qc(e.discoveryPath),i({url:h.url,authToken:g.authToken})}let f=await Dr(s);if(f?.url&&!Ko(f)){let h=sy(f,g??d,s),S=await Zc(h,e.discoveryPath);if(S==="deferred_busy"&&g?.authToken&&await dt(f.url,{authToken:g.authToken}))return i({url:f.url,authToken:g.authToken});if(S==="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,C_))}throw Error(`Timed out after ${ry}ms waiting for detached hub startup.`)}async function Go(e,t={}){let n=cy();return await zi(n.discoveryPath,async()=>$_(n,e,t))}var W_=5000,j_=500;async function P2(e={}){let t=cy(),n=e.workspaceRoot??process.cwd(),r=await Re(t.discoveryPath),o=r?.url?await Dr(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await Go(n)};let s={...o,authToken:o.authToken??r?.authToken,pid:o.pid??r?.pid};if(Hn(o).compatible)return{outcome:"already_current",url:o.url,authToken:s.authToken};if(qo(zo(),o)<=0)return{outcome:"hub_not_older",url:o.url,authToken:s.authToken};if(!await Bn(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 Bn(s.url,s.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},d=Date.now()+(e.waitForIdleMs??W_),c;for(;;){try{if(c=(await Fr(s.url,s.authToken)).activeSessionCount,c===0)break}catch{}if(Date.now()>=d)break;await new Promise((p)=>setTimeout(p,j_))}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 Hr(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 Go(n),activeSessionCount:c??0}}function du(){return K_()==="production"?Ot():vt()}function X_(){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 fy(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 fy(e.data);return String(e)}function J_(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 ly(e){let t=e,n=J_(t.reason);return new Oe("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:ou,{closeCode:t.code,closeReason:n||void 0})}function py(e,t){if(e instanceof Oe)return e;if(e instanceof Error)return new Oe("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new Oe("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 Oe("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new Oe("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 ru="*",Gi=8000,Y_="cline-hub-auth.",hy=new Map,yy=new Set,Q_=3000,Z_=3000,ex=100,ou="Hub connection closed",tx=250,nx=5000,my=0.5;class Oe extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function rx(e){return e instanceof Oe}class Vi extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function U2(e,t){return e instanceof Vi&&e.code==="hub_command_timeout"&&(t===void 0||e.command===t)}function cu(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let r=uu(e.toString());return r?hy.get(r):void 0}function ox(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 uu(e){if(!ox(e))return;let t=new URL(Xi(e));return t.search="",t.hash="",t.toString()}function su(e){let t=uu(e);return!!t&&yy.has(t)}function Ur(e,t){let n=uu(e);if(n){if(yy.add(n),t?.trim())hy.set(n,t)}return e}class $n{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 Oe("hub_connection_closed",ou);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()||cu(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(ln.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=py(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 Oe("hub_connect_timeout",`Timed out resolving hub connection headers after ${Gi}ms`))},Gi)})])}catch(c){let u=c instanceof Oe?c:new Oe("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 Oe("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let s=o?new V_(e.toString(),{headers:{...o}}):new(X_())(e.toString(),t?[`${Y_}${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 Oe("hub_connect_timeout",`Timed out connecting to hub after ${Gi}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)},Gi);s.addEventListener("open",()=>{if(u)return;u=!0,clearTimeout(l),d()}),s.addEventListener("error",(p)=>{if(u)return;u=!0,clearTimeout(l);let m=py(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:ly(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(fy(d)))}),s.addEventListener("close",(d)=>{if(this.socket!==s)return;if(!i)this.lastCloseError=ly(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=q_("hubreq_");r?.onDispatch?.(s);let i=G_(e,r?.timeoutMs),a=new Promise((c,u)=>{let l=i===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(s))return;u(new Vi(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===$i){let c=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Lr(c,d.error.message)}throw new Vi(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!su(this.currentUrl)||!rx(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await au({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(tx*2**this.reconnectAttempt,nx),t=Math.round(e*(1-my)+Math.random()*e*my);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(!su(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await au({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 Oe("hub_connection_closed",ou);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 Oe("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??ru}subscriptionSessionIdFromKey(e){return e===ru?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[ru,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 Xi(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 dt(e,t){let n=new $n({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 iu(e,t){let n=Xi(e),r=await Vt(n,{authToken:t?.authToken});if(!r)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=Mt(),s=Hn(r,o);if(!s.compatible&&!Nr(r))return{status:s.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!z_(r).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await dt(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}async function sx(e){let t=Date.now()+Z_;while(Date.now()<t){if(!(await Vt(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,ex))}return!1}function ix(e,t){try{return Xi(e)===Xi(t)}catch{return!1}}function Sy(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 F2(e){return Sy(e).activeSessionCount>0}async function Fr(e,t,n){let r=new $n({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:Q_});return Sy(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function by(e,t,n){try{return(await Fr(e,t,n)).activeSessionCount===0}catch{return!1}}async function ax(e,t){let n=`${e.discoveryPath}.superseded`,r=await Re(n);if(!r?.url||!r.authToken)return;let o=await iu(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await by(o.url,r.authToken,t))return;return Ur(o.url,r.authToken)}async function dx(e={}){if(e.endpoint?.trim()){let o=await iu(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=du(),n=await Re(t.discoveryPath);if(!n?.url)return await ax(t,e);let r=await iu(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return Ur(r.url,n.authToken);if(r.status==="protocol_mismatch")await Gt(t.discoveryPath).catch(()=>{return});return}async function au(e={}){let t=await dx(e);if(t&&await dt(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Go(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function Bn(e,t,n,r){gy();let o=new URL(e),s=t?.trim()||cu(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 nu(e,t){gy();let n=new URL(e),r=t?.trim()||cu(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 cx(e=du()){let t=await Re(e.discoveryPath);if(!t?.url)return!1;try{if(await nu(t.url,t.authToken))return!0}catch{}return!1}async function B2(e){if(!su(e.url))return;let t=du(),n=await Re(t.discoveryPath);if(!n?.url||!ix(n.url,e.url))return;if(!await by(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await cx())return;if(!await sx(n.url))return;return await Gt(t.discoveryPath).catch(()=>{return}),await au({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveClineBuildEnv as ux}from"@cline/shared";function lx(e,t){if(e instanceof Error)return e;if(e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"&&e.message.trim())return Error(e.message.trim());let n=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return Error(n?`Failed to connect to hub at ${t} (${n} event before socket open).`:`Failed to connect to hub at ${t}.`)}var px="cline-hub-auth.";function mx(e){return e.host!==void 0||e.port!==void 0||e.pathname!==void 0}function gx(e,t){let n=new URL(e),r=new URL(t);return n.search="",n.hash="",r.search="",r.hash="",n.toString()===r.toString()}function vy(){return ux()==="production"?Ot():vt()}async function fx(e){let t=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),t)return t;let n=vy(),r=await Re(n.discoveryPath);if(r?.url&&gx(e.toString(),r.url))return r.authToken;return}async function hx(e={}){let t=Fn(e);if(!mx(e)){let n=vy(),r=await Re(n.discoveryPath);if(r?.url)return r.url}return Xt(t.host,t.port,t.pathname)}async function Ty(e){return await new Promise((t,n)=>{(async()=>{let r=new URL(e),o=await fx(r);r.hash="";let s=new WebSocket(r.toString(),o?[`${px}${o}`]:void 0),i=new Map,a=0;s.addEventListener("open",()=>{t({send(d){let c=d.requestId??`hub-client-${++a}`;return new Promise((u,l)=>{i.set(c,{resolve:u,reject:l});let p={kind:"command",envelope:{...d,requestId:c}};s.send(JSON.stringify(p))})},close(){s.close()}})}),s.addEventListener("message",(d)=>{let c=JSON.parse(String(d.data));if(c.kind==="reply"&&c.envelope.requestId){let u=i.get(c.envelope.requestId);if(u)i.delete(c.envelope.requestId),u.resolve(c.envelope)}}),s.addEventListener("close",()=>{for(let d of i.values())d.reject(Error("Hub connection closed"));i.clear()}),s.addEventListener("error",(d)=>{n(lx(d,e))})})().catch(n)})}async function K2(e){try{return(await Ty(e)).close(),!0}catch{return!1}}async function G2(e,t){let n=await hx(e),r=await Ty(n);try{return await r.send({version:t.version??"v1",clientId:t.clientId??"hub-client",...t})}finally{r.close()}}import{existsSync as yx}from"node:fs";import{isHubDaemonProcess as Sx,resolveClineBuildEnv as bx}from"@cline/shared";var vx=1e4,Tx="CLINE_HUB_BUILD_WATCH_INTERVAL_MS";function wx(){let e=Number(process.env[Tx]);return Number.isFinite(e)&&e>0?e:vx}async function kx(e,t){try{let n=await Fr(e.url,t);return{...e,activeSessionCount:n.activeSessionCount,participantClientCount:n.participantClientCount}}catch{return e}}function Cx(){return bx()==="production"?Ot():vt()}function Ix(e){try{return yx(`${e}.lock`)}catch{return!1}}async function Ax(){let e=Cx();if(Ix(e.discoveryPath))return;let t=await Re(e.discoveryPath).catch(()=>{return});if(!t?.url)return;let n=await Vt(t.url).catch(()=>{return});if(!n?.url)return;let r=Mt(),o=Hn(n,r);if(o.compatible)return;let s=(a)=>({url:n.url,reason:a,hubBuildId:n.buildId,hubCoreVersion:n.coreVersion,expectedBuildId:r});if(o.reason==="unsupported_protocol")return s("unsupported_protocol");let i=zo();if(i.coreVersion&&n.coreVersion&&i.coreVersion===n.coreVersion)return;if(qo(i,n)>0)return await kx(s("outdated_hub"),t.authToken);return s("build_mismatch")}function eY(e){if(Sx()||process.env.CLINE_HUB_PORT?.trim())return()=>{};let t=e.intervalMs??wx(),n,r,o=!1,s=setInterval(()=>{if(o)return;o=!0,Ax().then((i)=>{if(!i){n=void 0,r=void 0;return}let a=`${i.reason}:${i.hubBuildId??""}`;if(a===n)return;if(i.reason==="outdated_hub"&&r!==a){r=a;return}r=void 0,n=a,e.onMismatch(i)}).catch(()=>{return}).finally(()=>{o=!1})},t);return s.unref?.(),()=>{clearInterval(s)}}function lu(e){return e?JSON.parse(JSON.stringify(e)):{}}function Ji(e){let t=e?.session&&typeof e.session==="object"?e.session:void 0;if(!t)return;let n=t.metadata&&typeof t.metadata==="object"?lu(t.metadata):void 0;return{sessionId:typeof t.sessionId==="string"?t.sessionId:"",parentSessionId:typeof n?.parentSessionId==="string"?n.parentSessionId:void 0,status:typeof t.status==="string"?t.status:void 0,messagesPath:typeof n?.messagesPath==="string"?n.messagesPath:void 0,metadata:n}}function wy(e,t){return e.error?.message??`hub command failed: ${t}`}function Rx(e){let t=lu(e);if(typeof t.error==="string"&&t.error.trim())return{...t,error:t.error.trim()};let n=t.result&&typeof t.result==="object"?t.result:void 0;if(typeof n?.text==="string"&&n.text.trim())return{...t,error:n.text.trim()};let r=n?.error&&typeof n.error==="object"?n.error:void 0;if(typeof r?.message==="string"&&r.message.trim())return{...t,error:r.message.trim()};return t}function ky(e){let t=e?.sessionId;return typeof t==="string"&&t.trim()?t.trim():void 0}function Ex(e){let t=e?.checkpoint;if(!t||typeof t!=="object"||Array.isArray(t))throw Error("hub checkpoint restore returned no checkpoint");let n=t;if(typeof n.ref!=="string"||typeof n.createdAt!=="number"||typeof n.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return n}function Px(e){let t=lu(e.payload);if(e.event==="schedule.execution_completed")return{sessionId:e.sessionId?.trim()||ky(t)||"",eventType:"schedule.execution.completed",payload:t};if(e.event==="schedule.execution_failed")return{sessionId:e.sessionId?.trim()||ky(t)||"",eventType:"schedule.execution.failed",payload:t};let n=e.sessionId?.trim();if(!n)return;switch(e.event){case"iteration.started":return{sessionId:n,eventType:"runtime.chat.iteration_start",payload:t};case"iteration.finished":return{sessionId:n,eventType:"runtime.chat.iteration_end",payload:t};case"assistant.delta":return{sessionId:n,eventType:"runtime.chat.text_delta",payload:t};case"assistant.media":return{sessionId:n,eventType:"runtime.chat.media",payload:t};case"usage.updated":return{sessionId:n,eventType:"runtime.chat.usage",payload:t};case"session.notice":return{sessionId:n,eventType:"runtime.chat.notice",payload:t};case"tool.started":return{sessionId:n,eventType:"runtime.chat.tool_call_start",payload:t};case"tool.updated":return{sessionId:n,eventType:"runtime.chat.tool_call_update",payload:t};case"tool.finished":return{sessionId:n,eventType:"runtime.chat.tool_call_end",payload:t};case"approval.requested":return{sessionId:n,eventType:"approval.requested",payload:t};case"run.aborted":return{sessionId:n,eventType:"runtime.chat.aborted",payload:t};case"run.failed":return{sessionId:n,eventType:"runtime.chat.failed",payload:Rx(e.payload)};case"run.completed":return{sessionId:n,eventType:"runtime.chat.completed",payload:t};default:return}}class _x{client;constructor(e){this.client=new $n({url:e.address,authToken:e.authToken,clientId:e.clientId,clientType:e.clientType??"hub-session-client",displayName:e.displayName??"hub session client",workspaceRoot:e.workspaceRoot,cwd:e.cwd,metadata:e.metadata})}async connect(){await this.client.connect()}async taskCommand(e,t){return await this.client.connect(),(await this.client.command(e,t)).payload??{}}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(e){await this.client.connect();let t=await this.client.command("session.create",{workspaceRoot:e.workspaceRoot,cwd:e.cwd,sessionConfig:{providerId:e.provider,modelId:e.model,apiKey:e.apiKey,cwd:e.cwd??e.workspaceRoot,workspaceRoot:e.workspaceRoot,systemPrompt:e.systemPrompt??"",mode:e.mode??"act",rules:e.rules,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,enableTools:e.enableTools,enableSpawnAgent:e.enableSpawn!==!1,enableAgentTeams:e.enableTeams!==!1,disableMcpSettingsTools:e.disableMcpSettingsTools,agentPluginPaths:e.agentPluginPaths,missionLogIntervalSteps:e.missionStepInterval,missionLogIntervalMs:e.missionTimeIntervalMs},metadata:{source:e.source??"cli",provider:e.provider,model:e.model,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,prompt:void 0,interactive:e.interactive!==!1},runtimeOptions:{mode:e.mode,systemPrompt:e.systemPrompt,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,autoApproveTools:e.autoApproveTools,toolExecutors:e.toolExecutors,configExtensions:e.configExtensions},modelSelection:{provider:e.provider,model:e.model,apiKey:e.apiKey},toolPolicies:e.toolPolicies}),n=Ji(t.payload);if(!n?.sessionId)throw Error("hub session create returned no session id");return{sessionId:n.sessionId,startResult:{sessionId:n.sessionId,manifestPath:"",messagesPath:n.messagesPath??""}}}async sendRuntimeSession(e,t,n){return await this.client.connect(),{result:(await this.client.command("session.send_input",{prompt:t.prompt,mode:t.config.mode,attachments:t.attachments,delivery:t.delivery,timeoutSeconds:t.config.timeoutSeconds},e,n)).payload?.result}}async stopRuntimeSession(e){return await this.client.connect(),await this.client.command("session.detach",{sessionId:e},e),{applied:!0}}async abortRuntimeSession(e){return await this.client.connect(),await this.client.command("run.abort",{sessionId:e},e),{applied:!0}}async updateSession(e){return await this.client.connect(),await this.client.command("session.update",{sessionId:e.sessionId,metadata:e.metadata},e.sessionId),{updated:!0}}async getSession(e){await this.client.connect();let t;try{t=await this.client.command("session.get",void 0,e)}catch(n){if(Wi(n))return;throw n}return Ji(t.payload)}async readMessages(e){let t=e.trim();if(!t)return[];await this.client.connect();let n=await this.client.command("session.messages",{sessionId:t},t);if(!n.ok)throw Error(wy(n,"session.messages"));let r=n.payload?.messages;return Array.isArray(r)?r:[]}async restore(e){let t=e.sessionId.trim();if(!t)throw Error("sessionId is required");let n=e.restore?.messages!==!1;if(n&&!e.config)throw Error("config is required when restore.messages is true");await this.client.connect();let r=e.config,o=await this.client.command("session.restore",{sessionId:t,checkpointRunCount:e.checkpointRunCount,restore:e.restore,...r?{workspaceRoot:r.workspaceRoot,cwd:r.cwd,sessionConfig:{providerId:r.provider,modelId:r.model,apiKey:r.apiKey,cwd:r.cwd??r.workspaceRoot,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:r.mode??"act",rules:r.rules,maxIterations:r.maxIterations,enableTools:r.enableTools,enableSpawnAgent:r.enableSpawn!==!1,enableAgentTeams:r.enableTeams!==!1,disableMcpSettingsTools:r.disableMcpSettingsTools,agentPluginPaths:r.agentPluginPaths,missionLogIntervalSteps:r.missionStepInterval,missionLogIntervalMs:r.missionTimeIntervalMs},metadata:{source:r.source??"cli",provider:r.provider,model:r.model,enableTools:r.enableTools,enableSpawn:r.enableSpawn,enableTeams:r.enableTeams,prompt:void 0,interactive:r.interactive!==!1},runtimeOptions:{mode:r.mode,systemPrompt:r.systemPrompt,maxIterations:r.maxIterations,enableTools:r.enableTools,enableSpawn:r.enableSpawn,enableTeams:r.enableTeams,autoApproveTools:r.autoApproveTools,configExtensions:r.configExtensions},modelSelection:{provider:r.provider,model:r.model,apiKey:r.apiKey},toolPolicies:r.toolPolicies}:{}},t);if(!o.ok)throw Error(wy(o,"session.restore"));let s=Ji(o.payload);if(n&&!s?.sessionId)throw Error("hub checkpoint restore returned no session id");let i=Array.isArray(o.payload?.messages)?o.payload.messages:void 0,a=Ex(o.payload);return{sessionId:s?.sessionId,startResult:s?.sessionId?{sessionId:s.sessionId,manifestPath:"",messagesPath:s.messagesPath??""}:void 0,...i?{messages:i}:{},checkpoint:a}}async listSessions(e){await this.client.connect();let t=await this.client.command("session.list",{limit:e?.limit??200});return(Array.isArray(t.payload?.sessions)?t.payload?.sessions:[]).map((r)=>Ji({session:r})).filter((r)=>Boolean(r?.sessionId))}async searchSessions(e){await this.client.connect();let t=await this.client.command("session.search",e);return Array.isArray(t.payload?.hits)?t.payload.hits:[]}async deleteSession(e,t=!0){return await this.client.connect(),(await this.client.command("session.delete",{sessionId:e,deleteCheckpointRefs:t})).payload?.deleted===!0}async respondToolApproval(e){await this.client.connect(),await this.client.command("approval.respond",{approvalId:e.approvalId,approved:e.approved,payload:e.reason?{reason:e.reason}:void 0,responderClientId:e.responderClientId})}streamEvents(e,t){let n=new Set((e.sessionIds??[]).map((o)=>o.trim()).filter(Boolean)),r=this.client.subscribe((o)=>{let s=Px(o);if(!s)return;if(n.size>0&&!n.has(s.sessionId))return;t.onEvent?.(s)});return this.client.connect().catch((o)=>{t.onError?.(o instanceof Error?o:Error(String(o)))}),r}streamTeamProgress(e,t){let n=this.client.subscribe((r)=>{if(r.event!=="team.progress"||!r.payload)return;t.onProjection?.(r.payload)});return this.client.connect().catch((r)=>{t.onError?.(r instanceof Error?r:Error(String(r)))}),n}async createSchedule(e){return await this.client.connect(),(await this.client.command("schedule.create",e)).payload?.schedule}async listSchedules(e){await this.client.connect();let t=await this.client.command("schedule.list");return Array.isArray(t.payload?.schedules)?t.payload?.schedules:[]}async getSchedule(e){return await this.client.connect(),(await this.client.command("schedule.get",{scheduleId:e})).payload?.schedule}async updateSchedule(e,t){return await this.client.connect(),(await this.client.command("schedule.update",{scheduleId:e,...t})).payload?.schedule}async pauseSchedule(e){return await this.client.connect(),(await this.client.command("schedule.disable",{scheduleId:e})).payload?.schedule}async resumeSchedule(e){return await this.client.connect(),(await this.client.command("schedule.enable",{scheduleId:e})).payload?.schedule}async deleteSchedule(e){return await this.client.connect(),(await this.client.command("schedule.delete",{scheduleId:e})).payload?.deleted===!0}async triggerScheduleNow(e){return await this.client.connect(),(await this.client.command("schedule.trigger",{scheduleId:e})).payload?.execution}async listScheduleExecutions(e,t){await this.client.connect();let n=await this.client.command("schedule.list_executions",{scheduleId:e,limit:t});return Array.isArray(n.payload?.executions)?n.payload?.executions:[]}async getScheduleStats(){return await this.client.connect(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.client.connect();let e=await this.client.command("schedule.active");return Array.isArray(e.payload?.executions)?e.payload?.executions:[]}async getUpcomingScheduledRuns(e){await this.client.connect();let t=await this.client.command("schedule.upcoming",{limit:e});return Array.isArray(t.payload?.upcoming)?t.payload?.upcoming:[]}async createTask(e){return(await this.taskCommand("task.create",e)).task}async listTasks(e={}){let t=await this.taskCommand("task.list",e);return Array.isArray(t.tasks)?t.tasks:[]}async getTask(e){return(await this.taskCommand("task.get",{taskId:e})).task}async updateTask(e){return(await this.taskCommand("task.update",e)).task}async approveTask(e,t){return(await this.taskCommand("task.approve",{taskId:e,expectedRevision:t})).task}async cancelTask(e,t,n){return(await this.taskCommand("task.cancel",{taskId:e,reason:n,expectedRevision:t})).task}async runTask(e,t){return await this.taskCommand("task.run",{taskId:e,expectedRevision:t})}async getTaskAutomation(){return(await this.taskCommand("task.automation.get",{})).policy}async setTaskAutomation(e){return(await this.taskCommand("task.automation.set",{policy:e})).policy}}class xx{client;constructor(e){this.client=new $n({url:e.address,authToken:e.authToken,clientId:e.clientId,clientType:e.clientType??"hub-ui-client",displayName:e.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(e){await this.client.command("ui.notify",e)}async sendShowWindow(e){await this.client.command("ui.show_window",e??{})}async listClients(){let e=await this.client.command("client.list");return Array.isArray(e.payload?.clients)?e.payload.clients:[]}async listSessions(e=200){let t=await this.client.command("session.list",{limit:e});return Array.isArray(t.payload?.sessions)?t.payload.sessions:[]}async searchSessions(e){let t=await this.client.command("session.search",e);return Array.isArray(t.payload?.hits)?t.payload.hits:[]}async toggleSetting(e){let t=await this.client.command("settings.toggle",e);if(!t.ok)throw Error(t.error?.message??"settings.toggle failed");return t.payload}subscribeUI(e){return this.client.subscribe((t)=>{switch(t.event){case"ui.notify":e.onNotify?.(t.payload);break;case"ui.show_window":e.onShowWindow?.(t.payload);break;case"hub.client.registered":e.onClientRegistered?.(t.payload??{});break;case"hub.client.disconnected":e.onClientDisconnected?.(t.payload??{});break;case"session.created":e.onSessionCreated?.(t.payload??{});break;case"session.updated":e.onSessionUpdated?.(t.payload??{});break;case"session.detached":e.onSessionDetached?.(t.payload??{});break}})}}import{normalizeProviderId as Q1}from"@cline/llms";import{readdirSync as y1}from"node:fs";import{homedir as S1}from"node:os";import{isAbsolute as b1,join as Nm,resolve as Dm}from"node:path";import{captureSdkError as ft,createSessionId as v1,isLikelyAuthError as T1,normalizeUserInput as w1}from"@cline/shared";import{setHomeDirIfUnset as k1}from"@cline/shared/storage";import{decodeJwtPayload as AM,getClineEnvironmentConfig as zy}from"@cline/shared";import{decodeJwtPayload as Ux,getClineEnvironmentConfig as Fx}from"@cline/shared";import{createHash as Mx}from"node:crypto";var Ox;function Je(e){if(typeof e!=="string"||e.length===0)return"unset";return Mx("sha256").update(e).digest("hex").slice(0,8)}function ce(e){try{Ox?.debug(e)}catch{}}function Lx(){let e;return{promise:new Promise((n)=>{e=n}),resolve:e}}async function Wn(e){let t=await import("node:http"),n=e.host??"127.0.0.1",r=e.timeoutMs??300000,o=e.successHtml??Nx,s=Lx(),i=!1,a=null,d=null,c=null,u=(m)=>{if(i)return;i=!0,s.resolve(m)},l=()=>{if(a)clearTimeout(a),a=null;let m=c;if(c=null,d)d.close(),d.closeAllConnections?.(),d=null;if(m!==null&&e.onClose)Promise.resolve(e.onClose({host:n,port:m})).catch(()=>{})},p=async()=>(a=setTimeout(()=>{l(),u(null)},r),s.promise);for(let m of e.ports){let g=t.createServer((h,S)=>{try{let y=new URL(h.url||"",`http://${n}:${m}`);if(y.pathname!==e.callbackPath){S.statusCode=404,S.end("Not found");return}let b={url:y,code:y.searchParams.get("code")??void 0,state:y.searchParams.get("state")??void 0,provider:y.searchParams.get("provider")??void 0,error:y.searchParams.get("error")??void 0};if(b.error){S.statusCode=400,S.end(`Authentication failed: ${b.error}`),l(),u(b);return}if(!b.code){S.statusCode=400,S.end("Missing authorization code");return}if(e.expectedState&&b.state!==e.expectedState){S.statusCode=400,S.end("State mismatch");return}S.statusCode=200,S.setHeader("Content-Type","text/html; charset=utf-8"),S.end(o),l(),u(b)}catch{S.statusCode=500,S.end("Internal error")}}),f=await new Promise((h)=>{let S=(y)=>{g.off("error",S),h({bound:!1,error:y})};g.once("error",S),g.listen(m,n,()=>{g.off("error",S),d=g,h({bound:!0})})});if(f.error){if(f.error.code==="EADDRINUSE")continue;throw l(),f.error}if(f.bound){c=m;let h=`http://${n}:${m}${e.callbackPath}`;if(e.onListening)await Promise.resolve(e.onListening({host:n,port:m,callbackUrl:h})).catch(()=>{});return{callbackUrl:h,waitForCallback:p,cancelWait:()=>{l(),u(null)},close:()=>{l(),u(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var Nx=`<!DOCTYPE html>
313
313
  <html lang="en">
314
314
  <head>
315
315
  <meta charset="utf-8">
@@ -356,7 +356,7 @@ ${JSON.stringify(r,null,2)}`}startClaimLeaseHeartbeat(e){let t=Math.max(1000,Mat
356
356
  `);return`sha256:${n.digest("hex")}`}function Ru(e){let t=nS(e.sourceMessages),n=t.at(-1),r=sS(n);return ra.parse({version:1,updated_at:e.updatedAt??new Date().toISOString(),...e.conversationId?.trim()?{conversation_id:e.conversationId.trim()}:{},source_message_count:t.length,source_prefix_hash:iS(t),...r?{source_last_message_key:r}:{},messages:Au(e.compactedMessages),...e.systemPrompt!==void 0?{system_prompt:e.systemPrompt}:{}})}function Zo(e,t){if(t=nS(t),!(e.source_message_count<=t.length))return;let r=!!e.source_prefix_hash&&iS(t,e.source_message_count)===e.source_prefix_hash,o=t[e.source_message_count-1],s=!e.source_prefix_hash&&e.source_message_count>0&&!!e.source_last_message_key&&sS(o)===e.source_last_message_key;if(!(r||s))return;return[...Au(e.messages),...Au(t.slice(e.source_message_count))]}function Kr(e){let t=ra.safeParse(e);return t.success?t.data:void 0}import{createHandlerAsync as HO}from"@cline/llms";import{formatDisplayUserInput as aS}from"@cline/shared";var sO=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function iO(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function aO(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function dO(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function cO(e){if(typeof e.content==="string")return{hasAttachment:!1,text:e.content};if(!Array.isArray(e.content))return{hasAttachment:!1,text:"unknown"};let t=!1,n=!1,r=[];for(let o of e.content){if(!o||typeof o!=="object"||Array.isArray(o))continue;let s=o;if(s.type==="text"&&typeof s.text==="string")r.push(s.text);else if(s.type==="tool_result"||s.type==="tool-result")n=!0;else if(s.type==="file"||s.type==="image")t=!0}return{hasAttachment:t&&!n,text:r.join(`
357
357
  `)}}function uO(e){let t=aS(e);return t.startsWith("[TASK RESUMPTION]")||t==="The user approved switching to act mode. Continue with the approved plan now."}function Gr(e){if(iO(e.role)!=="user")return 0;let t=aO(e),n=typeof t?.kind==="string"?t.kind:void 0,r=dO(t);if(n==="compaction"||n==="compaction_summary")return r??1;if(r!==void 0)return r;if(n&&sO.has(n))return 0;let o=cO(e);if(!o.hasAttachment&&!aS(o.text))return 0;if(!o.hasAttachment&&uO(o.text))return 0;return 1}function es(e){let t=0;for(let n of e??[])t+=Gr(n);return t}function lO(e){switch(e){case"agentic_summary":case"basic_compaction_projection":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!0,dropThinkingBlocks:!0};case"normal_provider_request":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!1,dropThinkingBlocks:!1}}}function dS(e){return e.map((t)=>({...t,content:Array.isArray(t.content)?t.content.map((n)=>({...n})):t.content,...t.metadata?{metadata:{...t.metadata}}:{}}))}function Dt(e){try{return JSON.stringify(e).length}catch{return String(e).length}}function oa(e,t){return e.reduce((n,r)=>n+t(r),0)}function pS(e){return e.role==="user"&&Array.isArray(e.content)&&e.content.length>0&&e.content.every((t)=>t.type==="tool_result")}function sa(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n.role==="user"&&!pS(n))return t}return-1}function pO(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n.role==="user"&&!pS(n))return t}return-1}function Pu(e){let t=new Set;if(!Array.isArray(e.content))return t;for(let n of e.content)if(n.type==="tool_use")t.add(n.id);else if(n.type==="tool_result")t.add(n.tool_use_id);return t}function mO(e){let t=new Map;for(let n=0;n<e.length;n+=1)for(let r of Pu(e[n])){let o=t.get(r);if(o)o.add(n);else t.set(r,new Set([n]))}return t}function Eu(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)}for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(!Array.isArray(r.content))continue;if(r.content.some((o)=>o.type==="tool_use"&&!t.has(o.id)))return n}return e.length}function gO(e,t){let n=mO(e),r=new Set,o=[t];while(o.length>0){let s=o.shift();if(s===void 0||r.has(s))continue;r.add(s);for(let i of Pu(e[s]))for(let a of n.get(i)??[])if(!r.has(a))o.push(a)}return r}function fO(e){return e.type==="image"||e.type==="media"||e.type==="redacted_thinking"}function hO(e){return e.type==="image"}function yO(e,t,n){if(t.dropThinkingBlocks&&e.type==="thinking")return!0;return t.dropUnsafeOutsideLiveTail&&!n&&fO(e)}function cS(e,t,n,r="over_budget"){let o=[],s=[];for(let i=0;i<e.length;i+=1){let a=e[i];if(Array.isArray(a.content)&&a.content.length===0){n.push({kind:"dropped_message",path:{messageIndex:t[i]},reason:r,originalSize:Dt(a),finalSize:0});continue}o.push(a),s.push(t[i])}return{messages:o,originalIndexes:s}}function SO(e,t,n,r,o,s){return e.map((i,a)=>{if(!Array.isArray(i.content))return i;let d=!1,c=a===r||a>=o,u=i.content.flatMap((l,p)=>{if(yO(l,s,c))return d=!0,n.push({kind:"dropped_block",path:{messageIndex:t[a],blockIndex:p},reason:"unsafe_to_truncate",originalSize:Dt(l),finalSize:0}),[];if(l.type==="tool_result"&&Array.isArray(l.content)){let m=l.content.filter((g)=>{if(s.dropUnsafeOutsideLiveTail&&!c&&hO(g))return!1;return!0});if(m.length!==l.content.length){d=!0;let g={...l,content:m};return n.push({kind:"dropped_block",path:{messageIndex:t[a],blockIndex:p},reason:"unsafe_to_truncate",originalSize:Dt(l),finalSize:Dt(g)}),[g]}}return[l]});return d?{...i,content:u}:i})}function bO(e,t,n){return e.map((r,o)=>{if(!Array.isArray(r.content))return r;let s=!1,i=r.content.filter((a,d)=>{if(a.type!=="thinking")return!0;return s=!0,n.push({kind:"dropped_block",path:{messageIndex:t[o],blockIndex:d},reason:"unsafe_to_truncate",originalSize:Dt(a),finalSize:0}),!1});return s?{...r,content:i}:r})}function Vr(e,t){if(t<=0)return"";if(e.length<=t)return e;if(t<=16)return e.slice(0,Math.max(1,t));let n=`
358
358
  ...[truncated ${e.length-t} chars]`,r=Math.max(1,t-n.length),o=`
359
- ...[truncated ${e.length-r} chars]`;return`${e.slice(0,r)}${o}`}function uS(e,t){if(typeof e==="string")return Vr(e,t);let n=t;return e.map((r)=>{if(n<=0){if(r.type==="text")return{...r,text:""};if(r.type==="file")return{...r,content:""};return r}if(r.type==="text"){let o=Vr(r.text,n);return n-=o.length,{...r,text:o}}if(r.type==="file"){let o=Vr(r.content,n);return n-=o.length,{...r,content:o}}return r})}function vO(e){if(typeof e==="string")return e.length;return e.reduce((t,n)=>{if(n.type==="text")return t+n.text.length;if(n.type==="file")return t+n.content.length;return t},0)}function TO(e,t){if(typeof e.content==="string")return{...e,content:Vr(e.content,t)};let n=t;return{...e,content:e.content.map((r)=>{if(n<=0){if(r.type==="text")return{...r,text:""};if(r.type==="file")return{...r,content:""};if(r.type==="tool_result")return{...r,content:uS(r.content,0)};return r}if(r.type==="text"){let o=Vr(r.text,n);return n-=o.length,{...r,text:o}}if(r.type==="file"){let o=Vr(r.content,n);return n-=o.length,{...r,content:o}}if(r.type==="tool_result"){let o=uS(r.content,n);return n-=vO(o),{...r,content:o}}return r})}}function wO(e){if(typeof e.content==="string")return e.content.length>0;return e.content.some((t)=>t.type==="text"||t.type==="file"||t.type==="tool_result")}function kO(e,t,n){return{messages:e.filter((r,o)=>!n.has(o)),originalIndexes:t.filter((r,o)=>!n.has(o))}}function CO(e,t){if(t<0)return!1;for(let n of e)if(n>=t)return!0;return!1}function lS(e,t){return t>=0&&e.has(t)}function ts(e){let t=[],n=[],r=lO(e.policyIntent);if(e.targetTokens<=0)return{status:"failed",messages:dS(e.messages),actions:t,liveTailHandling:"preserved_out_of_band",estimatedTokens:oa(e.messages,e.estimateMessageTokens),warnings:[{code:"budget_impossible",message:"Target budget must be greater than zero."}]};let o=dS(e.messages),s=o.map((c,u)=>u);if(r.dropThinkingBlocks){let c=cS(bO(o,s,t),s,t,"unsafe_to_truncate");o=c.messages,s=c.originalIndexes}let i=r.protectLatestTypedUser?sa(o):-1,a=r.protectLiveTailFromDrop?Eu(o):o.length;if(r.dropUnsafeOutsideLiveTail){let c=cS(SO(o,s,t,i,a,r),s,t);o=c.messages,s=c.originalIndexes}let d=oa(o,e.estimateMessageTokens);if(d<=e.targetTokens)return{status:"ok",messages:o,actions:t,liveTailHandling:t.length>0?"included_degraded":"included_verbatim",estimatedTokens:d,warnings:n};for(let c=o.length-1;c>=0&&d>e.targetTokens;c-=1){let u=sa(o);if(c===u)continue;if(r.protectLiveTailFromDrop&&c>=Eu(o))continue;if(!wO(o[c]))continue;let l=Dt(o[c]),p=Math.max(1,l/Math.max(1,e.estimateMessageTokens(o[c]))),m=Math.max(16,Math.floor(e.targetTokens*p/Math.max(1,o.length)));o[c]=TO(o[c],m),t.push({kind:"truncated_text",path:{messageIndex:s[c]},reason:"over_budget",originalSize:l,finalSize:Dt(o[c])}),d=oa(o,e.estimateMessageTokens)}for(let c=0;c<o.length&&d>e.targetTokens;){let u=pO(o),l=sa(o),p=r.protectLiveTailFromDrop?Eu(o):o.length;if(c===u||c===l){t.push({kind:"preserved",path:{messageIndex:s[c]},reason:"protected_live_tail",originalSize:Dt(o[c]),finalSize:Dt(o[c])}),c+=1;continue}let m=gO(o,c);if(lS(m,u)){c+=1;continue}if(lS(m,l)){c+=1;continue}if(CO(m,p)){c+=1;continue}for(let f of m)t.push({kind:"dropped_message",path:{messageIndex:s[f]},reason:m.size>1||Pu(o[f]).size>0?"tool_pair_boundary":"over_budget",originalSize:Dt(o[f]),finalSize:0});let g=kO(o,s,m);o=g.messages,s=g.originalIndexes,d=oa(o,e.estimateMessageTokens)}if(d>e.targetTokens)return n.push({code:"budget_unachievable_with_protections",message:"Projection could not reach budget without violating protected content."}),{status:"failed",messages:o,actions:t,liveTailHandling:"included_degraded",estimatedTokens:d,warnings:n};return{status:"ok",messages:o,actions:t,liveTailHandling:t.length>0?"included_degraded":"included_verbatim",estimatedTokens:d,warnings:n}}import{CHARS_PER_TOKEN as n5,estimateTokens as aa}from"@cline/shared";var hS=128000,IO=0.9,zn=0.9,yS=4,SS=0.7,bS=20000,mS=8192,gS=2000,vS=2000;function ia(e){return typeof e==="number"&&Number.isFinite(e)&&e>0}function ss(e){let t=ia(e.contextWindow)?e.contextWindow:void 0,n=ia(e.maxInputTokens)?e.maxInputTokens:void 0;if(n!==void 0)return t===void 0?n:Math.min(n,t);return t===void 0?void 0:t*IO}function os(e,t){if(e.length<=t)return e;return`${e.slice(0,t)}
359
+ ...[truncated ${e.length-r} chars]`;return`${e.slice(0,r)}${o}`}function uS(e,t){if(typeof e==="string")return Vr(e,t);let n=t;return e.map((r)=>{if(n<=0){if(r.type==="text")return{...r,text:""};if(r.type==="file")return{...r,content:""};return r}if(r.type==="text"){let o=Vr(r.text,n);return n-=o.length,{...r,text:o}}if(r.type==="file"){let o=Vr(r.content,n);return n-=o.length,{...r,content:o}}return r})}function vO(e){if(typeof e==="string")return e.length;return e.reduce((t,n)=>{if(n.type==="text")return t+n.text.length;if(n.type==="file")return t+n.content.length;return t},0)}function TO(e,t){if(typeof e.content==="string")return{...e,content:Vr(e.content,t)};let n=t;return{...e,content:e.content.map((r)=>{if(n<=0){if(r.type==="text")return{...r,text:""};if(r.type==="file")return{...r,content:""};if(r.type==="tool_result")return{...r,content:uS(r.content,0)};return r}if(r.type==="text"){let o=Vr(r.text,n);return n-=o.length,{...r,text:o}}if(r.type==="file"){let o=Vr(r.content,n);return n-=o.length,{...r,content:o}}if(r.type==="tool_result"){let o=uS(r.content,n);return n-=vO(o),{...r,content:o}}return r})}}function wO(e){if(typeof e.content==="string")return e.content.length>0;return e.content.some((t)=>t.type==="text"||t.type==="file"||t.type==="tool_result")}function kO(e,t,n){return{messages:e.filter((r,o)=>!n.has(o)),originalIndexes:t.filter((r,o)=>!n.has(o))}}function CO(e,t){if(t<0)return!1;for(let n of e)if(n>=t)return!0;return!1}function lS(e,t){return t>=0&&e.has(t)}function ts(e){let t=[],n=[],r=lO(e.policyIntent);if(e.targetTokens<=0)return{status:"failed",messages:dS(e.messages),actions:t,liveTailHandling:"preserved_out_of_band",estimatedTokens:oa(e.messages,e.estimateMessageTokens),warnings:[{code:"budget_impossible",message:"Target budget must be greater than zero."}]};let o=dS(e.messages),s=o.map((c,u)=>u);if(r.dropThinkingBlocks){let c=cS(bO(o,s,t),s,t,"unsafe_to_truncate");o=c.messages,s=c.originalIndexes}let i=r.protectLatestTypedUser?sa(o):-1,a=r.protectLiveTailFromDrop?Eu(o):o.length;if(r.dropUnsafeOutsideLiveTail){let c=cS(SO(o,s,t,i,a,r),s,t);o=c.messages,s=c.originalIndexes}let d=oa(o,e.estimateMessageTokens);if(d<=e.targetTokens)return{status:"ok",messages:o,actions:t,liveTailHandling:t.length>0?"included_degraded":"included_verbatim",estimatedTokens:d,warnings:n};for(let c=o.length-1;c>=0&&d>e.targetTokens;c-=1){let u=sa(o);if(c===u)continue;if(r.protectLiveTailFromDrop&&c>=Eu(o))continue;if(!wO(o[c]))continue;let l=Dt(o[c]),p=Math.max(1,l/Math.max(1,e.estimateMessageTokens(o[c]))),m=Math.max(16,Math.floor(e.targetTokens*p/Math.max(1,o.length)));o[c]=TO(o[c],m),t.push({kind:"truncated_text",path:{messageIndex:s[c]},reason:"over_budget",originalSize:l,finalSize:Dt(o[c])}),d=oa(o,e.estimateMessageTokens)}for(let c=0;c<o.length&&d>e.targetTokens;){let u=pO(o),l=sa(o),p=r.protectLiveTailFromDrop?Eu(o):o.length;if(c===u||c===l){t.push({kind:"preserved",path:{messageIndex:s[c]},reason:"protected_live_tail",originalSize:Dt(o[c]),finalSize:Dt(o[c])}),c+=1;continue}let m=gO(o,c);if(lS(m,u)){c+=1;continue}if(lS(m,l)){c+=1;continue}if(CO(m,p)){c+=1;continue}for(let f of m)t.push({kind:"dropped_message",path:{messageIndex:s[f]},reason:m.size>1||Pu(o[f]).size>0?"tool_pair_boundary":"over_budget",originalSize:Dt(o[f]),finalSize:0});let g=kO(o,s,m);o=g.messages,s=g.originalIndexes,d=oa(o,e.estimateMessageTokens)}if(d>e.targetTokens)return n.push({code:"budget_unachievable_with_protections",message:"Projection could not reach budget without violating protected content."}),{status:"failed",messages:o,actions:t,liveTailHandling:"included_degraded",estimatedTokens:d,warnings:n};return{status:"ok",messages:o,actions:t,liveTailHandling:t.length>0?"included_degraded":"included_verbatim",estimatedTokens:d,warnings:n}}import{CHARS_PER_TOKEN as n8,estimateTokens as aa}from"@cline/shared";var hS=128000,IO=0.9,zn=0.9,yS=4,SS=0.7,bS=20000,mS=8192,gS=2000,vS=2000;function ia(e){return typeof e==="number"&&Number.isFinite(e)&&e>0}function ss(e){let t=ia(e.contextWindow)?e.contextWindow:void 0,n=ia(e.maxInputTokens)?e.maxInputTokens:void 0;if(n!==void 0)return t===void 0?n:Math.min(n,t);return t===void 0?void 0:t*IO}function os(e,t){if(e.length<=t)return e;return`${e.slice(0,t)}
360
360
  ...[truncated ${e.length-t} chars]`}function AO(e){let t=RO(e);if(typeof t==="string")return t;return t.map((n)=>{switch(n.type){case"text":return n.text;case"file":return`<file path="${n.path}">
361
361
  ${n.content}
362
362
  </file>`;case"image":return`[image:${n.mediaType}]`;default:return""}}).join(`
@@ -419,7 +419,7 @@ ${IS(e)}${n}</SYSTEM_NOTICE>`}}function ca(e,t){if(typeof e.content==="string")r
419
419
  IMPORTANT: verify by EXECUTION, not by assumption. Before setting 'true' you must have observed evidence in this session that your solution works:
420
420
  - If the task provides or references specific tests, run those exact test(s) and include the passing output in your reasoning. If they still fail, revise and re-run.
421
421
  - If no tests are provided, construct your own check: actually run the program, script, or command you produced; confirm every required output file exists at the exact path requested; and confirm its contents match the required format, data types, and values. Read the output back as evidence.
422
- Phrases like "assume it works", "should be correct", or "probably fine" are NOT verification. Do NOT set 'true' unless your tool output shows the requirements are met; if you cannot obtain such evidence, set 'false'.`)});function Vn(e){if(e instanceof Error)return e.message;return String(e)}function tb(e){if(typeof e.old_text==="string"&&e.old_text.length>mn)return`Editor input too large: old_text was ${e.old_text.length} characters, exceeding the recommended limit of ${mn}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if(e.new_text.length>mn)return`Editor input too large: new_text was ${e.new_text.length} characters, exceeding the recommended limit of ${mn}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class Jr extends Error{timeoutMs;constructor(e,t){super(e);this.name="TimeoutError",this.timeoutMs=t}}function Yt(e,t,n){return Promise.race([e,new Promise((r,o)=>{setTimeout(()=>o(new Jr(n,t)),t)})])}function ka(e){let{path:t,start_line:n,end_line:r}=e;if(n==null&&r==null)return t;return`${t}:${n??1}-${r??"EOF"}`}function nb(e){let{start_line:t,end_line:n}=e;if(t==null||n==null||t<=n)return null;return`start_line must be less than or equal to end_line (received start_line: ${t}, end_line: ${n})`}var bL=new Set(["start_line","end_line"]);function vL(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=Object.keys(e);return t.length>0&&t.every((n)=>bL.has(n))}function eb(e){let t=[];for(let n of e){if(vL(n)){let r=t[t.length-1];if(typeof r==="string"){t[t.length-1]={path:r,...n};continue}if(r!==null&&typeof r==="object"&&!Array.isArray(r)&&"path"in r&&Object.keys(n).every((o)=>!(o in r))){t[t.length-1]={...r,...n};continue}}t.push(n)}return t}function rb(e){if(Array.isArray(e))return eb(e);if(e!==null&&typeof e==="object")for(let t of["files","paths"]){let n=e[t];if(Array.isArray(n))return{...e,[t]:eb(n)}}return e}function Ca(e){let t=SL(YS,e);if(typeof t==="string")return[t];if(Array.isArray(t))return t;if("commands"in t)return Array.isArray(t.commands)?t.commands:[t.commands];if("command"in t)return"args"in t?[t]:[t.command];if("cmd"in t)return[t.cmd];return[t]}function TL(e){if(typeof e==="string")return e;let t=e.args??[];if(t.length===0)return e.command;let n=t.map((r)=>/[\s"]/u.test(r)?JSON.stringify(r):r);return`${e.command} ${n.join(" ")}`}var Wu=200;function ob(e){let t=TL(e);if(t.length<=Wu)return t;let n=t.length-Wu;return`${t.slice(0,Wu)} ... [command truncated: ${n} more chars; full command is in the tool call input]`}var sb="core.plan-mode-command-guard";function ju(e={}){return{name:sb,manifest:{capabilities:["hooks"]},hooks:{beforeTool:(n)=>{if(n.tool.name!==Ie.RUN_COMMANDS)return;let r;try{r=Ca(n.input)}catch{return}for(let o of r){let s=zS(o);if(s)return ff(e.telemetry,{tool_name:"run_commands",blocked_construct:s,command_count:r.length,agent_id:n.snapshot.agentId,conversation_id:n.snapshot.conversationId,run_id:n.snapshot.runId,iteration:n.snapshot.iteration,tool_call_id:n.toolCall.toolCallId}),{skip:!0,reason:KS(s)}}return}}}}import{createTool as hn,getDefaultShell as GL,getPowerShellEdition as VL,getShellKind as XL,validateWithZod as yn,zodToJsonSchema as Qt}from"@cline/shared";import{spawn as db}from"node:child_process";import{randomUUID as fb}from"node:crypto";import{createWriteStream as EL,existsSync as PL,mkdtempSync as _L,renameSync as cb,rmSync as _a,writeFileSync as xL}from"node:fs";import{readdir as ML,readFile as OL,rm as Ea,stat as ub}from"node:fs/promises";import{tmpdir as hb}from"node:os";import{join as fn}from"node:path";import{StringDecoder as LL}from"node:string_decoder";import{getDefaultShell as NL,getShellInvocation as DL}from"@cline/shared";import{execFile as wL,spawnSync as O5}from"node:child_process";import{readFile as ib}from"node:fs/promises";var kL=2000,CL=4096;function IL(e){if(process.platform==="win32")return{file:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`]};return{file:"ps",args:["-p",String(e),"-o","lstart="],env:{...process.env,LC_ALL:"C",TZ:"UTC"}}}function ab(e){if(!Number.isSafeInteger(e)||e<=0)return"missing";try{return process.kill(e,0),"running"}catch(t){let n=t instanceof Error&&"code"in t?String(t.code):void 0;if(n==="ESRCH")return"missing";if(n==="EPERM")return"running";return"unavailable"}}function qu(e){return ab(e)==="missing"?{status:"missing"}:{status:"unavailable"}}function AL(e){let t=e.trim();return t?{status:"found",token:`${process.platform}:${t}`}:void 0}function RL(e){let t=e.lastIndexOf(")");if(t<0)return{status:"unavailable"};let n=e.slice(t+1).trim().split(/\s+/);if(["Z","X","x"].includes(n[0]??""))return{status:"missing"};let r=n[19];return r&&/^\d+$/.test(r)?{status:"running",startTime:r}:{status:"unavailable"}}async function Ia(e){if(!Number.isSafeInteger(e)||e<=0)return{status:"missing"};if(process.platform==="linux"){let n;try{n=await ib(`/proc/${e}/stat`,"utf8")}catch{return qu(e)}let r=RL(n);if(r.status!=="running")return r;try{let o=(await ib("/proc/sys/kernel/random/boot_id","utf8")).trim();return o?{status:"found",token:`linux:${o}:${r.startTime}`}:{status:"unavailable"}}catch{return{status:"unavailable"}}}let t=ab(e);if(t!=="running")return{status:t};try{let n=IL(e);return await new Promise((r)=>{wL(n.file,n.args,{encoding:"utf8",env:n.env,maxBuffer:CL,timeout:kL,windowsHide:!0},(o,s)=>{let i=!o&&typeof s==="string"?AL(s):void 0;r(i??qu(e))})})}catch{return qu(e)}}var gn=48000;function Aa(e,t={}){let n=t.maxChars??48000,r=t.totalChars??e.length;if(e.length<=n&&r<=n)return e;let o=Math.ceil(n/2),s=Math.max(1,n-o);return`${e.slice(0,o)}
422
+ Phrases like "assume it works", "should be correct", or "probably fine" are NOT verification. Do NOT set 'true' unless your tool output shows the requirements are met; if you cannot obtain such evidence, set 'false'.`)});function Vn(e){if(e instanceof Error)return e.message;return String(e)}function tb(e){if(typeof e.old_text==="string"&&e.old_text.length>mn)return`Editor input too large: old_text was ${e.old_text.length} characters, exceeding the recommended limit of ${mn}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if(e.new_text.length>mn)return`Editor input too large: new_text was ${e.new_text.length} characters, exceeding the recommended limit of ${mn}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class Jr extends Error{timeoutMs;constructor(e,t){super(e);this.name="TimeoutError",this.timeoutMs=t}}function Yt(e,t,n){return Promise.race([e,new Promise((r,o)=>{setTimeout(()=>o(new Jr(n,t)),t)})])}function ka(e){let{path:t,start_line:n,end_line:r}=e;if(n==null&&r==null)return t;return`${t}:${n??1}-${r??"EOF"}`}function nb(e){let{start_line:t,end_line:n}=e;if(t==null||n==null||t<=n)return null;return`start_line must be less than or equal to end_line (received start_line: ${t}, end_line: ${n})`}var bL=new Set(["start_line","end_line"]);function vL(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=Object.keys(e);return t.length>0&&t.every((n)=>bL.has(n))}function eb(e){let t=[];for(let n of e){if(vL(n)){let r=t[t.length-1];if(typeof r==="string"){t[t.length-1]={path:r,...n};continue}if(r!==null&&typeof r==="object"&&!Array.isArray(r)&&"path"in r&&Object.keys(n).every((o)=>!(o in r))){t[t.length-1]={...r,...n};continue}}t.push(n)}return t}function rb(e){if(Array.isArray(e))return eb(e);if(e!==null&&typeof e==="object")for(let t of["files","paths"]){let n=e[t];if(Array.isArray(n))return{...e,[t]:eb(n)}}return e}function Ca(e){let t=SL(YS,e);if(typeof t==="string")return[t];if(Array.isArray(t))return t;if("commands"in t)return Array.isArray(t.commands)?t.commands:[t.commands];if("command"in t)return"args"in t?[t]:[t.command];if("cmd"in t)return[t.cmd];return[t]}function TL(e){if(typeof e==="string")return e;let t=e.args??[];if(t.length===0)return e.command;let n=t.map((r)=>/[\s"]/u.test(r)?JSON.stringify(r):r);return`${e.command} ${n.join(" ")}`}var Wu=200;function ob(e){let t=TL(e);if(t.length<=Wu)return t;let n=t.length-Wu;return`${t.slice(0,Wu)} ... [command truncated: ${n} more chars; full command is in the tool call input]`}var sb="core.plan-mode-command-guard";function ju(e={}){return{name:sb,manifest:{capabilities:["hooks"]},hooks:{beforeTool:(n)=>{if(n.tool.name!==Ie.RUN_COMMANDS)return;let r;try{r=Ca(n.input)}catch{return}for(let o of r){let s=zS(o);if(s)return ff(e.telemetry,{tool_name:"run_commands",blocked_construct:s,command_count:r.length,agent_id:n.snapshot.agentId,conversation_id:n.snapshot.conversationId,run_id:n.snapshot.runId,iteration:n.snapshot.iteration,tool_call_id:n.toolCall.toolCallId}),{skip:!0,reason:KS(s)}}return}}}}import{createTool as hn,getDefaultShell as GL,getPowerShellEdition as VL,getShellKind as XL,validateWithZod as yn,zodToJsonSchema as Qt}from"@cline/shared";import{spawn as db}from"node:child_process";import{randomUUID as fb}from"node:crypto";import{createWriteStream as EL,existsSync as PL,mkdtempSync as _L,renameSync as cb,rmSync as _a,writeFileSync as xL}from"node:fs";import{readdir as ML,readFile as OL,rm as Ea,stat as ub}from"node:fs/promises";import{tmpdir as hb}from"node:os";import{join as fn}from"node:path";import{StringDecoder as LL}from"node:string_decoder";import{getDefaultShell as NL,getShellInvocation as DL}from"@cline/shared";import{execFile as wL,spawnSync as O8}from"node:child_process";import{readFile as ib}from"node:fs/promises";var kL=2000,CL=4096;function IL(e){if(process.platform==="win32")return{file:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`]};return{file:"ps",args:["-p",String(e),"-o","lstart="],env:{...process.env,LC_ALL:"C",TZ:"UTC"}}}function ab(e){if(!Number.isSafeInteger(e)||e<=0)return"missing";try{return process.kill(e,0),"running"}catch(t){let n=t instanceof Error&&"code"in t?String(t.code):void 0;if(n==="ESRCH")return"missing";if(n==="EPERM")return"running";return"unavailable"}}function qu(e){return ab(e)==="missing"?{status:"missing"}:{status:"unavailable"}}function AL(e){let t=e.trim();return t?{status:"found",token:`${process.platform}:${t}`}:void 0}function RL(e){let t=e.lastIndexOf(")");if(t<0)return{status:"unavailable"};let n=e.slice(t+1).trim().split(/\s+/);if(["Z","X","x"].includes(n[0]??""))return{status:"missing"};let r=n[19];return r&&/^\d+$/.test(r)?{status:"running",startTime:r}:{status:"unavailable"}}async function Ia(e){if(!Number.isSafeInteger(e)||e<=0)return{status:"missing"};if(process.platform==="linux"){let n;try{n=await ib(`/proc/${e}/stat`,"utf8")}catch{return qu(e)}let r=RL(n);if(r.status!=="running")return r;try{let o=(await ib("/proc/sys/kernel/random/boot_id","utf8")).trim();return o?{status:"found",token:`linux:${o}:${r.startTime}`}:{status:"unavailable"}}catch{return{status:"unavailable"}}}let t=ab(e);if(t!=="running")return{status:t};try{let n=IL(e);return await new Promise((r)=>{wL(n.file,n.args,{encoding:"utf8",env:n.env,maxBuffer:CL,timeout:kL,windowsHide:!0},(o,s)=>{let i=!o&&typeof s==="string"?AL(s):void 0;r(i??qu(e))})})}catch{return qu(e)}}var gn=48000;function Aa(e,t={}){let n=t.maxChars??48000,r=t.totalChars??e.length;if(e.length<=n&&r<=n)return e;let o=Math.ceil(n/2),s=Math.max(1,n-o);return`${e.slice(0,o)}
423
423
  [... output truncated: ${r} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
424
424
  `+e.slice(-s)}var Yr=2000,as=2000,Ra=48000,Qr=48000;var lb=10485760,HL=86400000,UL=60000,yb="cline-command-",Sb="output.log",bb="active-command.json",vb="completed-at",FL=48,BL=1000;function Tb(e){return typeof e==="number"&&Number.isFinite(e)?Math.max(0,e):HL}function $L(e){return typeof e==="number"&&Number.isFinite(e)?Math.max(1,e):UL}function WL(e){try{let t=JSON.parse(e);if(t.version!==1||typeof t.executionId!=="string"||t.executionId.length===0||!Number.isSafeInteger(t.pid)||(t.pid??0)<=0||typeof t.processStartToken!=="string"||t.processStartToken.length===0||typeof t.detachedAtMs!=="number"||!Number.isFinite(t.detachedAtMs)||t.detachedAtMs<0)return;return t}catch{return}}function zu(e,t){let n=`${e}.${fb()}.tmp`;try{xL(n,t,"utf8");try{cb(n,e)}catch(r){if(r instanceof Error&&"code"in r&&["EEXIST","EPERM"].includes(String(r.code)))_a(e,{force:!0}),cb(n,e);else throw r}}finally{_a(n,{force:!0})}}function jL(e,t){let n=e?.trim();if(!n)return;let r=Number(n);if(!Number.isFinite(r)||r<0)return;return Math.min(r,t)}async function pb(e){try{return await OL(e,"utf8")}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}}async function wb(e,t){let n=fn(e,bb),r=fn(e,vb),o=await pb(r),s=jL(o,t.nowMs),i=await pb(n);if(s!==void 0){if(i!==void 0)await Ea(n,{force:!0})}else if(i!==void 0){let d=WL(i);if(d){let c;try{c=await t.probeProcessStartToken(d.pid)}catch{c={status:"unavailable"}}if(c.status==="found"&&c.token===d.processStartToken)return mb(e,t),!1;if(c.status==="unavailable")return mb(e,t),!1}zu(r,String(t.nowMs)),await Ea(n,{force:!0}),s=t.nowMs}if(s===void 0)try{s=(await ub(fn(e,Sb))).mtimeMs}catch{s=(await ub(e)).mtimeMs}let a=t.nowMs-t.retentionMs;if(s>a)return Cb(e,Math.max(0,s+t.retentionMs-t.nowMs)),!1;return await Ea(e,{recursive:!0,force:!0}),!0}function mb(e,t,n=t.activeCommandPollIntervalMs){setTimeout(()=>{wb(e,{...t,nowMs:Date.now()}).catch(()=>{return})},n).unref()}async function kb(e={}){let t=e.tempDirectory??hb(),n=Tb(e.retentionMs),r=e.nowMs??Date.now(),o=e.processStartTokenProbe??Ia,s=$L(e.activeCommandPollIntervalMs),i;try{i=await ML(t,{withFileTypes:!0})}catch{return 0}let a=0;for(let d of i){if(!d.isDirectory()||!d.name.startsWith(yb))continue;let c=fn(t,d.name);try{if(await wb(c,{retentionMs:n,nowMs:r,probeProcessStartToken:o,activeCommandPollIntervalMs:s}))a+=1}catch{}}return a}class Zr extends Error{exitCode;output;constructor(e,t){super(`Command exited with code ${e}`);this.exitCode=e;this.output=t;this.name="CommandExitError"}}function Pa(e,t){if(e!==null)return`Command exited with code ${e}`;return t?`Command terminated by signal ${t}`:"Command terminated without an exit code"}class eo extends Error{signal;output;constructor(e,t){super(Pa(null,e));this.signal=e;this.output=t;this.name="CommandTerminationError"}}class xa extends Error{code;missing;constructor(e,t={}){super(`Failed to execute command: ${e.message}`);this.name="CommandSpawnError";let n=e.code;if(this.code=typeof n==="string"?n:void 0,this.code!=="ENOENT")this.missing=void 0;else if(t.cwd!==void 0&&!PL(t.cwd))this.missing="cwd";else this.missing="executable"}}function gb(e){let t=Math.ceil(e/2),n=Math.max(1,e-t),r=new LL("utf8"),o="",s="",i=0,a=(d)=>{if(!d)return;i+=d.length;let c=t-o.length;if(c>0){o+=d.slice(0,c),s=(s+d.slice(c)).slice(-n);return}s=(s+d).slice(-n)};return{append(d){let c=r.write(d);return a(c),c},current(){return{text:o+s,totalChars:i,dropped:i>o.length+s.length}},snapshot(){let d=r.end();return a(d),{text:o+s,totalChars:i,dropped:i>o.length+s.length,finalChunk:d}}}}function qL(e,t,n,r){let o=e.emitUpdate,s=typeof r==="number"&&Number.isFinite(r)?Math.max(1,Math.floor(Math.min(gn,r))):gn,i={},a=[],d,c=!1,u=()=>{if(!d)return;clearTimeout(d),d=void 0},l=()=>{if(u(),!o){i={},a=[];return}let m=i,g=a;i={},a=[];for(let f of g){let h=m[f];if(!h?.chunk)continue;let S=h.droppedChars>0?`\x1B[0m[${h.droppedChars} command-output characters skipped while streaming]
425
425
  `:"",b=S.length<s?S+h.chunk.slice(-(s-S.length)):h.chunk.slice(-s);o({stream:f,chunk:b,executionId:t,detachable:n(),...h.droppedChars>0?{truncated:!0,droppedChars:h.droppedChars}:{}})}},p=()=>{if(!o||d||c)return;d=setTimeout(l,FL),d.unref()};return{append(m,g){if(!o||c||!g)return;let f=i[m];if(!f)f={chunk:"",droppedChars:0},i[m]=f,a.push(m);if(g.length>=s)f.droppedChars+=f.chunk.length+g.length-s,f.chunk=g.slice(-s);else{let h=f.chunk.length+g.length-s;if(h>0)f.droppedChars+=h,f.chunk=f.chunk.slice(h);f.chunk+=g}p()},flush:l,stop(m={}){if(c)return;if(m.flush)l();else u(),i={},a=[];c=!0}}}function Cb(e,t){setTimeout(()=>{Ea(e,{recursive:!0,force:!0}).catch(()=>{return})},t).unref()}function zL(e,t){let n=_L(fn(hb(),yb)),r=fn(n,Sb),o=fn(n,bb),s=fn(n,vb);try{zu(o,`${JSON.stringify(t)}
@@ -1086,4 +1086,4 @@ Connection: close\r
1086
1086
  Content-Length: 0\r
1087
1087
  \r
1088
1088
  `),e.end()}catch{e.destroy()}}function yc(e,t){if(!e||!t)return!1;let n=Buffer.from(e,"utf8"),r=Buffer.from(t,"utf8");return n.length===r.length&&XV(n,r)}function VA(e,t){let n=e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"?e.code:void 0,r=e instanceof Error?e.message:typeof e==="string"?e:"Unknown startup error",o=`Failed to start hub server on ${t.host}:${t.port}${t.pathname}: ${r}`,s=Error(n?`${o} (${n})`:o);if(n)e.code=n,s.code=n;if(e instanceof Error&&e.stack)s.stack=`${s.name}: ${s.message}
1089
- Caused by: ${e.stack}`;return s}function rX(e){return e instanceof Error&&"code"in e&&e.code==="EADDRINUSE"}function XA(e,t,n,r){try{let o=new Ci(e),s=new Ci(Xt(t,n===0?1:n,r));return o.protocol===s.protocol&&o.hostname===s.hostname&&o.pathname===s.pathname&&(n===0||o.port===s.port)}catch{return!1}}function JA(e,t,n){return Error(`Hub owner ${e} is already running at ${t}; refusing a second endpoint at ${n}`)}var an=new Map,YA="cline-hub-auth.",oX=30000,QA=2000,sX=3000,iX=100;async function ZA(e,t){let n;try{return await Promise.race([e.then(()=>!0,()=>!0),new Promise((r)=>{n=setTimeout(()=>r(!1),t)})])}finally{if(n)clearTimeout(n)}}function Kg(e){return Array.isArray(e)?e.join(","):e??""}function eR(e){return e===32||e===9}function zg(e){let t=Kg(e).trim(),n="bearer";if(t.length<=6||t.slice(0,6).toLowerCase()!=="bearer"||!eR(t.charCodeAt(6)))return null;let r=7;while(r<t.length&&eR(t.charCodeAt(r)))r+=1;return t.slice(r).trim()||null}function aX(e){for(let t of Kg(e).split(",")){let n=t.trim();if(n.startsWith(YA))return n.slice(YA.length).trim()||null}return null}function nR(e){let t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function dX(e){let t=Kg(e).trim();if(!t)return!1;try{return nR(new Ci(t).hostname)}catch{return!1}}async function Gg(e){let t=e.owner??Un(),n=e.host??"127.0.0.1",r=e.pathname??"/hub",s=e.port??Ki(),i=s,a=Xt(n,s,r),d=Mt(),c=Jc(),u=Qh(),l=Ao.acquire(qA(t.discoveryPath));if(!l.held)K("warn","instance_lock.unavailable",{lockFile:l.lockFile});let p;try{p=new hc({...e,owner:t}),await p.start()}catch(_){throw l.release(),_}let m=p.getHubId(),g=new Wg(new jg(p),e.telemetry,e.workspaceRoot),f=new Set,h=new Date().toISOString(),S={protocolVersion:qg,minClientProtocolVersion:GA,maxClientProtocolVersion:KA,capabilities:YV,coreVersion:ln.version,buildId:d,buildEpochMs:c,pid:process.pid,startedAt:h},y=new Set,b,k,v,T=!1,w=()=>{if(k)return k;if(v){let M=an.get(t.discoveryPath);if(M?.server===v)M.state="closing"}if(b)clearInterval(b),b=void 0;let _=new Promise((M,re)=>{C.close((W)=>{if(W){re(W);return}M()})}),x=new Promise((M,re)=>{B.close((W)=>{if(W){re(W);return}M()})}),G=Promise.resolve().then(()=>p.stop()),E=G.then(async()=>{await Zh(t.discoveryPath,m)}),j=(async()=>{let re=(await Promise.allSettled([_,x,G,E])).flatMap((W)=>W.status==="rejected"?[W.reason]:[]);if(re.length>0)throw AggregateError(re,"hub server close failed")})().finally(()=>{if(an.get(t.discoveryPath)?.server===v)an.delete(t.discoveryPath);l.release()});k={transportStopped:G,closed:j};for(let M of y)M.terminate?.();y.clear();for(let M of f)M();return f.clear(),k},I=()=>w().closed,B=JV.createServer((_,x)=>{if(!T){x.statusCode=503,x.end("Starting");return}if((_.url??"/")==="/health"){let E=JSON.stringify({ok:!0,protocolVersion:S.protocolVersion,minClientProtocolVersion:S.minClientProtocolVersion,maxClientProtocolVersion:S.maxClientProtocolVersion,coreVersion:S.coreVersion,buildId:S.buildId,buildEpochMs:S.buildEpochMs,draining:p.isDraining(),host:n,port:i,url:a});x.statusCode=200,x.setHeader("content-type","application/json"),x.end(E);return}if((_.url??"/")==="/status"){if(!yc(zg(_.headers.authorization),u)){x.statusCode=401,x.end("Unauthorized");return}let E=JSON.stringify({hubId:m,...S,authToken:u,host:n,port:i,url:a,updatedAt:new Date().toISOString()});x.statusCode=200,x.setHeader("content-type","application/json"),x.end(E);return}if((_.url??"/")==="/version"){x.statusCode=200,x.setHeader("content-type","application/json"),x.end(JSON.stringify(S));return}let G=new Ci(_.url??"/",`http://${n}:${i}`);if(G.pathname==="/drain"&&_.method==="POST"){if(!yc(zg(_.headers.authorization),u)){x.statusCode=401,x.end("Unauthorized");return}let E=G.searchParams.get("off")===null;p.handleCommand({version:qg,command:"hub.drain",payload:{draining:E,reason:G.searchParams.get("reason")??"authenticated HTTP drain request"}}).then((j)=>{x.statusCode=j.ok?200:500,x.setHeader("content-type","application/json"),x.end(JSON.stringify(j.payload??{ok:j.ok}))},()=>{x.statusCode=500,x.end("Drain failed")});return}if(G.pathname==="/shutdown"&&_.method==="POST"){if(!yc(zg(_.headers.authorization),u)){x.statusCode=401,x.end("Unauthorized");return}let E=!1,j=()=>{if(E)return;E=!0;try{Promise.resolve(e.onShutdownRequested?.()).catch(()=>{return})}catch{}finally{I().catch(()=>{return})}};x.statusCode=202,x.setHeader("content-type","application/json"),x.setHeader("connection","close");let M=setTimeout(j,1000);M.unref?.(),x.end(JSON.stringify({ok:!0}),()=>{setImmediate(()=>{clearTimeout(M),j()})});return}x.statusCode=404,x.end("Not found")}),C=new QV({noServer:!0});b=setInterval(()=>{for(let _ of y){if(_.isAlive===!1){_.heartbeatTerminated=!0;try{_.terminate?.()}catch{}y.delete(_);continue}_.isAlive=!1;try{_.ping?.()}catch{try{_.terminate?.()}catch{}y.delete(_)}}},oX),B.on("upgrade",(_,x,G)=>{if(!T){nX(x);return}if(new Ci(_.url??"/",`http://${n}:${i}`).pathname!==r){x.destroy();return}let j=yc(aX(_.headers["sec-websocket-protocol"]),u);if(!(j||nR(n)&&dX(_.headers.origin))){tX(x);return}try{C.handleUpgrade(_,x,G,(re)=>{let W=re;W.isAlive=!0,W.on("pong",()=>{W.isAlive=!0}),y.add(W),W.once("close",(U,q)=>{K("info","socket.closed",{code:U,reason:tR(q).slice(0,200)||void 0,heartbeatTerminated:W.heartbeatTerminated??!1,serverClosing:k!==void 0})});let N=g.attach(ZV(re),{allowRegisteredWorkspace:j});f.add(N),re.once("close",()=>{y.delete(W),N(),f.delete(N)})})}catch{eX(x)}});try{await new Promise((_,x)=>{B.once("error",(G)=>{x(VA(G,{host:n,port:s,pathname:r}))}),B.listen(s,n,()=>{let G=B.address();if(!G||typeof G==="string"){x(VA(Error("Failed to resolve hub port"),{host:n,port:s,pathname:r}));return}i=G.port,a=Xt(n,i,r),_()})})}catch(_){if(b)clearInterval(b),b=void 0;if(_ instanceof Error)_.hubInstanceLockHeld=l.held;throw await ZA(Promise.resolve().then(()=>p.stop()),QA),l.release(),_}try{await qi(t.discoveryPath,{hubId:m,protocolVersion:qg,minClientProtocolVersion:GA,maxClientProtocolVersion:KA,capabilities:[...S.capabilities],coreVersion:ln.version,buildId:d,buildEpochMs:c,authToken:u,host:n,port:i,url:a,pid:process.pid,startedAt:h,updatedAt:h}),T=!0}catch(_){if(!await ZA(w().closed,QA))try{B.closeAllConnections(),B.unref()}catch{}throw _}return v={host:n,port:i,url:a,authToken:u,beginClose:w,close:I},v}async function rR(e){let t=e.owner??Un(),n=e.host!==void 0||e.port!==void 0||e.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),r=e.host??"127.0.0.1",o=e.port??Ki(),s=e.pathname??"/hub",i=Xt(r,o,s),a=t.discoveryPath,d=(u)=>{if(!n)Ur(u.url,u.authToken);return u},c=an.get(a);if(c){let u=await c.promise;if(c.state==="closing"){if(await u.beginClose().closed.catch(()=>{return}),an.get(a)===c)an.delete(a)}else if(XA(u.url,r,o,s)||e.allowPortFallback===!0)return d({server:u,url:u.url,authToken:u.authToken,action:"reuse"});else throw JA(t.ownerId,u.url,i)}return await zi(t.discoveryPath,async()=>{let u=await Re(t.discoveryPath);if(u?.url){let m=await Vt(u.url,{authToken:u.authToken});if(m?.url&&Nr(m)&&await dt(m.url,{authToken:u.authToken})){if(XA(u.url,r,o,s)||e.allowPortFallback===!0)return d({url:m.url,authToken:u.authToken,action:"reuse"});throw JA(t.ownerId,u.url,i)}if(m?.url){let g={url:m.url,authToken:u.authToken,pid:m.pid??u.pid};if(await tu(g)){if(await dt(m.url,{authToken:u.authToken}))return d({url:m.url,authToken:u.authToken,action:"reuse"})}else await Hr(g,t.discoveryPath)}else await Gt(t.discoveryPath)}let l=async(m)=>{let g=Gg({...m,owner:t}),f={promise:g,state:"starting"};an.set(a,f);try{let h=await g;return f.server=h,f.state="open",d({server:h,url:h.url,authToken:h.authToken,action:"started"})}catch(h){if(an.get(a)===f)an.delete(a);throw h}},p=Date.now()+sX;for(;;)try{return await l(e)}catch(m){if(jA(m)&&Date.now()<p){await new Promise((g)=>setTimeout(g,iX));continue}if(!e.allowPortFallback||!rX(m))throw m;return await l({...e,port:0})}})}function sR(){return oR()==="production"?Ot():vt()}function cX(e){return oR()!=="production"&&!e}async function kue(e){let t=Fn({host:e.host,port:e.port,pathname:e.pathname});return await Gg({...e,...t,owner:sR()})}async function Cue(e){let t=e.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),n=Fn({host:e.host,port:e.port,pathname:e.pathname});return await rR({...e,...n,allowPortFallback:e.allowPortFallback??cX(t),owner:sR()})}export{Wg as BrowserWebSocketHubAdapter,n_ as DEFAULT_HUB_HOST,o_ as DEFAULT_HUB_PATHNAME,r_ as DEFAULT_HUB_PORT,jce as HUB_LOCK_HELD_EXIT_CODE,Vi as HubCommandError,Ng as HubEventLogStore,Ao as HubInstanceLock,WA as HubLockHeldError,lc as HubRunAdmissionRejectedError,Pg as HubRunQueue,Ai as HubScheduleCommandService,Ni as HubScheduleService,hc as HubServerTransport,_x as HubSessionClient,Oe as HubTransportError,xx as HubUIClient,jg as NativeHubTransportAdapter,$n as NodeHubClient,Mr as ScheduledTaskInputSchema,Fh as TASKS_SYSTEM_PROMPT_RULE,Wo as TASKS_TOOL_NAME,$h as TasksToolInputSchema,RJ as __test__,Ax as checkManagedHubBuildMismatch,Gt as clearHubDiscovery,Zh as clearHubDiscoveryIfOwned,qo as compareHubBuilds,Ty as connectToHub,yP as createConfiguredTelemetryHandle,xh as createConfiguredTelemetryService,Qh as createHubAuthToken,Xt as createHubServerUrl,dJ as createInMemoryHubOwnerContext,lse as createLocalHubScheduleRuntimeHandlers,Kc as createTasksPromptExtension,zc as createTasksTool,au as ensureCompatibleLocalHubUrl,Go as ensureDetachedHubServer,Cue as ensureHubServer,rR as ensureHubWebSocketServer,Dc as executeScheduleOperation,Hn as getManagedHubCompatibility,FJ as hasActiveHubSessions,tu as hubHasLiveSessions,cJ as isDiscoveryFilePresent,UJ as isHubCommandTimeoutError,jA as isHubLockHeldError,rx as isHubReconnectableTransportError,nR as isLocalHubHostName,dX as isLocalHubOrigin,Nr as isManagedHubReusable,by as localHubHasNoActiveSessions,Xi as normalizeHubWebSocketUrl,EJ as prewarmDetachedHubServer,KJ as probeHubConnection,Vt as probeHubServer,Fr as queryHubSessionActivity,zg as readBearerToken,Re as readHubDiscovery,O_ as readSupersededHubDiscovery,Ur as rememberRecoverableLocalHubUrl,Bn as requestHubDrain,nu as requestHubShutdown,jo as resolveClineDataDir,iJ as resolveClineDir,dx as resolveCompatibleLocalHubUrl,s_ as resolveDefaultHubHost,i_ as resolveDefaultHubPathname,Ki as resolveDefaultHubPort,Jc as resolveHubBuildEpochMs,Mt as resolveHubBuildId,zo as resolveHubBuildIdentity,Fn as resolveHubEndpointOptions,kV as resolveHubEventLogPath,qA as resolveHubInstanceLockPath,Un as resolveHubOwnerContext,XG as resolveHubRunQueuePath,hx as resolveHubUrl,Ot as resolveProductionHubOwnerContext,vt as resolveSharedHubOwnerContext,hJ as resolveWorkspaceHubOwnerContext,BJ as restartLocalHubIfIdleAfterStartupTimeout,Hr as retireDiscoveredHub,GJ as sendHubCommand,F_ as spawnDetachedHubServer,B_ as spawnDetachedHubServerWithRetry,kue as startHubServer,Gg as startHubWebSocketServer,cx as stopLocalHubServerGracefully,Sy as summarizeHubSessionActivity,ty as toHubHealthUrl,XP as toHubStatusUrl,jm as truncateNotificationBody,PJ as upgradeManagedHub,dt as verifyHubConnection,eY as watchManagedHubBuildMismatch,zi as withHubStartupLock,qi as writeHubDiscovery};
1089
+ Caused by: ${e.stack}`;return s}function rX(e){return e instanceof Error&&"code"in e&&e.code==="EADDRINUSE"}function XA(e,t,n,r){try{let o=new Ci(e),s=new Ci(Xt(t,n===0?1:n,r));return o.protocol===s.protocol&&o.hostname===s.hostname&&o.pathname===s.pathname&&(n===0||o.port===s.port)}catch{return!1}}function JA(e,t,n){return Error(`Hub owner ${e} is already running at ${t}; refusing a second endpoint at ${n}`)}var an=new Map,YA="cline-hub-auth.",oX=30000,QA=2000,sX=3000,iX=100;async function ZA(e,t){let n;try{return await Promise.race([e.then(()=>!0,()=>!0),new Promise((r)=>{n=setTimeout(()=>r(!1),t)})])}finally{if(n)clearTimeout(n)}}function Kg(e){return Array.isArray(e)?e.join(","):e??""}function eR(e){return e===32||e===9}function zg(e){let t=Kg(e).trim(),n="bearer";if(t.length<=6||t.slice(0,6).toLowerCase()!=="bearer"||!eR(t.charCodeAt(6)))return null;let r=7;while(r<t.length&&eR(t.charCodeAt(r)))r+=1;return t.slice(r).trim()||null}function aX(e){for(let t of Kg(e).split(",")){let n=t.trim();if(n.startsWith(YA))return n.slice(YA.length).trim()||null}return null}function nR(e){let t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function dX(e){let t=Kg(e).trim();if(!t)return!1;try{return nR(new Ci(t).hostname)}catch{return!1}}async function Gg(e){let t=e.owner??Un(),n=e.host??"127.0.0.1",r=e.pathname??"/hub",s=e.port??Ki(),i=s,a=Xt(n,s,r),d=Mt(),c=Jc(),u=Qh(),l=Ao.acquire(qA(t.discoveryPath));if(!l.held)K("warn","instance_lock.unavailable",{lockFile:l.lockFile});let p;try{p=new hc({...e,owner:t}),await p.start()}catch(_){throw l.release(),_}let m=p.getHubId(),g=new Wg(new jg(p),e.telemetry,e.workspaceRoot),f=new Set,h=new Date().toISOString(),S={protocolVersion:qg,minClientProtocolVersion:GA,maxClientProtocolVersion:KA,capabilities:YV,coreVersion:ln.version,buildId:d,buildEpochMs:c,pid:process.pid,startedAt:h},y=new Set,b,k,v,T=!1,w=()=>{if(k)return k;if(v){let M=an.get(t.discoveryPath);if(M?.server===v)M.state="closing"}if(b)clearInterval(b),b=void 0;let _=new Promise((M,re)=>{C.close((W)=>{if(W){re(W);return}M()})}),x=new Promise((M,re)=>{B.close((W)=>{if(W){re(W);return}M()})}),G=Promise.resolve().then(()=>p.stop()),E=G.then(async()=>{await Zh(t.discoveryPath,m)}),j=(async()=>{let re=(await Promise.allSettled([_,x,G,E])).flatMap((W)=>W.status==="rejected"?[W.reason]:[]);if(re.length>0)throw AggregateError(re,"hub server close failed")})().finally(()=>{if(an.get(t.discoveryPath)?.server===v)an.delete(t.discoveryPath);l.release()});k={transportStopped:G,closed:j};for(let M of y)M.terminate?.();y.clear();for(let M of f)M();return f.clear(),k},I=()=>w().closed,B=JV.createServer((_,x)=>{if(!T){x.statusCode=503,x.end("Starting");return}if((_.url??"/")==="/health"){let E=JSON.stringify({ok:!0,protocolVersion:S.protocolVersion,minClientProtocolVersion:S.minClientProtocolVersion,maxClientProtocolVersion:S.maxClientProtocolVersion,coreVersion:S.coreVersion,buildId:S.buildId,buildEpochMs:S.buildEpochMs,draining:p.isDraining(),host:n,port:i,url:a});x.statusCode=200,x.setHeader("content-type","application/json"),x.end(E);return}if((_.url??"/")==="/status"){if(!yc(zg(_.headers.authorization),u)){x.statusCode=401,x.end("Unauthorized");return}let E=JSON.stringify({hubId:m,...S,authToken:u,host:n,port:i,url:a,updatedAt:new Date().toISOString()});x.statusCode=200,x.setHeader("content-type","application/json"),x.end(E);return}if((_.url??"/")==="/version"){x.statusCode=200,x.setHeader("content-type","application/json"),x.end(JSON.stringify(S));return}let G=new Ci(_.url??"/",`http://${n}:${i}`);if(G.pathname==="/drain"&&_.method==="POST"){if(!yc(zg(_.headers.authorization),u)){x.statusCode=401,x.end("Unauthorized");return}let E=G.searchParams.get("off")===null;p.handleCommand({version:qg,command:"hub.drain",payload:{draining:E,reason:G.searchParams.get("reason")??"authenticated HTTP drain request"}}).then((j)=>{x.statusCode=j.ok?200:500,x.setHeader("content-type","application/json"),x.end(JSON.stringify(j.payload??{ok:j.ok}))},()=>{x.statusCode=500,x.end("Drain failed")});return}if(G.pathname==="/shutdown"&&_.method==="POST"){if(!yc(zg(_.headers.authorization),u)){x.statusCode=401,x.end("Unauthorized");return}let E=!1,j=()=>{if(E)return;E=!0;try{Promise.resolve(e.onShutdownRequested?.()).catch(()=>{return})}catch{}finally{I().catch(()=>{return})}};x.statusCode=202,x.setHeader("content-type","application/json"),x.setHeader("connection","close");let M=setTimeout(j,1000);M.unref?.(),x.end(JSON.stringify({ok:!0}),()=>{setImmediate(()=>{clearTimeout(M),j()})});return}x.statusCode=404,x.end("Not found")}),C=new QV({noServer:!0});b=setInterval(()=>{for(let _ of y){if(_.isAlive===!1){_.heartbeatTerminated=!0;try{_.terminate?.()}catch{}y.delete(_);continue}_.isAlive=!1;try{_.ping?.()}catch{try{_.terminate?.()}catch{}y.delete(_)}}},oX),B.on("upgrade",(_,x,G)=>{if(!T){nX(x);return}if(new Ci(_.url??"/",`http://${n}:${i}`).pathname!==r){x.destroy();return}let j=yc(aX(_.headers["sec-websocket-protocol"]),u);if(!(j||nR(n)&&dX(_.headers.origin))){tX(x);return}try{C.handleUpgrade(_,x,G,(re)=>{let W=re;W.isAlive=!0,W.on("pong",()=>{W.isAlive=!0}),y.add(W),W.once("close",(U,q)=>{K("info","socket.closed",{code:U,reason:tR(q).slice(0,200)||void 0,heartbeatTerminated:W.heartbeatTerminated??!1,serverClosing:k!==void 0})});let N=g.attach(ZV(re),{allowRegisteredWorkspace:j});f.add(N),re.once("close",()=>{y.delete(W),N(),f.delete(N)})})}catch{eX(x)}});try{await new Promise((_,x)=>{B.once("error",(G)=>{x(VA(G,{host:n,port:s,pathname:r}))}),B.listen(s,n,()=>{let G=B.address();if(!G||typeof G==="string"){x(VA(Error("Failed to resolve hub port"),{host:n,port:s,pathname:r}));return}i=G.port,a=Xt(n,i,r),_()})})}catch(_){if(b)clearInterval(b),b=void 0;if(_ instanceof Error)_.hubInstanceLockHeld=l.held;throw await ZA(Promise.resolve().then(()=>p.stop()),QA),l.release(),_}try{await qi(t.discoveryPath,{hubId:m,protocolVersion:qg,minClientProtocolVersion:GA,maxClientProtocolVersion:KA,capabilities:[...S.capabilities],coreVersion:ln.version,buildId:d,buildEpochMs:c,authToken:u,host:n,port:i,url:a,pid:process.pid,startedAt:h,updatedAt:h}),T=!0}catch(_){if(!await ZA(w().closed,QA))try{B.closeAllConnections(),B.unref()}catch{}throw _}return v={host:n,port:i,url:a,authToken:u,beginClose:w,close:I},v}async function rR(e){let t=e.owner??Un(),n=e.host!==void 0||e.port!==void 0||e.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),r=e.host??"127.0.0.1",o=e.port??Ki(),s=e.pathname??"/hub",i=Xt(r,o,s),a=t.discoveryPath,d=(u)=>{if(!n)Ur(u.url,u.authToken);return u},c=an.get(a);if(c){let u=await c.promise;if(c.state==="closing"){if(await u.beginClose().closed.catch(()=>{return}),an.get(a)===c)an.delete(a)}else if(XA(u.url,r,o,s)||e.allowPortFallback===!0)return d({server:u,url:u.url,authToken:u.authToken,action:"reuse"});else throw JA(t.ownerId,u.url,i)}return await zi(t.discoveryPath,async()=>{let u=await Re(t.discoveryPath);if(u?.url){let m=await Vt(u.url,{authToken:u.authToken});if(m?.url&&Nr(m)&&await dt(m.url,{authToken:u.authToken})){if(XA(u.url,r,o,s)||e.allowPortFallback===!0)return d({url:m.url,authToken:u.authToken,action:"reuse"});throw JA(t.ownerId,u.url,i)}if(m?.url){let g={url:m.url,authToken:u.authToken,pid:m.pid??u.pid};if(await tu(g)){if(await dt(m.url,{authToken:u.authToken}))return d({url:m.url,authToken:u.authToken,action:"reuse"})}else await Hr(g,t.discoveryPath)}else await Gt(t.discoveryPath)}let l=async(m)=>{let g=Gg({...m,owner:t}),f={promise:g,state:"starting"};an.set(a,f);try{let h=await g;return f.server=h,f.state="open",d({server:h,url:h.url,authToken:h.authToken,action:"started"})}catch(h){if(an.get(a)===f)an.delete(a);throw h}},p=Date.now()+sX;for(;;)try{return await l(e)}catch(m){if(jA(m)&&Date.now()<p){await new Promise((g)=>setTimeout(g,iX));continue}if(!e.allowPortFallback||!rX(m))throw m;return await l({...e,port:0})}})}function sR(){return oR()==="production"?Ot():vt()}function cX(e){return oR()!=="production"&&!e}async function kue(e){let t=Fn({host:e.host,port:e.port,pathname:e.pathname});return await Gg({...e,...t,owner:sR()})}async function Cue(e){let t=e.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),n=Fn({host:e.host,port:e.port,pathname:e.pathname});return await rR({...e,...n,allowPortFallback:e.allowPortFallback??cX(t),owner:sR()})}export{Wg as BrowserWebSocketHubAdapter,n_ as DEFAULT_HUB_HOST,o_ as DEFAULT_HUB_PATHNAME,r_ as DEFAULT_HUB_PORT,jce as HUB_LOCK_HELD_EXIT_CODE,Vi as HubCommandError,Ng as HubEventLogStore,Ao as HubInstanceLock,WA as HubLockHeldError,lc as HubRunAdmissionRejectedError,Pg as HubRunQueue,Ai as HubScheduleCommandService,Ni as HubScheduleService,hc as HubServerTransport,_x as HubSessionClient,Oe as HubTransportError,xx as HubUIClient,jg as NativeHubTransportAdapter,$n as NodeHubClient,Mr as ScheduledTaskInputSchema,Fh as TASKS_SYSTEM_PROMPT_RULE,Wo as TASKS_TOOL_NAME,$h as TasksToolInputSchema,R2 as __test__,Ax as checkManagedHubBuildMismatch,Gt as clearHubDiscovery,Zh as clearHubDiscoveryIfOwned,qo as compareHubBuilds,Ty as connectToHub,yP as createConfiguredTelemetryHandle,xh as createConfiguredTelemetryService,Qh as createHubAuthToken,Xt as createHubServerUrl,d2 as createInMemoryHubOwnerContext,lse as createLocalHubScheduleRuntimeHandlers,Kc as createTasksPromptExtension,zc as createTasksTool,au as ensureCompatibleLocalHubUrl,Go as ensureDetachedHubServer,Cue as ensureHubServer,rR as ensureHubWebSocketServer,Dc as executeScheduleOperation,Hn as getManagedHubCompatibility,F2 as hasActiveHubSessions,tu as hubHasLiveSessions,c2 as isDiscoveryFilePresent,U2 as isHubCommandTimeoutError,jA as isHubLockHeldError,rx as isHubReconnectableTransportError,nR as isLocalHubHostName,dX as isLocalHubOrigin,Nr as isManagedHubReusable,by as localHubHasNoActiveSessions,Xi as normalizeHubWebSocketUrl,E2 as prewarmDetachedHubServer,K2 as probeHubConnection,Vt as probeHubServer,Fr as queryHubSessionActivity,zg as readBearerToken,Re as readHubDiscovery,O_ as readSupersededHubDiscovery,Ur as rememberRecoverableLocalHubUrl,Bn as requestHubDrain,nu as requestHubShutdown,jo as resolveClineDataDir,i2 as resolveClineDir,dx as resolveCompatibleLocalHubUrl,s_ as resolveDefaultHubHost,i_ as resolveDefaultHubPathname,Ki as resolveDefaultHubPort,Jc as resolveHubBuildEpochMs,Mt as resolveHubBuildId,zo as resolveHubBuildIdentity,Fn as resolveHubEndpointOptions,kV as resolveHubEventLogPath,qA as resolveHubInstanceLockPath,Un as resolveHubOwnerContext,XG as resolveHubRunQueuePath,hx as resolveHubUrl,Ot as resolveProductionHubOwnerContext,vt as resolveSharedHubOwnerContext,h2 as resolveWorkspaceHubOwnerContext,B2 as restartLocalHubIfIdleAfterStartupTimeout,Hr as retireDiscoveredHub,G2 as sendHubCommand,F_ as spawnDetachedHubServer,B_ as spawnDetachedHubServerWithRetry,kue as startHubServer,Gg as startHubWebSocketServer,cx as stopLocalHubServerGracefully,Sy as summarizeHubSessionActivity,ty as toHubHealthUrl,XP as toHubStatusUrl,jm as truncateNotificationBody,P2 as upgradeManagedHub,dt as verifyHubConnection,eY as watchManagedHubBuildMismatch,zi as withHubStartupLock,qi as writeHubDiscovery};