@cline/core 0.0.94-nightly.1792204233 → 0.0.95

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
@@ -316,7 +316,7 @@ ${JSON.stringify(r,null,2)}`}startClaimLeaseHeartbeat(e){let t=Math.max(1000,Mat
316
316
  scheduled_for = COALESCE(?, scheduled_for),
317
317
  updated_at = ?
318
318
  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,be(),e,n).changes??0)===1}attachReportPathToRun(e,t){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(t,be(),e)}}function Gi(e){return e?new Date(e).getTime():void 0}function dP(e){let t=e.metadata?{...e.metadata}:void 0;if(t)delete t.__hubScheduleCreatedBy,delete t.__hubScheduleCwd,delete t.__hubRuntimeOptions;return t}function qo(e){let t=e.metadata;return{scheduleId:e.externalId,name:e.title,cronPattern:e.triggerKind==="one_off"?zo: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:Gi(e.nextRunAt),lastRunAt:Gi(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:dP(e)}}function cP(e){switch(e){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function Jc(e,t){return{executionId:e.runId,scheduleId:t,sessionId:e.sessionId,triggeredAt:new Date(e.scheduledFor??e.createdAt).getTime(),startedAt:Gi(e.startedAt),endedAt:Gi(e.completedAt),status:cP(e.status),errorMessage:e.error}}class Vi{store;materializer;runner;started=!1;disposed=!1;constructor(e){this.store=new jo({dbPath:e.dbPath}),this.materializer=new Do({store:this.store}),this.runner=new Fo({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===zo?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 qo(this.store.createHubSchedule({...e,timezone:t}))}getSchedule(e){let t=this.store.getHubSchedule(e);return t?qo(t):void 0}listSchedules(e={}){return this.store.listHubSchedules(e).map((t)=>qo(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=qo(n),i=t.cronPattern??s.cronPattern;if(i.trim()===zo&&typeof t.timezone==="string"&&t.timezone.trim())throw Error("timezone is only supported for recurring schedules");if(this.validateScheduleTiming(i,i.trim()===zo?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?qo(a):void 0}validateScheduleTiming(e,t,n,r){if(e.trim()!==zo){vh(e),Gc(t);return}if(t?.trim())throw Error("timezone is only supported for recurring schedules");let o=n?.[aP];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 Jc(n,e)}triggerScheduleNowDetached(e){let t=this.store.enqueueHubScheduleRun(e,"manual");if(!t)return;return this.runner.tick().catch(()=>{return}),Jc(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 Jc(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 Qc,statSync as uP}from"node:fs";import{isAbsolute as xh,relative as lP,sep as Mh}from"node:path";import{ONE_TIME_SCHEDULE_CRON_PATTERN as Oh,ONE_TIME_SCHEDULE_RUN_AT_METADATA_KEY as Lh}from"@cline/shared";import{z as he}from"zod";var pP=he.enum(["create","update","list","get","pause","resume","delete","run_now"]),mP=he.object({provider_id:he.string().min(1),model_id:he.string().min(1).optional()}),$r=he.object({operation:pP,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:mP.optional(),limit:he.number().int().positive().max(200).optional()});function Fr(e,t,n,r){if(!Nh.has(t.operation))return;mn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.scheduled.${t.operation}`,success:r,agentId:n.agentId})}var Nh=new Set(["create","update","pause","resume","delete","run_now"]);function Br(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Zc(e,t){try{let n=Qc.native(e);if(!uP(n).isDirectory())throw Error("not a directory");return n}catch{throw Error(`${t} does not resolve to an existing safe path`)}}function gP(e,t){try{return Qc.native(e)===Qc.native(t)}catch{return!1}}function Dh(e,t,n){let r=lP(e,t);if(r===".."||r.startsWith(`..${Mh}`)||xh(r))throw Error(`${n} is outside the workspace scope`)}function Uh(e,t,n){return Zc(xh(t)?t:`${e}${Mh}${t}`,n)}function fP(e){let t=Zc(e.workspaceRoot,"workspaceRoot"),n=e.cwd?Uh(t,e.cwd,"cwd"):t;return Dh(t,n,"cwd"),{...e,workspaceRoot:t,cwd:n}}function Hr(e,t){if(!e)throw Error("schedule does not exist");if(!gP(e.workspaceRoot,t.workspaceRoot))throw Error("schedule is outside this session's workspace scope");let n=Zc(e.workspaceRoot,"schedule workspaceRoot");if(e.cwd){let r=Uh(n,e.cwd,"schedule cwd");Dh(n,r,"schedule cwd")}}function _h(e){if(!e)return;return{providerId:e.provider_id.trim(),modelId:e.model_id?.trim()||void 0}}function Yc(e){if(!e)return;return[...new Set(e.map((t)=>t.trim()).filter(Boolean))]}function Fh(e){let t=Date.parse(Br(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 hP(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:Oh,metadata:{[Lh]:Fh(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:Br(e.cron_pattern,"cron_pattern"),timezone:e.timezone?.trim()||void 0}}throw Error("schedule_type is required for create")}function yP(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:Oh,timezone:null,metadata:{[Lh]:Fh(e.run_at)}}}if(e.schedule_type==="recurring"||e.cron_pattern)return{cronPattern:Br(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 Ko(e){return Br(e.schedule_id,"schedule_id")}async function eu(e,t,n){let r=$r.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=fP(s);if(Nh.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:Br(o.name,"name"),...hP(o),prompt:Br(o.prompt,"prompt"),workspaceRoot:i.workspaceRoot,cwd:i.cwd,modelSelection:_h(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:Yc(o.tags)});return e.publish?.("schedule.created",{schedule:a},n.sessionId),Fr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:a}}case"update":{let a=Ko(o);Hr(e.schedules.getSchedule(a),i);let d=e.schedules.updateSchedule(a,{scheduleId:a,...yP(o),name:o.name?.trim()||void 0,prompt:o.prompt?.trim()||void 0,modelSelection:_h(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:Yc(o.tags)});if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.updated",{schedule:d},n.sessionId),Fr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"list":{let a=e.schedules.listSchedules({enabled:o.enabled,tags:Yc(o.tags),workspaceRoot:i.workspaceRoot,limit:o.limit??50}).filter((d)=>{try{return Hr(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(Ko(o));return Hr(a,i),{ok:!0,operation:o.operation,schedule:a}}case"pause":case"resume":{let a=Ko(o);Hr(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),Fr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"delete":{let a=Ko(o);Hr(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),Fr(e,o,n,!0),{ok:!0,operation:o.operation,deleted:d}}case"run_now":{let a=Ko(o);Hr(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),Fr(e,o,n,!0),{ok:!0,operation:o.operation,execution:d}}}}catch(s){return Fr(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 qP}from"@cline/llms";import{markOtlpTraceRelayProvider as zP}from"@cline/shared";import{metrics as KP,trace as GP}from"@opentelemetry/api";import{logs as VP}from"@opentelemetry/api-logs";import{OTLPLogExporter as XP}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as JP}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as YP}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as QP}from"@opentelemetry/resources";import{BatchLogRecordProcessor as ZP,ConsoleLogRecordExporter as e_,LoggerProvider as t_}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as n_,MeterProvider as r_,PeriodicExportingMetricReader as ty}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as o_,ConsoleSpanExporter as s_,SimpleSpanProcessor as i_}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as a_}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as d_,ATTR_SERVICE_VERSION as c_}from"@opentelemetry/semantic-conventions";import{mkdirSync as SP,readFileSync as bP,statSync as vP,writeFileSync as TP}from"node:fs";import{dirname as wP}from"node:path";import{CONFIGURABLE_MODEL_TOOL_NAMES as Hh}from"@cline/shared";import{resolveGlobalSettingsPath as Bh}from"@cline/shared/storage";import{z as He}from"zod";var tu=He.preprocess((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string").map((t)=>t.trim()).filter(Boolean):void 0,He.array(He.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}),kP=He.enum(["basic","agentic"]).catch("agentic"),IP=He.partialRecord(He.enum(Hh),He.object({enabled:He.boolean()}).strip()).optional(),CP=He.enum(["plan","act"]),nu=He.object({telemetryOptOut:He.boolean().default(!1).catch(!1),autoUpdateEnabled:He.boolean().default(!0).catch(!0),compactionStrategy:kP.optional(),compactionEnabled:He.boolean().optional().catch(void 0),planActMode:CP.optional().catch(void 0),toolAutoApprove:He.boolean().optional().catch(void 0),tuiTheme:He.string().optional().catch(void 0),disabledTools:tu.optional(),tools:IP,disabledPlugins:tu.optional(),disabledAgentPlugins:tu.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 Xi(){return nu.parse({})}var Ji;function RP(){Ji=void 0}function AP(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 EP(e){let t;try{t=bP(e,"utf8")}catch{return{value:Xi(),loadFailed:!0}}try{let n=nu.safeParse(JSON.parse(t));return n.success?{value:n.data,loadFailed:!1}:{value:Xi(),loadFailed:!0}}catch{return{value:Xi(),loadFailed:!0}}}function $h(){let e=Bh(),t=vP(e,{throwIfNoEntry:!1}),n=t?.mtimeMs??0,r=t?.size??0,o=Ji;if(o&&o.path===e&&o.mtimeMs===n&&o.size===r)return o;let s=t?EP(e):{value:Xi(),loadFailed:!1},i=AP(s.value);return Ji={path:e,mtimeMs:n,size:r,value:i,loadFailed:s.loadFailed},Ji}function at(){return $h().value}function Go(e,t={}){let n=Bh(),r=at();SP(wP(n),{recursive:!0});let o=nu.parse(e);if(!r.telemetryOptOut&&o.telemetryOptOut)Lf(t.telemetry);TP(n,`${JSON.stringify(o,null,2)}
319
- `,"utf8"),RP()}function Wh(){return at().telemetryOptOut}function $n(e){return new Set(e??at().disabledTools??[])}function jh(e){return new Set(e??at().disabledPlugins??[])}function Vo(e){return new Set(e??at().disabledAgentPlugins??[])}function qh(e){return Hh.includes(e)}function PP(){let e=$h();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function ru(e){return PP()[e]?.enabled===!0}function _P(e,t){let n=at();Go({...n,tools:{...n.tools,[e]:{enabled:t}}})}function zh(e){if(qh(e)){let o=ru(e);return _P(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 Go({...t,disabledTools:[...n]}),!r}function xP(e,t){let n=[...new Set(e.map((i)=>i.trim()).filter(Boolean))];if(n.length===0)return;let r=at(),o=$n(r.disabledTools),s={...r.tools};for(let i of n){if(qh(i)){s[i]={enabled:!t};continue}if(t)o.add(i);else o.delete(i)}Go({...r,disabledTools:[...o],tools:s})}function Kh(e,t){return xP([e],t),t}function Gh(e,t){let n=e.trim();if(!n)return;let r=at(),o=jh(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Go({...r,disabledPlugins:[...o]})}function Vh(e,t){let n=e.trim();if(!n)return;let r=at(),o=Vo(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Go({...r,disabledAgentPlugins:[...o]})}function ou(e,t){let n=jh(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r))}function Wn(e,t){let n=$n(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r.name))}function Xh(e,t){if(!e||e.length===0)return e;let n=$n(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 MP,mkdirSync as OP,readFileSync as LP,writeFileSync as NP}from"node:fs";import{resolve as DP}from"node:path";import{resolveSessionDataDir as UP}from"@cline/shared/storage";import{nanoid as FP}from"nanoid";import*as HP from"node-machine-id";var BP="machine-id",Jh,Yh=!1;function Qh(){if(!Yh)Jh=Zh(),Yh=!0;return Jh??ey()}function Xo(e){let t=e?.trim();if(t)return t;let n=Zh();if(n)return n;return ey()}function $P(){let e=HP;return e.machineIdSync??e.default?.machineIdSync}function Zh(){try{let e=$P();if(!e)return;return e().trim()||void 0}catch{return}}function ey(){let e=UP(),t=DP(e,BP);try{if(MP(t)){let r=LP(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${FP()}`;try{OP(e,{recursive:!0}),NP(t,n,"utf8")}catch{}return n}import{SeverityNumber as Wr}from"@opentelemetry/api-logs";class su{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)),o=WP(r.severity);this.logger.emit({severityText:o.text,severityNumber:o.number,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(jP(d)){o[c]=d;continue}try{o[c]=JSON.stringify(d)}catch{o[c]=String(d)}}return o}}function WP(e){switch(typeof e==="string"?e.toLowerCase():e){case"trace":return{text:"TRACE",number:Wr.TRACE};case"debug":return{text:"DEBUG",number:Wr.DEBUG};case"warn":case"warning":return{text:"WARN",number:Wr.WARN};case"error":return{text:"ERROR",number:Wr.ERROR};case"fatal":return{text:"FATAL",number:Wr.FATAL};default:return{text:"INFO",number:Wr.INFO}}}function jP(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class iu{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 Yi{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new iu({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??Qh(),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 ny{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 ry{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=QP({...e.resourceAttributes,[d_]:e.serviceName??"cline",...e.serviceVersion?{[c_]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)KP.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)VP.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return GP.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new su({...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 Yi({...e,adapters:[t],distinctId:Xo(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=au(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)=>g_(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 r_({resource:e,readers:o})}createTracerProvider(e){let t=au(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=m_(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 a_({resource:e,spanProcessors:s?[new qP,...o]:o});if(s)zP(i);return i}createLoggerProvider(e){let t=au(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=p_(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new ZP(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 t_({resource:e,processors:n})}}function u_(e){let t=new ry(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 oy(e){if(Wh())return{telemetry:new ny(e)};if(e.enabled!==!0)return{telemetry:new Yi({...e,distinctId:Xo(e.distinctId)})};return u_(e)}function l_(e){let{telemetry:t,provider:n,emitProviderCreated:r}=oy(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 au(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function p_(e,t){if(e==="console")return new e_;if(!t.endpoint)return null;let n=du(t.endpoint,"/v1/logs");return new XP({url:n,headers:t.headers})}function m_(e,t){if(e==="console")return new i_(new s_);if(!t.endpoint)return null;let n=du(t.endpoint,"/v1/traces");return new o_(new YP({url:n,headers:t.headers}))}function g_(e,t){if(e==="console")return new ty({exporter:new n_,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=du(t.endpoint,"/v1/metrics");return new ty({exporter:new JP({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function du(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 b_,zodToJsonSchema as v_}from"@cline/shared";import{z as Dt}from"zod";import{resolve as sy}from"node:path";import{z as ee}from"zod";var iy=ee.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),f_=ee.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),ay=ee.union([ee.literal(0),ee.literal(1),ee.literal(2),ee.literal(3),ee.literal(4),ee.literal(5)]),h_=ee.object({provider_id:ee.string().min(1),model_id:ee.string().min(1).optional()}),Qi=ee.object({operation:ee.enum(["create","update","list","get"]),task_id:ee.string().min(1).optional(),expected_revision:ee.number().int().positive().optional(),type:iy.optional(),title:ee.string().min(1).optional(),description:ee.string().nullable().optional(),instructions:ee.string().min(1).optional(),scope:ee.enum(["workspace","global"]).optional(),workspace_root:ee.string().min(1).nullable().optional(),cwd:ee.string().min(1).nullable().optional(),resource_paths:ee.array(ee.string().min(1)).optional(),priority:ay.optional(),assignee:ee.string().min(1).nullable().optional(),model_selection:h_.nullable().optional(),mode:ee.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:ee.string().nullable().optional(),max_iterations:ee.number().int().positive().nullable().optional(),timeout_seconds:ee.number().int().positive().nullable().optional(),available_at:ee.string().datetime().optional(),expires_at:ee.string().datetime().optional(),automation_eligible:ee.boolean().optional(),statuses:ee.array(f_).optional(),types:ee.array(iy).optional(),priorities:ee.array(ay).optional(),limit:ee.number().int().positive().max(500).optional()}),y_=new Set(["create","update"]);function cu(e,t,n,r){if(!y_.has(t.operation))return;mn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.todo.${t.operation}`,success:r,agentId:n.agentId})}function jr(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function dy(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function uy(e,t){return sy(e)===sy(t)}function cy(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!uy(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 S_(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||!uy(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function ly(e,t,n){let r=Qi.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=S_(o,i);switch(o.operation){case"create":{let d={type:jr(o.type,"type"),title:jr(o.title,"title"),description:o.description??void 0,instructions:jr(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:dy(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:jr(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 cu(e,o,n,!0),c}case"update":{let d=jr(o.task_id,"task_id");if(cy(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:dy(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 cu(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(jr(o.task_id,"task_id"));return cy(d,i),{ok:!0,operation:o.operation,task:d}}}}catch(i){return cu(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:i instanceof Error?i.message:String(i)}}}}var Jo="tasks",py='# 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.',T_="# 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.",w_=Qi.extend({kind:Dt.literal("todo")}).strict(),my=$r.extend({kind:Dt.literal("scheduled")}).strict(),gy=Dt.discriminatedUnion("kind",[w_,my]),k_=Dt.discriminatedUnion("kind",[my]),fy=["create","update","list","get","pause","resume","delete","run_now"],I_=Dt.object({...$r.shape,...Qi.shape,kind:Dt.enum(["todo","scheduled"]),operation:Dt.enum(fy)}).strict(),C_=Dt.object({...$r.shape,kind:Dt.enum(["scheduled"]),operation:Dt.enum(fy)}).strict();function uu(e){let t=e.todo;return b_({name:Jo,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:v_(t?I_:C_),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?gy:k_).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 ly(t,o.data,r)}}return{kind:"scheduled",...await eu(e.scheduled,o.data,r)}}})}function lu(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?T_:py,whenToolAvailable:Jo})}}}import{createSessionId as Hx,ensureLoopbackProxyBypass as Wy,isHubProtocolCompatible as Bx,resolveClineBuildEnv as $x,resolveHubCommandTimeoutMs as Wx}from"@cline/shared";import{HttpProxyAgent as jx}from"http-proxy-agent";import{HttpsProxyAgent as qx}from"https-proxy-agent";import{getProxyForUrl as zx}from"proxy-from-env";import Kx from"ws";var Zi="0.0.94-nightly.1792204233";var hn={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Zi,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"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.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","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","proxy-from-env":"^2.1.0","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/proxy-from-env":"^1.0.4","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var ea="session_not_found";class qr 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 ta(e){return e instanceof qr||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as sx}from"node:child_process";import{closeSync as ix,mkdirSync as ax,openSync as dx,readFileSync as cx,unlinkSync as ux}from"node:fs";import{basename as lx,dirname as px,join as mx}from"node:path";import{fileURLToPath as gx}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fx,getClineClientIdentity as hx,isBunEmbeddedModulePath as yx,isHubDaemonProcess as Ly,resolveClineBuildEnv as Ny,withHubLauncherIdentity as Sx,withResolvedClineBuildEnv as bx}from"@cline/shared";import{createHash as R_,randomBytes as wy}from"node:crypto";import{existsSync as A_}from"node:fs";import{mkdir as mu,open as yy,readFile as ky,rename as E_,rm as na,writeFile as P_}from"node:fs/promises";import{dirname as Iy,join as gu}from"node:path";import{ensureLoopbackProxyBypass as __,isHubProtocolCompatible as x_}from"@cline/shared";import{resolveClineDataDir as Yo,resolveClineDir as IY}from"@cline/shared/storage";var M_="CLINE_HUB_DISCOVERY_PATH",O_="CLINE_HUB_BUILD_ID",L_="CLINE_HUB_BUILD_EPOCH_MS",N_=30000,D_=15000,Sy=100;function U_(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function F_(e){return R_("sha256").update(e).digest("hex").slice(0,12)}function H_(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 Cy(){return wy(32).toString("hex")}function by(e){return new Promise((t)=>setTimeout(t,e))}function B_(e){return`${e}.lock`}async function $_(e){try{let t=JSON.parse(await ky(gu(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 pu(e){await na(e,{recursive:!0,force:!0}).catch(()=>{return})}function Ut(){let e=process.env[O_]?.trim();if(e)return e;return"sdk-v1-f5a1fc2ba8d43f15033fc87e8829924161d986b0704ba71d3b1f2052a2bf3e40".trim()||`source-${String(hn.version)}`}function fu(){let e=Number(process.env[L_]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792204255621)?1792204255621:void 0}function jn(e,t=Ut()){let n=x_(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 vy(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function Ty(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 W_(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=vy(e.buildEpochMs),s=vy(t.buildEpochMs);if(o!==void 0&&s!==void 0&&o!==s)return o<s?-1:1;let i=Ty(e.coreVersion),a=Ty(t.coreVersion);if(i&&a){let d=W_(i,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function Zo(){return{buildId:Ut(),buildEpochMs:fu(),coreVersion:String(hn.version)}}function zr(e,t){let n=t?.self??Zo(),r=jn(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 qn(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${F_(e)}`,n=process.env[M_]?.trim()||gu(Yo(),"locks","hub","owners",`${U_(t)}.json`);return{ownerId:t,discoveryPath:n}}function RY(e=`hub-${Date.now().toString(36)}`){return qn(e)}async function Re(e,t={}){try{let n;try{n=await ky(e,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r;try{r=JSON.parse(n)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!r||typeof r.hubId!=="string"||typeof r.protocolVersion!=="string"||typeof r.authToken!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string"||typeof r.startedAt!=="string"||typeof r.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:r.hubId,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,authToken:r.authToken,host:r.host,port:r.port,url:r.url,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:r.startedAt,updatedAt:r.updatedAt}}catch(n){if(t.onError==="throw")throw n;return}}async function ra(e,t){await hu(e,async()=>{let n=Iy(e);await mu(n,{recursive:!0});let r=`${e}.${process.pid}.${wy(6).toString("hex")}.tmp`,o;try{o=await yy(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
319
+ `,"utf8"),RP()}function Wh(){return at().telemetryOptOut}function $n(e){return new Set(e??at().disabledTools??[])}function jh(e){return new Set(e??at().disabledPlugins??[])}function Vo(e){return new Set(e??at().disabledAgentPlugins??[])}function qh(e){return Hh.includes(e)}function PP(){let e=$h();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function ru(e){return PP()[e]?.enabled===!0}function _P(e,t){let n=at();Go({...n,tools:{...n.tools,[e]:{enabled:t}}})}function zh(e){if(qh(e)){let o=ru(e);return _P(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 Go({...t,disabledTools:[...n]}),!r}function xP(e,t){let n=[...new Set(e.map((i)=>i.trim()).filter(Boolean))];if(n.length===0)return;let r=at(),o=$n(r.disabledTools),s={...r.tools};for(let i of n){if(qh(i)){s[i]={enabled:!t};continue}if(t)o.add(i);else o.delete(i)}Go({...r,disabledTools:[...o],tools:s})}function Kh(e,t){return xP([e],t),t}function Gh(e,t){let n=e.trim();if(!n)return;let r=at(),o=jh(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Go({...r,disabledPlugins:[...o]})}function Vh(e,t){let n=e.trim();if(!n)return;let r=at(),o=Vo(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Go({...r,disabledAgentPlugins:[...o]})}function ou(e,t){let n=jh(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r))}function Wn(e,t){let n=$n(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r.name))}function Xh(e,t){if(!e||e.length===0)return e;let n=$n(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 MP,mkdirSync as OP,readFileSync as LP,writeFileSync as NP}from"node:fs";import{resolve as DP}from"node:path";import{resolveSessionDataDir as UP}from"@cline/shared/storage";import{nanoid as FP}from"nanoid";import*as HP from"node-machine-id";var BP="machine-id",Jh,Yh=!1;function Qh(){if(!Yh)Jh=Zh(),Yh=!0;return Jh??ey()}function Xo(e){let t=e?.trim();if(t)return t;let n=Zh();if(n)return n;return ey()}function $P(){let e=HP;return e.machineIdSync??e.default?.machineIdSync}function Zh(){try{let e=$P();if(!e)return;return e().trim()||void 0}catch{return}}function ey(){let e=UP(),t=DP(e,BP);try{if(MP(t)){let r=LP(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${FP()}`;try{OP(e,{recursive:!0}),NP(t,n,"utf8")}catch{}return n}import{SeverityNumber as Wr}from"@opentelemetry/api-logs";class su{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)),o=WP(r.severity);this.logger.emit({severityText:o.text,severityNumber:o.number,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(jP(d)){o[c]=d;continue}try{o[c]=JSON.stringify(d)}catch{o[c]=String(d)}}return o}}function WP(e){switch(typeof e==="string"?e.toLowerCase():e){case"trace":return{text:"TRACE",number:Wr.TRACE};case"debug":return{text:"DEBUG",number:Wr.DEBUG};case"warn":case"warning":return{text:"WARN",number:Wr.WARN};case"error":return{text:"ERROR",number:Wr.ERROR};case"fatal":return{text:"FATAL",number:Wr.FATAL};default:return{text:"INFO",number:Wr.INFO}}}function jP(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class iu{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 Yi{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new iu({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??Qh(),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 ny{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 ry{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=QP({...e.resourceAttributes,[d_]:e.serviceName??"cline",...e.serviceVersion?{[c_]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)KP.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)VP.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return GP.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new su({...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 Yi({...e,adapters:[t],distinctId:Xo(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=au(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)=>g_(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 r_({resource:e,readers:o})}createTracerProvider(e){let t=au(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=m_(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 a_({resource:e,spanProcessors:s?[new qP,...o]:o});if(s)zP(i);return i}createLoggerProvider(e){let t=au(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=p_(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new ZP(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 t_({resource:e,processors:n})}}function u_(e){let t=new ry(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 oy(e){if(Wh())return{telemetry:new ny(e)};if(e.enabled!==!0)return{telemetry:new Yi({...e,distinctId:Xo(e.distinctId)})};return u_(e)}function l_(e){let{telemetry:t,provider:n,emitProviderCreated:r}=oy(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 au(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function p_(e,t){if(e==="console")return new e_;if(!t.endpoint)return null;let n=du(t.endpoint,"/v1/logs");return new XP({url:n,headers:t.headers})}function m_(e,t){if(e==="console")return new i_(new s_);if(!t.endpoint)return null;let n=du(t.endpoint,"/v1/traces");return new o_(new YP({url:n,headers:t.headers}))}function g_(e,t){if(e==="console")return new ty({exporter:new n_,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=du(t.endpoint,"/v1/metrics");return new ty({exporter:new JP({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function du(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 b_,zodToJsonSchema as v_}from"@cline/shared";import{z as Dt}from"zod";import{resolve as sy}from"node:path";import{z as ee}from"zod";var iy=ee.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),f_=ee.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),ay=ee.union([ee.literal(0),ee.literal(1),ee.literal(2),ee.literal(3),ee.literal(4),ee.literal(5)]),h_=ee.object({provider_id:ee.string().min(1),model_id:ee.string().min(1).optional()}),Qi=ee.object({operation:ee.enum(["create","update","list","get"]),task_id:ee.string().min(1).optional(),expected_revision:ee.number().int().positive().optional(),type:iy.optional(),title:ee.string().min(1).optional(),description:ee.string().nullable().optional(),instructions:ee.string().min(1).optional(),scope:ee.enum(["workspace","global"]).optional(),workspace_root:ee.string().min(1).nullable().optional(),cwd:ee.string().min(1).nullable().optional(),resource_paths:ee.array(ee.string().min(1)).optional(),priority:ay.optional(),assignee:ee.string().min(1).nullable().optional(),model_selection:h_.nullable().optional(),mode:ee.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:ee.string().nullable().optional(),max_iterations:ee.number().int().positive().nullable().optional(),timeout_seconds:ee.number().int().positive().nullable().optional(),available_at:ee.string().datetime().optional(),expires_at:ee.string().datetime().optional(),automation_eligible:ee.boolean().optional(),statuses:ee.array(f_).optional(),types:ee.array(iy).optional(),priorities:ee.array(ay).optional(),limit:ee.number().int().positive().max(500).optional()}),y_=new Set(["create","update"]);function cu(e,t,n,r){if(!y_.has(t.operation))return;mn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.todo.${t.operation}`,success:r,agentId:n.agentId})}function jr(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function dy(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function uy(e,t){return sy(e)===sy(t)}function cy(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!uy(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 S_(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||!uy(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function ly(e,t,n){let r=Qi.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=S_(o,i);switch(o.operation){case"create":{let d={type:jr(o.type,"type"),title:jr(o.title,"title"),description:o.description??void 0,instructions:jr(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:dy(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:jr(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 cu(e,o,n,!0),c}case"update":{let d=jr(o.task_id,"task_id");if(cy(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:dy(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 cu(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(jr(o.task_id,"task_id"));return cy(d,i),{ok:!0,operation:o.operation,task:d}}}}catch(i){return cu(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:i instanceof Error?i.message:String(i)}}}}var Jo="tasks",py='# 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.',T_="# 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.",w_=Qi.extend({kind:Dt.literal("todo")}).strict(),my=$r.extend({kind:Dt.literal("scheduled")}).strict(),gy=Dt.discriminatedUnion("kind",[w_,my]),k_=Dt.discriminatedUnion("kind",[my]),fy=["create","update","list","get","pause","resume","delete","run_now"],I_=Dt.object({...$r.shape,...Qi.shape,kind:Dt.enum(["todo","scheduled"]),operation:Dt.enum(fy)}).strict(),C_=Dt.object({...$r.shape,kind:Dt.enum(["scheduled"]),operation:Dt.enum(fy)}).strict();function uu(e){let t=e.todo;return b_({name:Jo,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:v_(t?I_:C_),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?gy:k_).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 ly(t,o.data,r)}}return{kind:"scheduled",...await eu(e.scheduled,o.data,r)}}})}function lu(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?T_:py,whenToolAvailable:Jo})}}}import{createSessionId as Hx,ensureLoopbackProxyBypass as Wy,isHubProtocolCompatible as Bx,resolveClineBuildEnv as $x,resolveHubCommandTimeoutMs as Wx}from"@cline/shared";import{HttpProxyAgent as jx}from"http-proxy-agent";import{HttpsProxyAgent as qx}from"https-proxy-agent";import{getProxyForUrl as zx}from"proxy-from-env";import Kx from"ws";var Zi="0.0.95";var hn={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Zi,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"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.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","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","proxy-from-env":"^2.1.0","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/proxy-from-env":"^1.0.4","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var ea="session_not_found";class qr 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 ta(e){return e instanceof qr||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as sx}from"node:child_process";import{closeSync as ix,mkdirSync as ax,openSync as dx,readFileSync as cx,unlinkSync as ux}from"node:fs";import{basename as lx,dirname as px,join as mx}from"node:path";import{fileURLToPath as gx}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fx,getClineClientIdentity as hx,isBunEmbeddedModulePath as yx,isHubDaemonProcess as Ly,resolveClineBuildEnv as Ny,withHubLauncherIdentity as Sx,withResolvedClineBuildEnv as bx}from"@cline/shared";import{createHash as R_,randomBytes as wy}from"node:crypto";import{existsSync as A_}from"node:fs";import{mkdir as mu,open as yy,readFile as ky,rename as E_,rm as na,writeFile as P_}from"node:fs/promises";import{dirname as Iy,join as gu}from"node:path";import{ensureLoopbackProxyBypass as __,isHubProtocolCompatible as x_}from"@cline/shared";import{resolveClineDataDir as Yo,resolveClineDir as IY}from"@cline/shared/storage";var M_="CLINE_HUB_DISCOVERY_PATH",O_="CLINE_HUB_BUILD_ID",L_="CLINE_HUB_BUILD_EPOCH_MS",N_=30000,D_=15000,Sy=100;function U_(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function F_(e){return R_("sha256").update(e).digest("hex").slice(0,12)}function H_(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 Cy(){return wy(32).toString("hex")}function by(e){return new Promise((t)=>setTimeout(t,e))}function B_(e){return`${e}.lock`}async function $_(e){try{let t=JSON.parse(await ky(gu(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 pu(e){await na(e,{recursive:!0,force:!0}).catch(()=>{return})}function Ut(){let e=process.env[O_]?.trim();if(e)return e;return"sdk-v1-d7fc6ac75da1ec6a985419452ab0576ef1178c82233d7370cd14e6261884bd99".trim()||`source-${String(hn.version)}`}function fu(){let e=Number(process.env[L_]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792205906587)?1792205906587:void 0}function jn(e,t=Ut()){let n=x_(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 vy(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function Ty(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 W_(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=vy(e.buildEpochMs),s=vy(t.buildEpochMs);if(o!==void 0&&s!==void 0&&o!==s)return o<s?-1:1;let i=Ty(e.coreVersion),a=Ty(t.coreVersion);if(i&&a){let d=W_(i,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function Zo(){return{buildId:Ut(),buildEpochMs:fu(),coreVersion:String(hn.version)}}function zr(e,t){let n=t?.self??Zo(),r=jn(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 qn(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${F_(e)}`,n=process.env[M_]?.trim()||gu(Yo(),"locks","hub","owners",`${U_(t)}.json`);return{ownerId:t,discoveryPath:n}}function RY(e=`hub-${Date.now().toString(36)}`){return qn(e)}async function Re(e,t={}){try{let n;try{n=await ky(e,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r;try{r=JSON.parse(n)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!r||typeof r.hubId!=="string"||typeof r.protocolVersion!=="string"||typeof r.authToken!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string"||typeof r.startedAt!=="string"||typeof r.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:r.hubId,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,authToken:r.authToken,host:r.host,port:r.port,url:r.url,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:r.startedAt,updatedAt:r.updatedAt}}catch(n){if(t.onError==="throw")throw n;return}}async function ra(e,t){await hu(e,async()=>{let n=Iy(e);await mu(n,{recursive:!0});let r=`${e}.${process.pid}.${wy(6).toString("hex")}.tmp`,o;try{o=await yy(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
320
320
  `,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await E_(r,e);let s;try{s=await yy(n,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await o?.close().catch(()=>{return}),await na(r,{force:!0}).catch(()=>{return}),s}})}async function Yt(e){await hu(e,async()=>{await na(e,{force:!0}).catch(()=>{return})})}async function Ry(e,t){return await hu(e,async()=>{if((await Re(e))?.hubId!==t)return!1;return await na(e,{force:!0}),!0})}async function Ay(e,t,n){let r=B_(e);await mu(Iy(r),{recursive:!0});let o=Date.now()+D_;while(!0){try{await mu(r,{recursive:!1})}catch(s){if((s instanceof Error&&"code"in s?String(s.code):"")!=="EEXIST")throw s;let a=await $_(r);if(!a){if(Date.now()>=o){await pu(r);continue}await by(Sy);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!H_(a.pid)||d>N_){await pu(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await by(Sy);continue}try{return await P_(gu(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
321
321
  `,"utf8"),await n()}finally{await pu(r)}}}function hu(e,t){return Ay(`${e}.mutation`,"discovery mutation",t)}function oa(e,t){return Ay(e,"startup",t)}async function Qt(e,t){__();try{let n=await fetch(t?.authToken?j_(e):Ey(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 Zt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Ey(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function j_(e){let t=new URL(Ey(e));return t.pathname="/status",t.toString()}function AY(e){return A_(e)}import{CLINE_HUB_DEV_PORT as q_,CLINE_HUB_PORT as z_,resolveClineBuildEnv as K_}from"@cline/shared";var G_="CLINE_HUB_HOST",V_="CLINE_HUB_PORT",X_="CLINE_HUB_PATHNAME",J_="127.0.0.1",Y_=z_,Q_="/hub";function Py(e){return K_(e)==="development"?q_:Y_}function Z_(e={}){return(e.env??process.env)[G_]?.trim()||J_}function sa(e={}){let n=(e.env??process.env)[V_]?.trim();if(!n)return Py(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return Py(e);return r}function ex(e={}){return(e.env??process.env)[X_]?.trim()||Q_}function zn(e={},t={}){return{host:e.host??Z_(t),port:e.port??sa(t),pathname:e.pathname??ex(t)}}import{join as tx}from"node:path";var nx="shared:cline",rx="CLINE_HUB_DISCOVERY_PATH",ox="hub-production";function LY(e){let t=Un(e.trim());return qn(`workspace:${t||e.trim()}`)}function wt(e=nx){return qn(`${e}@${Ut()}`)}function Ft(){return{ownerId:ox,discoveryPath:process.env[rx]?.trim()||tx(Yo(),"locks","hub","production.json")}}var _y=15000,vx=200,xy=3000,Tx=100,wx=[100,250,500,1000,2000],Dy="--cline-hub-daemon",kx=3,Ix=60000,bu=new Map,zY={resetRetireAttempts(){bu.clear()},resolveDaemonEntryArgs:Fy,resolveLaunchCommand:(e,t={})=>Hy(e,t)};function Cx(e,t=Date.now()){let n=bu.get(e);if(!n||t-n.windowStartedAt>Ix)return bu.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=kx}function Rx(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function Ax(){try{let e=mx(Yo(),"logs","hub-daemon.log");return ax(px(e),{recursive:!0}),{fd:dx(e,"a"),logPath:e}}catch{return}}function Uy(){return Ny()==="production"?Ft():wt()}function es(e){return zr(e)}function Ex(e){try{let t=JSON.parse(cx(`${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 yu(e){try{ux(`${e}.superseded`)}catch{}}function My(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Kr(e,t){try{return await Qt(e,{authToken:t})}catch{return}}async function Oy(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Kr(e))?.url)return!0;await new Promise((o)=>setTimeout(o,Tx))}return!1}async function Gr(e,t){if(!Cx(e.url))return!1;await Kn(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Tu(e.url,e.authToken).catch(()=>!1);let n=await Oy(e.url,xy);if(!n&&e.pid&&Px(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Oy(e.url,xy)}if(n)await Yt(t).catch(()=>{return});return n}function Px(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function vu(e){try{return(await Xr(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function Su(e,t){if(es(e))return"reusable";let n=await Kn(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await vu(e)){if(n)await Kn(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Gr(e,t);if(!r&&n)await Kn(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function _x(e){if(Ny()!=="production")return;let t=wt();if(t.discoveryPath===e.discoveryPath)return;let n=await Re(t.discoveryPath);if(n?.url)await Gr(n,t.discoveryPath);else await Yt(t.discoveryPath).catch(()=>{return})}function xx(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return gx(new URL(`./entry.${e}`,import.meta.url))}function Fy(e,t){if(yx(e))return[Dy];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}var ia;function KY(e){let t=e?.command.trim();ia=t?{command:t,args:e?.args?[...e.args]:void 0}:void 0}function Hy(e,t){let n,r;if(ia)n=ia.command,r=ia.args??[Dy];else{let o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let s=lx(o).toLowerCase().includes("bun");n=o,r=Fy(xx(),s)}return{launcher:n,args:[...r,"--cwd",e,...Rx(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...Sx(bx(process.env),Mx()),CLINE_NO_INTERACTIVE:"1",[fx]:"1"}}}function Mx(){let e=hx(),t=e?.name?.trim();return t?{client:t,version:e?.version,transport:"local"}:void 0}function Ox(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 Lx(e,t={}){if(Ly())return;let n=Hy(e,t),r=Ax();try{sx(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)ix(r.fd)}}async function Nx(e,t={}){for(let n=0;;n++)try{Lx(e,t);return}catch(r){let o=wx[n];if(!Ox(r)||o===void 0)throw r;await new Promise((s)=>setTimeout(s,o))}}function GY(e,t={}){if(Ly())return;ts(e,t).catch(()=>{})}async function Dx(e,t,n={}){let r=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=zn(n),s=Zt(o.host,o.port,o.pathname),i=(g)=>{if(!r)Vr(g.url,g.authToken);return g};await _x(e).catch(()=>{return});let a=await Re(e.discoveryPath),d=a?.url?void 0:Ex(e.discoveryPath),c=!1;if(a?.url){let g=a.authToken;if(!g)c=!0,await Gr(a,e.discoveryPath);else{let f=await Kr(a.url,g);if(f?.url&&es(f)&&await dt(f.url,{authToken:g}))return yu(e.discoveryPath),i({url:f.url,authToken:g});if(f?.url){if(await Su({...f,authToken:g},e.discoveryPath)==="deferred_busy"&&await dt(f.url,{authToken:g}))return i({url:f.url,authToken:g})}else await Yt(e.discoveryPath).catch(()=>{return})}}let u=await Kr(s);if(u?.url){let g=My(u,a??d,s);if(es(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 ra(e.discoveryPath,b)}catch{}return yu(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 Su(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 n.beforeSpawn?.(),await Nx(t,{...p,manageConnectors:n.manageConnectors});let m=Date.now()+_y;while(Date.now()<m){let g=await Re(e.discoveryPath);if(g?.url&&g.authToken){let h=await Kr(g.url,g.authToken);if(h?.url&&es(h)&&await dt(h.url,{authToken:g.authToken}))return yu(e.discoveryPath),i({url:h.url,authToken:g.authToken})}let f=await Kr(s);if(f?.url&&!es(f)){let h=My(f,g??d,s),S=await Su(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,vx))}throw Error(`Timed out after ${_y}ms waiting for detached hub startup.`)}async function ts(e,t={}){let n=Uy();return await oa(n.discoveryPath,async()=>Dx(n,e,t))}var Ux=5000,Fx=500;async function VY(e={}){let t=Uy(),n=e.workspaceRoot??process.cwd(),r=await Re(t.discoveryPath),o=r?.url?await Kr(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await ts(n)};let s={...o,authToken:o.authToken??r?.authToken,pid:o.pid??r?.pid};if(jn(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 Kn(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 Kn(s.url,s.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},d=Date.now()+(e.waitForIdleMs??Ux),c;for(;;){try{if(c=(await Xr(s.url,s.authToken)).activeSessionCount,c===0)break}catch{}if(Date.now()>=d)break;await new Promise((p)=>setTimeout(p,Fx))}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 Gr(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 ts(n),activeSessionCount:c??0}}function Eu(){return $x()==="production"?Ft():wt()}function Gx(){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 Vx(e){let t=new URL(e);t.protocol=e.protocol==="wss:"?"https:":"http:";let n=zx(t.toString());if(!n)return;return e.protocol==="wss:"?new qx(n):new jx(n)}function jy(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 jy(e.data);return String(e)}function Xx(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 By(e){let t=e,n=Xx(t.reason);return new Le("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Iu,{closeCode:t.code,closeReason:n||void 0})}function wu(e,t){if(e instanceof Le)return e;if(e instanceof Error)return new Le("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new Le("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 Le("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new Le("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 ku="*",aa=8000,Jx="cline-hub-auth.",qy=new Map,zy=new Set,Yx=3000,Qx=3000,Zx=100,Iu="Hub connection closed",eM=250,tM=5000,$y=0.5;class Le extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function nM(e){return e instanceof Le}class da extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function i5(e,t){return e instanceof da&&e.code==="hub_command_timeout"&&(t===void 0||e.command===t)}function Pu(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let r=_u(e.toString());return r?qy.get(r):void 0}function rM(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 _u(e){if(!rM(e))return;let t=new URL(ca(e));return t.search="",t.hash="",t.toString()}function Cu(e){let t=_u(e);return!!t&&zy.has(t)}function Vr(e,t){let n=_u(e);if(n){if(zy.add(n),t?.trim())qy.set(n,t)}return e}class Gn{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 Le("hub_connection_closed",Iu);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()||Pu(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(hn.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=wu(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 c;try{o=await Promise.race([Promise.resolve().then(()=>r()),new Promise((u,l)=>{c=setTimeout(()=>{l(new Le("hub_connect_timeout",`Timed out resolving hub connection headers after ${aa}ms`))},aa)})])}catch(u){let l=u instanceof Le?u:new Le("hub_connect_failed",u instanceof Error?u.message:String(u));if(n===this.connectGeneration)this.lastCloseError=l;throw l}finally{clearTimeout(c)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((c)=>c.toLowerCase()==="sec-websocket-protocol")){let c=new Le("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=c;throw c}let s;try{s=o?Vx(e):void 0}catch(c){let u=wu(c,e);if(n===this.connectGeneration)this.lastCloseError=u;throw u}let i=o?new Kx(e.toString(),{headers:{...o},agent:s}):new(Gx())(e.toString(),t?[`${Jx}${t}`]:void 0);this.socket=i;let a=!1,d=new Promise((c,u)=>{let l=!1,p=setTimeout(()=>{if(l)return;l=!0,a=!0;let m=new Le("hub_connect_timeout",`Timed out connecting to hub after ${aa}ms`);if(this.socket===i)this.lastCloseError=m,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}u(m)},aa);i.addEventListener("open",()=>{if(l)return;l=!0,clearTimeout(p),c()}),i.addEventListener("error",(m)=>{if(l)return;l=!0,clearTimeout(p);let g=wu(m,e);if(this.socket===i)this.lastCloseError=g,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;u(g)}),i.addEventListener("close",(m)=>{if(l)return;l=!0,clearTimeout(p);let g=a?this.lastCloseError:By(m);if(this.socket===i){if(!a)this.lastCloseError=g,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}u(g)})});return i.addEventListener("message",(c)=>{this.handleFrame(JSON.parse(jy(c)))}),i.addEventListener("close",(c)=>{if(this.socket!==i)return;if(!a)this.lastCloseError=By(c),this.sawSocketClose=!0;this.registered=!1;for(let u of this.pendingReplies.values())u.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await d,i}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=Hx("hubreq_");r?.onDispatch?.(s);let i=Wx(e,r?.timeoutMs),a=new Promise((c,u)=>{let l=i===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(s))return;u(new da(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===ea){let c=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new qr(c,d.error.message)}throw new da(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Cu(this.currentUrl)||!nM(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(eM*2**this.reconnectAttempt,tM),t=Math.round(e*(1-$y)+Math.random()*e*$y);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(!Cu(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 Le("hub_connection_closed",Iu);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 Le("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??ku}subscriptionSessionIdFromKey(e){return e===ku?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[ku,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 ca(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 Gn({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 Ru(e,t){let n=ca(e),r=await Qt(n,{authToken:t?.authToken});if(!r)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=Ut(),s=jn(r,o);if(!s.compatible&&!zr(r))return{status:s.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!Bx(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 oM(e){let t=Date.now()+Qx;while(Date.now()<t){if(!(await Qt(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,Zx))}return!1}function sM(e,t){try{return ca(e)===ca(t)}catch{return!1}}function Ky(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 a5(e){return Ky(e).activeSessionCount>0}async function Xr(e,t,n){let r=new Gn({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:Yx});return Ky(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function Gy(e,t,n){try{return(await Xr(e,t,n)).activeSessionCount===0}catch{return!1}}async function iM(e,t){let n=`${e.discoveryPath}.superseded`,r=await Re(n);if(!r?.url||!r.authToken)return;let o=await Ru(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await Gy(o.url,r.authToken,t))return;return Vr(o.url,r.authToken)}async function aM(e={}){if(e.endpoint?.trim()){let o=await Ru(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=Eu(),n=await Re(t.discoveryPath);if(!n?.url)return await iM(t,e);let r=await Ru(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return Vr(r.url,n.authToken);if(r.status==="protocol_mismatch")await Yt(t.discoveryPath).catch(()=>{return});return}async function Au(e={}){let t=await aM(e);if(t&&await dt(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await ts(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function Kn(e,t,n,r){Wy();let o=new URL(e),s=t?.trim()||Pu(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 Tu(e,t){Wy();let n=new URL(e),r=t?.trim()||Pu(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 dM(e=Eu()){let t=await Re(e.discoveryPath,{onError:"throw"});if(!t?.url)return!1;try{if(await Tu(t.url,t.authToken))return!0}catch{}return!1}async function d5(e){if(!Cu(e.url))return;let t=Eu(),n=await Re(t.discoveryPath);if(!n?.url||!sM(n.url,e.url))return;if(!await Gy(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await dM())return;if(!await oM(n.url))return;return await Yt(t.discoveryPath).catch(()=>{return}),await Au({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveClineBuildEnv as cM}from"@cline/shared";function uM(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 lM="cline-hub-auth.";function pM(e){return e.host!==void 0||e.port!==void 0||e.pathname!==void 0}function mM(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 cM()==="production"?Ft():wt()}async function gM(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&&mM(e.toString(),r.url))return r.authToken;return}async function fM(e={}){let t=zn(e);if(!pM(e)){let n=Vy(),r=await Re(n.discoveryPath);if(r?.url)return r.url}return Zt(t.host,t.port,t.pathname)}async function Xy(e){return await new Promise((t,n)=>{(async()=>{let r=new URL(e),o=await gM(r);r.hash="";let s=new WebSocket(r.toString(),o?[`${lM}${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(uM(d,e))})})().catch(n)})}async function g5(e){try{return(await Xy(e)).close(),!0}catch{return!1}}async function f5(e,t){let n=await fM(e),r=await Xy(n);try{return await r.send({version:t.version??"v1",clientId:t.clientId??"hub-client",...t})}finally{r.close()}}import{existsSync as hM}from"node:fs";import{isHubDaemonProcess as yM,resolveClineBuildEnv as SM}from"@cline/shared";var bM=1e4,vM="CLINE_HUB_BUILD_WATCH_INTERVAL_MS";function TM(){let e=Number(process.env[vM]);return Number.isFinite(e)&&e>0?e:bM}async function wM(e,t){try{let n=await Xr(e.url,t);return{...e,activeSessionCount:n.activeSessionCount,participantClientCount:n.participantClientCount}}catch{return e}}function kM(){return SM()==="production"?Ft():wt()}function IM(e){try{return hM(`${e}.lock`)}catch{return!1}}async function CM(){let e=kM();if(IM(e.discoveryPath))return;let t=await Re(e.discoveryPath).catch(()=>{return});if(!t?.url)return;let n=await Qt(t.url).catch(()=>{return});if(!n?.url)return;let r=Ut(),o=jn(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 wM(s("outdated_hub"),t.authToken);return s("build_mismatch")}function w5(e){if(yM()||process.env.CLINE_HUB_PORT?.trim())return()=>{};let t=e.intervalMs??TM(),n,r,o=!1,s=setInterval(()=>{if(o)return;o=!0,CM().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 xu(e){return e?JSON.parse(JSON.stringify(e)):{}}function ua(e){let t=e?.session&&typeof e.session==="object"?e.session:void 0;if(!t)return;let n=t.metadata&&typeof t.metadata==="object"?xu(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 Jy(e,t){return e.error?.message??`hub command failed: ${t}`}function RM(e){let t=xu(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 Yy(e){let t=e?.sessionId;return typeof t==="string"&&t.trim()?t.trim():void 0}function AM(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 EM(e){let t=xu(e.payload);if(e.event==="schedule.execution_completed")return{sessionId:e.sessionId?.trim()||Yy(t)||"",eventType:"schedule.execution.completed",payload:t};if(e.event==="schedule.execution_failed")return{sessionId:e.sessionId?.trim()||Yy(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:RM(e.payload)};case"run.completed":return{sessionId:n,eventType:"runtime.chat.completed",payload:t};default:return}}class PM{client;constructor(e){this.client=new Gn({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,...e.plugins?{plugins:e.plugins}:{}}),n=ua(t.payload);if(!n?.sessionId)throw Error("hub session create returned no session id");let r=Array.isArray(t.payload?.pluginIssues)?t.payload.pluginIssues:void 0;return{sessionId:n.sessionId,startResult:{sessionId:n.sessionId,manifestPath:"",messagesPath:n.messagesPath??""},...r?.length?{pluginIssues:r}:{}}}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(ta(n))return;throw n}return ua(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(Jy(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,...r.plugins?{plugins:r.plugins}:{}}:{}},t);if(!o.ok)throw Error(Jy(o,"session.restore"));let s=ua(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=AM(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)=>ua({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=EM(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 _M{client;constructor(e){this.client=new Gn({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 fK}from"@cline/llms";import{readdirSync as Oz}from"node:fs";import{homedir as Lz}from"node:os";import{isAbsolute as Nz,join as dg,resolve as cg}from"node:path";import{captureSdkError as ht,createSessionId as Dz,isLikelyAuthError as Uz,normalizeUserInput as Fz}from"@cline/shared";import{setHomeDirIfUnset as Hz}from"@cline/shared/storage";import{decodeJwtPayload as CO,getClineEnvironmentConfig as bS}from"@cline/shared";import{setTimeout as Zy}from"node:timers/promises";import{decodeJwtPayload as UM,getClineEnvironmentConfig as FM}from"@cline/shared";import{createHash as xM}from"node:crypto";var MM;function Ze(e){if(typeof e!=="string"||e.length===0)return"unset";return xM("sha256").update(e).digest("hex").slice(0,8)}function ce(e){try{MM?.debug(e)}catch{}}function OM(){let e;return{promise:new Promise((n)=>{e=n}),resolve:e}}async function Vn(e){let t=await import("node:http"),n=e.host??"127.0.0.1",r=e.timeoutMs??300000,o=e.successHtml??LM,s=OM(),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 LM=`<!DOCTYPE html>
322
322
  <html lang="en">