@cline/core 0.0.89-nightly.1790822319 → 0.0.89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hub/index.js
CHANGED
|
@@ -307,7 +307,7 @@ ${JSON.stringify(r,null,2)}`}startClaimLeaseHeartbeat(e){let t=Math.max(1000,Mat
|
|
|
307
307
|
scheduled_for = COALESCE(?, scheduled_for),
|
|
308
308
|
updated_at = ?
|
|
309
309
|
WHERE run_id = ? AND claim_token = ?`).run(e.releaseAttempt?1:0,e.error??null,e.scheduledFor??null,t,e.runId,e.claimToken).changes??0)>0}attachSessionIdToRun(e,t,n){return(this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ? AND claim_token = ? AND status = 'running'").run(t,Ae(),e,n).changes??0)===1}attachReportPathToRun(e,t){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(t,Ae(),e)}}function Ni(e){return e?new Date(e).getTime():void 0}function wE(e){let t=e.metadata?{...e.metadata}:void 0;if(t)delete t.__hubScheduleCreatedBy,delete t.__hubScheduleCwd,delete t.__hubRuntimeOptions;return t}function No(e){let t=e.metadata;return{scheduleId:e.externalId,name:e.title,cronPattern:e.triggerKind==="one_off"?Do: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:Ni(e.nextRunAt),lastRunAt:Ni(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:wE(e)}}function kE(e){switch(e){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function Nc(e,t){return{executionId:e.runId,scheduleId:t,sessionId:e.sessionId,triggeredAt:new Date(e.scheduledFor??e.createdAt).getTime(),startedAt:Ni(e.startedAt),endedAt:Ni(e.completedAt),status:kE(e.status),errorMessage:e.error}}class Di{store;materializer;runner;started=!1;disposed=!1;constructor(e){this.store=new Lo({dbPath:e.dbPath}),this.materializer=new Ao({store:this.store}),this.runner=new Po({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===Do?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 No(this.store.createHubSchedule({...e,timezone:t}))}getSchedule(e){let t=this.store.getHubSchedule(e);return t?No(t):void 0}listSchedules(e={}){return this.store.listHubSchedules(e).map((t)=>No(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=No(n),i=t.cronPattern??s.cronPattern;if(i.trim()===Do&&typeof t.timezone==="string"&&t.timezone.trim())throw Error("timezone is only supported for recurring schedules");if(this.validateScheduleTiming(i,i.trim()===Do?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?No(a):void 0}validateScheduleTiming(e,t,n,r){if(e.trim()!==Do){Yf(e),Mc(t);return}if(t?.trim())throw Error("timezone is only supported for recurring schedules");let o=n?.[TE];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 Nc(n,e)}triggerScheduleNowDetached(e){let t=this.store.enqueueHubScheduleRun(e,"manual");if(!t)return;return this.runner.tick().catch(()=>{return}),Nc(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 Nc(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 Uc,statSync as CE}from"node:fs";import{isAbsolute as dh,relative as IE,sep as ch}from"node:path";import{ONE_TIME_SCHEDULE_CRON_PATTERN as uh,ONE_TIME_SCHEDULE_RUN_AT_METADATA_KEY as lh}from"@cline/shared";import{z as he}from"zod";var AE=he.enum(["create","update","list","get","pause","resume","delete","run_now"]),RE=he.object({provider_id:he.string().min(1),model_id:he.string().min(1).optional()}),Mr=he.object({operation:AE,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:RE.optional(),limit:he.number().int().positive().max(200).optional()});function Pr(e,t,n,r){if(!ph.has(t.operation))return;dn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.scheduled.${t.operation}`,success:r,agentId:n.agentId})}var ph=new Set(["create","update","pause","resume","delete","run_now"]);function xr(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Hc(e,t){try{let n=Uc.native(e);if(!CE(n).isDirectory())throw Error("not a directory");return n}catch{throw Error(`${t} does not resolve to an existing safe path`)}}function EE(e,t){try{return Uc.native(e)===Uc.native(t)}catch{return!1}}function mh(e,t,n){let r=IE(e,t);if(r===".."||r.startsWith(`..${ch}`)||dh(r))throw Error(`${n} is outside the workspace scope`)}function gh(e,t,n){return Hc(dh(t)?t:`${e}${ch}${t}`,n)}function PE(e){let t=Hc(e.workspaceRoot,"workspaceRoot"),n=e.cwd?gh(t,e.cwd,"cwd"):t;return mh(t,n,"cwd"),{...e,workspaceRoot:t,cwd:n}}function _r(e,t){if(!e)throw Error("schedule does not exist");if(!EE(e.workspaceRoot,t.workspaceRoot))throw Error("schedule is outside this session's workspace scope");let n=Hc(e.workspaceRoot,"schedule workspaceRoot");if(e.cwd){let r=gh(n,e.cwd,"schedule cwd");mh(n,r,"schedule cwd")}}function ah(e){if(!e)return;return{providerId:e.provider_id.trim(),modelId:e.model_id?.trim()||void 0}}function Dc(e){if(!e)return;return[...new Set(e.map((t)=>t.trim()).filter(Boolean))]}function fh(e){let t=Date.parse(xr(e,"run_at"));if(!Number.isFinite(t))throw Error("run_at must be an ISO timestamp");if(t<=Date.now())throw Error("run_at must be in the future");return t}function _E(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:uh,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:xr(e.cron_pattern,"cron_pattern"),timezone:e.timezone?.trim()||void 0}}throw Error("schedule_type is required for create")}function xE(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:uh,timezone:null,metadata:{[lh]:fh(e.run_at)}}}if(e.schedule_type==="recurring"||e.cron_pattern)return{cronPattern:xr(e.cron_pattern,"cron_pattern"),timezone:e.timezone===null?null:e.timezone?.trim()||void 0};return{timezone:e.timezone===null?null:e.timezone?.trim()||void 0}}function Uo(e){return xr(e.schedule_id,"schedule_id")}async function Fc(e,t,n){let r=Mr.safeParse(t);if(!r.success)return{ok:!1,error:{code:"invalid_schedule_input",message:r.error.issues[0]?.message??"Invalid schedule input"}};let o=r.data;try{if(!n.sessionId)throw Error("tasks requires a Hub session");let s=await e.resolveSessionDefaults(n.sessionId);if(!s?.workspaceRoot.trim())throw Error("tasks could not resolve the current workspace");let i=PE(s);if(ph.has(o.operation)&&!i.interactive)throw Error("schedule mutations require an interactive user session");switch(o.operation){case"create":{let a=e.schedules.createSchedule({name:xr(o.name,"name"),..._E(o),prompt:xr(o.prompt,"prompt"),workspaceRoot:i.workspaceRoot,cwd:i.cwd,modelSelection:ah(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:Dc(o.tags)});return e.publish?.("schedule.created",{schedule:a},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:a}}case"update":{let a=Uo(o);_r(e.schedules.getSchedule(a),i);let d=e.schedules.updateSchedule(a,{scheduleId:a,...xE(o),name:o.name?.trim()||void 0,prompt:o.prompt?.trim()||void 0,modelSelection:ah(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:Dc(o.tags)});if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.updated",{schedule:d},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"list":{let a=e.schedules.listSchedules({enabled:o.enabled,tags:Dc(o.tags),workspaceRoot:i.workspaceRoot,limit:o.limit??50}).filter((d)=>{try{return _r(d,i),!0}catch{return!1}}).slice(0,o.limit??50);return{ok:!0,operation:o.operation,schedules:a}}case"get":{let a=e.schedules.getSchedule(Uo(o));return _r(a,i),{ok:!0,operation:o.operation,schedule:a}}case"pause":case"resume":{let a=Uo(o);_r(e.schedules.getSchedule(a),i);let d=o.operation==="pause"?e.schedules.pauseSchedule(a):e.schedules.resumeSchedule(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.updated",{schedule:d},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"delete":{let a=Uo(o);_r(e.schedules.getSchedule(a),i);let d=e.schedules.deleteSchedule(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.deleted",{deleted:d,scheduleId:a},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,deleted:d}}case"run_now":{let a=Uo(o);_r(e.schedules.getSchedule(a),i);let d=e.schedules.triggerScheduleNowDetached(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.triggered",{execution:d},n.sessionId),Pr(e,o,n,!0),{ok:!0,operation:o.operation,execution:d}}}}catch(s){return Pr(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"schedule_operation_failed",message:s instanceof Error?s.message:String(s)}}}}import{LangfuseAttributesSpanProcessor as rP}from"@cline/llms";import{markOtlpTraceRelayProvider as oP}from"@cline/shared";import{metrics as sP,trace as iP}from"@opentelemetry/api";import{logs as aP}from"@opentelemetry/api-logs";import{OTLPLogExporter as dP}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as cP}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as uP}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as lP}from"@opentelemetry/resources";import{BatchLogRecordProcessor as pP,ConsoleLogRecordExporter as mP,LoggerProvider as gP}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as fP,MeterProvider as hP,PeriodicExportingMetricReader as Oh}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as yP,ConsoleSpanExporter as SP,SimpleSpanProcessor as bP}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as vP}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as TP,ATTR_SERVICE_VERSION as wP}from"@opentelemetry/semantic-conventions";import{mkdirSync as ME,readFileSync as OE,statSync as LE,writeFileSync as NE}from"node:fs";import{dirname as DE}from"node:path";import{CONFIGURABLE_MODEL_TOOL_NAMES as hh}from"@cline/shared";import{resolveGlobalSettingsPath as yh}from"@cline/shared/storage";import{z as He}from"zod";var Bc=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}),UE=He.enum(["basic","agentic"]).catch("agentic"),HE=He.partialRecord(He.enum(hh),He.object({enabled:He.boolean()}).strip()).optional(),FE=He.enum(["plan","act"]),$c=He.object({telemetryOptOut:He.boolean().default(!1).catch(!1),autoUpdateEnabled:He.boolean().default(!0).catch(!0),compactionStrategy:UE.optional(),compactionEnabled:He.boolean().optional().catch(void 0),planActMode:FE.optional().catch(void 0),toolAutoApprove:He.boolean().optional().catch(void 0),tuiTheme:He.string().optional().catch(void 0),disabledTools:Bc.optional(),tools:HE,disabledPlugins:Bc.optional(),disabledAgentPlugins:Bc.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 Ui(){return $c.parse({})}var Hi;function BE(){Hi=void 0}function $E(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 WE(e){let t;try{t=OE(e,"utf8")}catch{return{value:Ui(),loadFailed:!0}}try{let n=$c.safeParse(JSON.parse(t));return n.success?{value:n.data,loadFailed:!1}:{value:Ui(),loadFailed:!0}}catch{return{value:Ui(),loadFailed:!0}}}function Sh(){let e=yh(),t=LE(e,{throwIfNoEntry:!1}),n=t?.mtimeMs??0,r=t?.size??0,o=Hi;if(o&&o.path===e&&o.mtimeMs===n&&o.size===r)return o;let s=t?WE(e):{value:Ui(),loadFailed:!1},i=$E(s.value);return Hi={path:e,mtimeMs:n,size:r,value:i,loadFailed:s.loadFailed},Hi}function at(){return Sh().value}function Ho(e,t={}){let n=yh(),r=at();ME(DE(n),{recursive:!0});let o=$c.parse(e);if(!r.telemetryOptOut&&o.telemetryOptOut)lf(t.telemetry);NE(n,`${JSON.stringify(o,null,2)}
|
|
310
|
-
`,"utf8"),BE()}function bh(){return at().telemetryOptOut}function Nn(e){return new Set(e??at().disabledTools??[])}function vh(e){return new Set(e??at().disabledPlugins??[])}function Fo(e){return new Set(e??at().disabledAgentPlugins??[])}function Th(e){return hh.includes(e)}function jE(){let e=Sh();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function Wc(e){return jE()[e]?.enabled===!0}function qE(e,t){let n=at();Ho({...n,tools:{...n.tools,[e]:{enabled:t}}})}function wh(e){if(Th(e)){let o=Wc(e);return qE(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 Ho({...t,disabledTools:[...n]}),!r}function zE(e,t){let n=[...new Set(e.map((i)=>i.trim()).filter(Boolean))];if(n.length===0)return;let r=at(),o=Nn(r.disabledTools),s={...r.tools};for(let i of n){if(Th(i)){s[i]={enabled:!t};continue}if(t)o.add(i);else o.delete(i)}Ho({...r,disabledTools:[...o],tools:s})}function kh(e,t){return zE([e],t),t}function Ch(e,t){let n=e.trim();if(!n)return;let r=at(),o=vh(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Ho({...r,disabledPlugins:[...o]})}function Ih(e,t){let n=e.trim();if(!n)return;let r=at(),o=Fo(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Ho({...r,disabledAgentPlugins:[...o]})}function Ah(e,t){let n=vh(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r))}function Dn(e,t){let n=Nn(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r.name))}function Rh(e,t){if(!e||e.length===0)return e;let n=Nn(t);if(n.size===0)return e;return e.map((r)=>{if(!r.setup)return r;return{...r,setup:(o,s)=>r.setup?.({...o,registerTool:(i)=>{if(!n.has(i.name))o.registerTool(i)}},s)}})}import{existsSync as KE,mkdirSync as GE,readFileSync as VE,writeFileSync as XE}from"node:fs";import{resolve as JE}from"node:path";import{resolveSessionDataDir as YE}from"@cline/shared/storage";import{nanoid as QE}from"nanoid";import*as ZE from"node-machine-id";var eP="machine-id",Eh,Ph=!1;function _h(){if(!Ph)Eh=xh(),Ph=!0;return Eh??Mh()}function Bo(e){let t=e?.trim();if(t)return t;let n=xh();if(n)return n;return Mh()}function tP(){let e=ZE;return e.machineIdSync??e.default?.machineIdSync}function xh(){try{let e=tP();if(!e)return;return e().trim()||void 0}catch{return}}function Mh(){let e=YE(),t=JE(e,eP);try{if(KE(t)){let r=VE(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${QE()}`;try{GE(e,{recursive:!0}),XE(t,n,"utf8")}catch{}return n}class jc{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(e){this.name=e.name??"OpenTelemetryAdapter",this.metadata={...e.metadata},this.meterProvider=e.meterProvider,this.loggerProvider=e.loggerProvider,this.meter=e.meterProvider?.getMeter("cline")??null,this.logger=e.loggerProvider?.getLogger("cline")??null,this.enabled=e.enabled??!0,this.distinctId=e.distinctId,this.commonProperties=e.commonProperties?{...e.commonProperties}:{}}emit(e,t){if(!this.isEnabled())return;this.emitLog(e,t,!1)}emitRequired(e,t){this.emitLog(e,t,!0)}recordCounter(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.counters.get(e);if(!s)s=this.meter.createCounter(e,r?{description:r}:void 0),this.counters.set(e,s);s.add(t,this.flattenProperties(this.buildAttributes(n)))}recordHistogram(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.histograms.get(e);if(!s)s=this.meter.createHistogram(e,r?{description:r}:void 0),this.histograms.set(e,s);s.record(t,this.flattenProperties(this.buildAttributes(n)))}recordGauge(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.buildAttributes(n),i=JSON.stringify(s),a=this.gaugeValues.get(e);if(t===null){if(a){if(a.delete(i),a.size===0)this.gaugeValues.delete(e),this.gauges.delete(e)}return}let d=a;if(!d)d=new Map,this.gaugeValues.set(e,d);if(!this.gauges.has(e)){let c=this.meter.createObservableGauge(e,r?{description:r}:void 0);c.addCallback((u)=>{for(let l of this.snapshotGaugeSeries(e))u.observe(l.value,this.flattenProperties(l.attributes))}),this.gauges.set(e,c)}d.set(i,{value:t,attributes:s})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(e){this.distinctId=e}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(e,t,n){if(!this.logger)return;let r=this.flattenProperties(this.buildAttributes(t,n));this.logger.emit({severityText:"INFO",body:e,attributes:r})}buildAttributes(e,t=!1){return{...this.commonProperties,...this.metadata,...e,...this.distinctId?{distinct_id:this.distinctId}:{},...t?{_required:!0}:{}}}snapshotGaugeSeries(e){let t=this.gaugeValues.get(e);if(!t)return[];return Array.from(t.values(),(n)=>({value:n.value,attributes:n.attributes?{...n.attributes}:void 0}))}flattenProperties(e,t="",n=new WeakSet,r=0){if(!e)return{};let o={},s=100,i=10;for(let[a,d]of Object.entries(e)){if(a==="__proto__"||a==="constructor"||a==="prototype")continue;let c=t?`${t}.${a}`:a;if(d===null||d===void 0){o[c]=String(d);continue}if(Array.isArray(d)){let u=d.length>s?d.slice(0,s):d;try{o[c]=JSON.stringify(u)}catch{o[c]="[UnserializableArray]"}if(d.length>s)o[`${c}_truncated`]=!0,o[`${c}_original_length`]=d.length;continue}if(typeof d==="object"){if(d instanceof Date){o[c]=d.toISOString();continue}if(d instanceof Error){o[c]=d.message;continue}if(n.has(d)){o[c]="[Circular]";continue}if(r>=i){o[c]="[MaxDepthExceeded]";continue}n.add(d),Object.assign(o,this.flattenProperties(d,c,n,r+1));continue}if(nP(d)){o[c]=d;continue}try{o[c]=JSON.stringify(d)}catch{o[c]=String(d)}}return o}}function nP(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class qc{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 Fi{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new qc({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??_h(),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 Lh{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 Nh{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=lP({[TP]:e.serviceName??"cline",...e.serviceVersion?{[wP]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)sP.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)aP.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return iP.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new jc({...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 Fi({...e,adapters:[t],distinctId:Bo(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=zc(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)=>RP(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 hP({resource:e,readers:o})}createTracerProvider(e){let t=zc(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=AP(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 vP({resource:e,spanProcessors:s?[new rP,...o]:o});if(s)oP(i);return i}createLoggerProvider(e){let t=zc(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=IP(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new pP(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 gP({resource:e,processors:n})}}function kP(e){let t=new Nh(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 Dh(e){if(bh())return{telemetry:new Lh(e)};if(e.enabled!==!0)return{telemetry:new Fi({...e,distinctId:Bo(e.distinctId)})};return kP(e)}function CP(e){let{telemetry:t,provider:n,emitProviderCreated:r}=Dh(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 zc(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function IP(e,t){if(e==="console")return new mP;if(!t.endpoint)return null;let n=Kc(t.endpoint,"/v1/logs");return new dP({url:n,headers:t.headers})}function AP(e,t){if(e==="console")return new bP(new SP);if(!t.endpoint)return null;let n=Kc(t.endpoint,"/v1/traces");return new yP(new uP({url:n,headers:t.headers}))}function RP(e,t){if(e==="console")return new Oh({exporter:new fP,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=Kc(t.endpoint,"/v1/metrics");return new Oh({exporter:new cP({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function Kc(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 MP,zodToJsonSchema as OP}from"@cline/shared";import{z as xt}from"zod";import{resolve as Uh}from"node:path";import{z as Y}from"zod";var Hh=Y.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),EP=Y.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),Fh=Y.union([Y.literal(0),Y.literal(1),Y.literal(2),Y.literal(3),Y.literal(4),Y.literal(5)]),PP=Y.object({provider_id:Y.string().min(1),model_id:Y.string().min(1).optional()}),Bi=Y.object({operation:Y.enum(["create","update","list","get"]),task_id:Y.string().min(1).optional(),expected_revision:Y.number().int().positive().optional(),type:Hh.optional(),title:Y.string().min(1).optional(),description:Y.string().nullable().optional(),instructions:Y.string().min(1).optional(),scope:Y.enum(["workspace","global"]).optional(),workspace_root:Y.string().min(1).nullable().optional(),cwd:Y.string().min(1).nullable().optional(),resource_paths:Y.array(Y.string().min(1)).optional(),priority:Fh.optional(),assignee:Y.string().min(1).nullable().optional(),model_selection:PP.nullable().optional(),mode:Y.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Y.string().nullable().optional(),max_iterations:Y.number().int().positive().nullable().optional(),timeout_seconds:Y.number().int().positive().nullable().optional(),available_at:Y.string().datetime().optional(),expires_at:Y.string().datetime().optional(),automation_eligible:Y.boolean().optional(),statuses:Y.array(EP).optional(),types:Y.array(Hh).optional(),priorities:Y.array(Fh).optional(),limit:Y.number().int().positive().max(500).optional()}),_P=new Set(["create","update"]);function Gc(e,t,n,r){if(!_P.has(t.operation))return;dn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.todo.${t.operation}`,success:r,agentId:n.agentId})}function Or(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Bh(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function Wh(e,t){return Uh(e)===Uh(t)}function $h(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!Wh(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 xP(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||!Wh(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function jh(e,t,n){let r=Bi.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=xP(o,i);switch(o.operation){case"create":{let d={type:Or(o.type,"type"),title:Or(o.title,"title"),description:o.description??void 0,instructions:Or(o.instructions,"instructions"),scope:a,workspaceRoot:i.workspaceRoot,cwd:a==="workspace"?(o.cwd??i.cwd)?.trim()||void 0:void 0,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee??void 0,modelSelection:Bh(o.model_selection)??i.modelSelection,mode:o.mode??void 0,systemPrompt:o.system_prompt??void 0,maxIterations:o.max_iterations??void 0,timeoutSeconds:o.timeout_seconds??void 0,availableAt:o.available_at,expiresAt:Or(o.expires_at,"expires_at"),automationEligible:o.automation_eligible,createdBy:s,originSessionId:n.sessionId,originTaskId:i.originTaskId},c={ok:!0,operation:o.operation,task:await e.manager.createTask(d)};return Gc(e,o,n,!0),c}case"update":{let d=Or(o.task_id,"task_id");if($h(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:Bh(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 Gc(e,o,n,!0),c}case"list":{let d={statuses:o.statuses,types:o.types,scope:a,workspaceRoot:i.workspaceRoot,priorities:o.priorities,automationEligible:o.automation_eligible,limit:o.limit};return{ok:!0,operation:o.operation,tasks:await e.manager.listTasks(d)}}case"get":{let d=await e.manager.getTask(Or(o.task_id,"task_id"));return $h(d,i),{ok:!0,operation:o.operation,task:d}}}}catch(i){return Gc(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:i instanceof Error?i.message:String(i)}}}}var $o="tasks",qh='# 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.',LP="# 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.",NP=Bi.extend({kind:xt.literal("todo")}).strict(),zh=Mr.extend({kind:xt.literal("scheduled")}).strict(),Kh=xt.discriminatedUnion("kind",[NP,zh]),DP=xt.discriminatedUnion("kind",[zh]),Gh=["create","update","list","get","pause","resume","delete","run_now"],UP=xt.object({...Mr.shape,...Bi.shape,kind:xt.enum(["todo","scheduled"]),operation:xt.enum(Gh)}).strict(),HP=xt.object({...Mr.shape,kind:xt.enum(["scheduled"]),operation:xt.enum(Gh)}).strict();function Vc(e){let t=e.todo;return MP({name:$o,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:OP(t?UP:HP),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?Kh:DP).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 jh(t,o.data,r)}}return{kind:"scheduled",...await Fc(e.scheduled,o.data,r)}}})}function Xc(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?LP:qh,whenToolAvailable:$o})}}}import{createSessionId as Y_,ensureLoopbackProxyBypass as by,isHubProtocolCompatible as Q_,resolveClineBuildEnv as Z_,resolveHubCommandTimeoutMs as ex}from"@cline/shared";import tx from"ws";var $i="0.0.89-nightly.1790822319";var ln={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:$i,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var Wi="session_not_found";class Lr extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function ji(e){return e instanceof Lr||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as S_}from"node:child_process";import{closeSync as b_,mkdirSync as v_,openSync as T_,readFileSync as w_,unlinkSync as k_}from"node:fs";import{basename as C_,dirname as I_,join as A_}from"node:path";import{fileURLToPath as R_}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as E_,isBunEmbeddedModulePath as P_,isHubDaemonProcess as py,resolveClineBuildEnv as my,withResolvedClineBuildEnv as __}from"@cline/shared";import{createHash as FP,randomBytes as ey}from"node:crypto";import{existsSync as BP}from"node:fs";import{mkdir as Yc,open as Xh,readFile as ty,rename as $P,rm as qi,writeFile as WP}from"node:fs/promises";import{dirname as ny,join as Qc}from"node:path";import{ensureLoopbackProxyBypass as jP,isHubProtocolCompatible as qP}from"@cline/shared";import{resolveClineDataDir as Wo,resolveClineDir as SJ}from"@cline/shared/storage";var zP="CLINE_HUB_DISCOVERY_PATH",KP="CLINE_HUB_BUILD_ID",GP="CLINE_HUB_BUILD_EPOCH_MS",VP=30000,XP=15000,Jh=100;function JP(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function YP(e){return FP("sha256").update(e).digest("hex").slice(0,12)}function QP(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 ry(){return ey(32).toString("hex")}function Yh(e){return new Promise((t)=>setTimeout(t,e))}function ZP(e){return`${e}.lock`}async function e_(e){try{let t=JSON.parse(await ty(Qc(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 Jc(e){await qi(e,{recursive:!0,force:!0}).catch(()=>{return})}function Mt(){let e=process.env[KP]?.trim();if(e)return e;return"sdk-v1-6c2e124548c958dc2dfce34aaa351c6fe8916e64d8c8528ac24875d5232f6140".trim()||`source-${String(ln.version)}`}function Zc(){let e=Number(process.env[GP]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790822344987)?1790822344987:void 0}function Un(e,t=Mt()){let n=qP(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 Qh(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function Zh(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 t_(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 jo(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=Qh(e.buildEpochMs),s=Qh(t.buildEpochMs);if(o!==void 0&&s!==void 0&&o!==s)return o<s?-1:1;let i=Zh(e.coreVersion),a=Zh(t.coreVersion);if(i&&a){let d=t_(i,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function qo(){return{buildId:Mt(),buildEpochMs:Zc(),coreVersion:String(ln.version)}}function Nr(e,t){let n=t?.self??qo(),r=Un(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return jo(n,e)<=0}function Hn(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${YP(e)}`,n=process.env[zP]?.trim()||Qc(Wo(),"locks","hub","owners",`${JP(t)}.json`);return{ownerId:t,discoveryPath:n}}function vJ(e=`hub-${Date.now().toString(36)}`){return Hn(e)}async function Re(e){try{let t=JSON.parse(await ty(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function zi(e,t){await eu(e,async()=>{let n=ny(e);await Yc(n,{recursive:!0});let r=`${e}.${process.pid}.${ey(6).toString("hex")}.tmp`,o;try{o=await Xh(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
|
|
310
|
+
`,"utf8"),BE()}function bh(){return at().telemetryOptOut}function Nn(e){return new Set(e??at().disabledTools??[])}function vh(e){return new Set(e??at().disabledPlugins??[])}function Fo(e){return new Set(e??at().disabledAgentPlugins??[])}function Th(e){return hh.includes(e)}function jE(){let e=Sh();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function Wc(e){return jE()[e]?.enabled===!0}function qE(e,t){let n=at();Ho({...n,tools:{...n.tools,[e]:{enabled:t}}})}function wh(e){if(Th(e)){let o=Wc(e);return qE(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 Ho({...t,disabledTools:[...n]}),!r}function zE(e,t){let n=[...new Set(e.map((i)=>i.trim()).filter(Boolean))];if(n.length===0)return;let r=at(),o=Nn(r.disabledTools),s={...r.tools};for(let i of n){if(Th(i)){s[i]={enabled:!t};continue}if(t)o.add(i);else o.delete(i)}Ho({...r,disabledTools:[...o],tools:s})}function kh(e,t){return zE([e],t),t}function Ch(e,t){let n=e.trim();if(!n)return;let r=at(),o=vh(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Ho({...r,disabledPlugins:[...o]})}function Ih(e,t){let n=e.trim();if(!n)return;let r=at(),o=Fo(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Ho({...r,disabledAgentPlugins:[...o]})}function Ah(e,t){let n=vh(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r))}function Dn(e,t){let n=Nn(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r.name))}function Rh(e,t){if(!e||e.length===0)return e;let n=Nn(t);if(n.size===0)return e;return e.map((r)=>{if(!r.setup)return r;return{...r,setup:(o,s)=>r.setup?.({...o,registerTool:(i)=>{if(!n.has(i.name))o.registerTool(i)}},s)}})}import{existsSync as KE,mkdirSync as GE,readFileSync as VE,writeFileSync as XE}from"node:fs";import{resolve as JE}from"node:path";import{resolveSessionDataDir as YE}from"@cline/shared/storage";import{nanoid as QE}from"nanoid";import*as ZE from"node-machine-id";var eP="machine-id",Eh,Ph=!1;function _h(){if(!Ph)Eh=xh(),Ph=!0;return Eh??Mh()}function Bo(e){let t=e?.trim();if(t)return t;let n=xh();if(n)return n;return Mh()}function tP(){let e=ZE;return e.machineIdSync??e.default?.machineIdSync}function xh(){try{let e=tP();if(!e)return;return e().trim()||void 0}catch{return}}function Mh(){let e=YE(),t=JE(e,eP);try{if(KE(t)){let r=VE(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${QE()}`;try{GE(e,{recursive:!0}),XE(t,n,"utf8")}catch{}return n}class jc{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(e){this.name=e.name??"OpenTelemetryAdapter",this.metadata={...e.metadata},this.meterProvider=e.meterProvider,this.loggerProvider=e.loggerProvider,this.meter=e.meterProvider?.getMeter("cline")??null,this.logger=e.loggerProvider?.getLogger("cline")??null,this.enabled=e.enabled??!0,this.distinctId=e.distinctId,this.commonProperties=e.commonProperties?{...e.commonProperties}:{}}emit(e,t){if(!this.isEnabled())return;this.emitLog(e,t,!1)}emitRequired(e,t){this.emitLog(e,t,!0)}recordCounter(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.counters.get(e);if(!s)s=this.meter.createCounter(e,r?{description:r}:void 0),this.counters.set(e,s);s.add(t,this.flattenProperties(this.buildAttributes(n)))}recordHistogram(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.histograms.get(e);if(!s)s=this.meter.createHistogram(e,r?{description:r}:void 0),this.histograms.set(e,s);s.record(t,this.flattenProperties(this.buildAttributes(n)))}recordGauge(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let s=this.buildAttributes(n),i=JSON.stringify(s),a=this.gaugeValues.get(e);if(t===null){if(a){if(a.delete(i),a.size===0)this.gaugeValues.delete(e),this.gauges.delete(e)}return}let d=a;if(!d)d=new Map,this.gaugeValues.set(e,d);if(!this.gauges.has(e)){let c=this.meter.createObservableGauge(e,r?{description:r}:void 0);c.addCallback((u)=>{for(let l of this.snapshotGaugeSeries(e))u.observe(l.value,this.flattenProperties(l.attributes))}),this.gauges.set(e,c)}d.set(i,{value:t,attributes:s})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(e){this.distinctId=e}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(e,t,n){if(!this.logger)return;let r=this.flattenProperties(this.buildAttributes(t,n));this.logger.emit({severityText:"INFO",body:e,attributes:r})}buildAttributes(e,t=!1){return{...this.commonProperties,...this.metadata,...e,...this.distinctId?{distinct_id:this.distinctId}:{},...t?{_required:!0}:{}}}snapshotGaugeSeries(e){let t=this.gaugeValues.get(e);if(!t)return[];return Array.from(t.values(),(n)=>({value:n.value,attributes:n.attributes?{...n.attributes}:void 0}))}flattenProperties(e,t="",n=new WeakSet,r=0){if(!e)return{};let o={},s=100,i=10;for(let[a,d]of Object.entries(e)){if(a==="__proto__"||a==="constructor"||a==="prototype")continue;let c=t?`${t}.${a}`:a;if(d===null||d===void 0){o[c]=String(d);continue}if(Array.isArray(d)){let u=d.length>s?d.slice(0,s):d;try{o[c]=JSON.stringify(u)}catch{o[c]="[UnserializableArray]"}if(d.length>s)o[`${c}_truncated`]=!0,o[`${c}_original_length`]=d.length;continue}if(typeof d==="object"){if(d instanceof Date){o[c]=d.toISOString();continue}if(d instanceof Error){o[c]=d.message;continue}if(n.has(d)){o[c]="[Circular]";continue}if(r>=i){o[c]="[MaxDepthExceeded]";continue}n.add(d),Object.assign(o,this.flattenProperties(d,c,n,r+1));continue}if(nP(d)){o[c]=d;continue}try{o[c]=JSON.stringify(d)}catch{o[c]=String(d)}}return o}}function nP(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class qc{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 Fi{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new qc({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??_h(),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 Lh{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 Nh{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=lP({[TP]:e.serviceName??"cline",...e.serviceVersion?{[wP]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)sP.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)aP.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return iP.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new jc({...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 Fi({...e,adapters:[t],distinctId:Bo(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=zc(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)=>RP(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 hP({resource:e,readers:o})}createTracerProvider(e){let t=zc(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=AP(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 vP({resource:e,spanProcessors:s?[new rP,...o]:o});if(s)oP(i);return i}createLoggerProvider(e){let t=zc(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=IP(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new pP(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 gP({resource:e,processors:n})}}function kP(e){let t=new Nh(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 Dh(e){if(bh())return{telemetry:new Lh(e)};if(e.enabled!==!0)return{telemetry:new Fi({...e,distinctId:Bo(e.distinctId)})};return kP(e)}function CP(e){let{telemetry:t,provider:n,emitProviderCreated:r}=Dh(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 zc(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function IP(e,t){if(e==="console")return new mP;if(!t.endpoint)return null;let n=Kc(t.endpoint,"/v1/logs");return new dP({url:n,headers:t.headers})}function AP(e,t){if(e==="console")return new bP(new SP);if(!t.endpoint)return null;let n=Kc(t.endpoint,"/v1/traces");return new yP(new uP({url:n,headers:t.headers}))}function RP(e,t){if(e==="console")return new Oh({exporter:new fP,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=Kc(t.endpoint,"/v1/metrics");return new Oh({exporter:new cP({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function Kc(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 MP,zodToJsonSchema as OP}from"@cline/shared";import{z as xt}from"zod";import{resolve as Uh}from"node:path";import{z as Y}from"zod";var Hh=Y.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),EP=Y.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),Fh=Y.union([Y.literal(0),Y.literal(1),Y.literal(2),Y.literal(3),Y.literal(4),Y.literal(5)]),PP=Y.object({provider_id:Y.string().min(1),model_id:Y.string().min(1).optional()}),Bi=Y.object({operation:Y.enum(["create","update","list","get"]),task_id:Y.string().min(1).optional(),expected_revision:Y.number().int().positive().optional(),type:Hh.optional(),title:Y.string().min(1).optional(),description:Y.string().nullable().optional(),instructions:Y.string().min(1).optional(),scope:Y.enum(["workspace","global"]).optional(),workspace_root:Y.string().min(1).nullable().optional(),cwd:Y.string().min(1).nullable().optional(),resource_paths:Y.array(Y.string().min(1)).optional(),priority:Fh.optional(),assignee:Y.string().min(1).nullable().optional(),model_selection:PP.nullable().optional(),mode:Y.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Y.string().nullable().optional(),max_iterations:Y.number().int().positive().nullable().optional(),timeout_seconds:Y.number().int().positive().nullable().optional(),available_at:Y.string().datetime().optional(),expires_at:Y.string().datetime().optional(),automation_eligible:Y.boolean().optional(),statuses:Y.array(EP).optional(),types:Y.array(Hh).optional(),priorities:Y.array(Fh).optional(),limit:Y.number().int().positive().max(500).optional()}),_P=new Set(["create","update"]);function Gc(e,t,n,r){if(!_P.has(t.operation))return;dn(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.todo.${t.operation}`,success:r,agentId:n.agentId})}function Or(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Bh(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function Wh(e,t){return Uh(e)===Uh(t)}function $h(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!Wh(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 xP(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||!Wh(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function jh(e,t,n){let r=Bi.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=xP(o,i);switch(o.operation){case"create":{let d={type:Or(o.type,"type"),title:Or(o.title,"title"),description:o.description??void 0,instructions:Or(o.instructions,"instructions"),scope:a,workspaceRoot:i.workspaceRoot,cwd:a==="workspace"?(o.cwd??i.cwd)?.trim()||void 0:void 0,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee??void 0,modelSelection:Bh(o.model_selection)??i.modelSelection,mode:o.mode??void 0,systemPrompt:o.system_prompt??void 0,maxIterations:o.max_iterations??void 0,timeoutSeconds:o.timeout_seconds??void 0,availableAt:o.available_at,expiresAt:Or(o.expires_at,"expires_at"),automationEligible:o.automation_eligible,createdBy:s,originSessionId:n.sessionId,originTaskId:i.originTaskId},c={ok:!0,operation:o.operation,task:await e.manager.createTask(d)};return Gc(e,o,n,!0),c}case"update":{let d=Or(o.task_id,"task_id");if($h(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:Bh(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 Gc(e,o,n,!0),c}case"list":{let d={statuses:o.statuses,types:o.types,scope:a,workspaceRoot:i.workspaceRoot,priorities:o.priorities,automationEligible:o.automation_eligible,limit:o.limit};return{ok:!0,operation:o.operation,tasks:await e.manager.listTasks(d)}}case"get":{let d=await e.manager.getTask(Or(o.task_id,"task_id"));return $h(d,i),{ok:!0,operation:o.operation,task:d}}}}catch(i){return Gc(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:i instanceof Error?i.message:String(i)}}}}var $o="tasks",qh='# 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.',LP="# 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.",NP=Bi.extend({kind:xt.literal("todo")}).strict(),zh=Mr.extend({kind:xt.literal("scheduled")}).strict(),Kh=xt.discriminatedUnion("kind",[NP,zh]),DP=xt.discriminatedUnion("kind",[zh]),Gh=["create","update","list","get","pause","resume","delete","run_now"],UP=xt.object({...Mr.shape,...Bi.shape,kind:xt.enum(["todo","scheduled"]),operation:xt.enum(Gh)}).strict(),HP=xt.object({...Mr.shape,kind:xt.enum(["scheduled"]),operation:xt.enum(Gh)}).strict();function Vc(e){let t=e.todo;return MP({name:$o,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:OP(t?UP:HP),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?Kh:DP).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 jh(t,o.data,r)}}return{kind:"scheduled",...await Fc(e.scheduled,o.data,r)}}})}function Xc(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?LP:qh,whenToolAvailable:$o})}}}import{createSessionId as Y_,ensureLoopbackProxyBypass as by,isHubProtocolCompatible as Q_,resolveClineBuildEnv as Z_,resolveHubCommandTimeoutMs as ex}from"@cline/shared";import tx from"ws";var $i="0.0.89";var ln={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:$i,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var Wi="session_not_found";class Lr extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function ji(e){return e instanceof Lr||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as S_}from"node:child_process";import{closeSync as b_,mkdirSync as v_,openSync as T_,readFileSync as w_,unlinkSync as k_}from"node:fs";import{basename as C_,dirname as I_,join as A_}from"node:path";import{fileURLToPath as R_}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as E_,isBunEmbeddedModulePath as P_,isHubDaemonProcess as py,resolveClineBuildEnv as my,withResolvedClineBuildEnv as __}from"@cline/shared";import{createHash as FP,randomBytes as ey}from"node:crypto";import{existsSync as BP}from"node:fs";import{mkdir as Yc,open as Xh,readFile as ty,rename as $P,rm as qi,writeFile as WP}from"node:fs/promises";import{dirname as ny,join as Qc}from"node:path";import{ensureLoopbackProxyBypass as jP,isHubProtocolCompatible as qP}from"@cline/shared";import{resolveClineDataDir as Wo,resolveClineDir as SJ}from"@cline/shared/storage";var zP="CLINE_HUB_DISCOVERY_PATH",KP="CLINE_HUB_BUILD_ID",GP="CLINE_HUB_BUILD_EPOCH_MS",VP=30000,XP=15000,Jh=100;function JP(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function YP(e){return FP("sha256").update(e).digest("hex").slice(0,12)}function QP(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 ry(){return ey(32).toString("hex")}function Yh(e){return new Promise((t)=>setTimeout(t,e))}function ZP(e){return`${e}.lock`}async function e_(e){try{let t=JSON.parse(await ty(Qc(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 Jc(e){await qi(e,{recursive:!0,force:!0}).catch(()=>{return})}function Mt(){let e=process.env[KP]?.trim();if(e)return e;return"sdk-v1-320526e16fc49dc154a7a13f617d0519faa9a32e6ef1a78b3e596c061889b15d".trim()||`source-${String(ln.version)}`}function Zc(){let e=Number(process.env[GP]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790811192802)?1790811192802:void 0}function Un(e,t=Mt()){let n=qP(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 Qh(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function Zh(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 t_(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 jo(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=Qh(e.buildEpochMs),s=Qh(t.buildEpochMs);if(o!==void 0&&s!==void 0&&o!==s)return o<s?-1:1;let i=Zh(e.coreVersion),a=Zh(t.coreVersion);if(i&&a){let d=t_(i,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function qo(){return{buildId:Mt(),buildEpochMs:Zc(),coreVersion:String(ln.version)}}function Nr(e,t){let n=t?.self??qo(),r=Un(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return jo(n,e)<=0}function Hn(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${YP(e)}`,n=process.env[zP]?.trim()||Qc(Wo(),"locks","hub","owners",`${JP(t)}.json`);return{ownerId:t,discoveryPath:n}}function vJ(e=`hub-${Date.now().toString(36)}`){return Hn(e)}async function Re(e){try{let t=JSON.parse(await ty(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function zi(e,t){await eu(e,async()=>{let n=ny(e);await Yc(n,{recursive:!0});let r=`${e}.${process.pid}.${ey(6).toString("hex")}.tmp`,o;try{o=await Xh(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
|
|
311
311
|
`,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await $P(r,e);let s;try{s=await Xh(n,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await o?.close().catch(()=>{return}),await qi(r,{force:!0}).catch(()=>{return}),s}})}async function Gt(e){await eu(e,async()=>{await qi(e,{force:!0}).catch(()=>{return})})}async function oy(e,t){return await eu(e,async()=>{if((await Re(e))?.hubId!==t)return!1;return await qi(e,{force:!0}),!0})}async function sy(e,t,n){let r=ZP(e);await Yc(ny(r),{recursive:!0});let o=Date.now()+XP;while(!0){try{await Yc(r,{recursive:!1})}catch(s){if((s instanceof Error&&"code"in s?String(s.code):"")!=="EEXIST")throw s;let a=await e_(r);if(!a){if(Date.now()>=o){await Jc(r);continue}await Yh(Jh);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!QP(a.pid)||d>VP){await Jc(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await Yh(Jh);continue}try{return await WP(Qc(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
312
312
|
`,"utf8"),await n()}finally{await Jc(r)}}}function eu(e,t){return sy(`${e}.mutation`,"discovery mutation",t)}function Ki(e,t){return sy(e,"startup",t)}async function Vt(e,t){jP();try{let n=await fetch(t?.authToken?n_(e):iy(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let r=await n.json();if(typeof r.protocolVersion!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string")return;return{protocolVersion:r.protocolVersion,minClientProtocolVersion:typeof r.minClientProtocolVersion==="string"?r.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof r.maxClientProtocolVersion==="string"?r.maxClientProtocolVersion:void 0,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof r.coreVersion==="string"?r.coreVersion:void 0,buildId:typeof r.buildId==="string"?r.buildId:void 0,buildEpochMs:typeof r.buildEpochMs==="number"?r.buildEpochMs:void 0,host:r.host,port:r.port,url:r.url,hubId:typeof r.hubId==="string"?r.hubId:void 0,authToken:typeof r.authToken==="string"?r.authToken:void 0,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:typeof r.startedAt==="string"?r.startedAt:void 0,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:void 0}}catch{return}}function Xt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function iy(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function n_(e){let t=new URL(iy(e));return t.pathname="/status",t.toString()}function TJ(e){return BP(e)}import{CLINE_HUB_DEV_PORT as r_,CLINE_HUB_PORT as o_,resolveClineBuildEnv as s_}from"@cline/shared";var i_="CLINE_HUB_HOST",a_="CLINE_HUB_PORT",d_="CLINE_HUB_PATHNAME",c_="127.0.0.1",u_=o_,l_="/hub";function ay(e){return s_(e)==="development"?r_:u_}function p_(e={}){return(e.env??process.env)[i_]?.trim()||c_}function Gi(e={}){let n=(e.env??process.env)[a_]?.trim();if(!n)return ay(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return ay(e);return r}function m_(e={}){return(e.env??process.env)[d_]?.trim()||l_}function Fn(e={},t={}){return{host:e.host??p_(t),port:e.port??Gi(t),pathname:e.pathname??m_(t)}}import{join as g_}from"node:path";var f_="shared:cline",h_="CLINE_HUB_DISCOVERY_PATH",y_="hub-production";function EJ(e){let t=xn(e.trim());return Hn(`workspace:${t||e.trim()}`)}function vt(e=f_){return Hn(`${e}@${Mt()}`)}function Ot(){return{ownerId:y_,discoveryPath:process.env[h_]?.trim()||g_(Wo(),"locks","hub","production.json")}}var dy=15000,x_=200,cy=3000,M_=100,O_=[100,250,500,1000,2000],L_="--cline-hub-daemon",N_=3,D_=60000,ru=new Map,FJ={resetRetireAttempts(){ru.clear()},resolveDaemonEntryArgs:fy};function U_(e,t=Date.now()){let n=ru.get(e);if(!n||t-n.windowStartedAt>D_)return ru.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=N_}function H_(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function F_(){try{let e=A_(Wo(),"logs","hub-daemon.log");return v_(I_(e),{recursive:!0}),{fd:T_(e,"a"),logPath:e}}catch{return}}function gy(){return my()==="production"?Ot():vt()}function zo(e){return Nr(e)}function B_(e){try{let t=JSON.parse(w_(`${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 tu(e){try{k_(`${e}.superseded`)}catch{}}function uy(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Dr(e,t){try{return await Vt(e,{authToken:t})}catch{return}}async function ly(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Dr(e))?.url)return!0;await new Promise((o)=>setTimeout(o,M_))}return!1}async function Ur(e,t){if(!U_(e.url))return!1;await Bn(e.url,e.authToken,"retired by newer install").catch(()=>!1),await su(e.url,e.authToken).catch(()=>!1);let n=await ly(e.url,cy);if(!n&&e.pid&&$_(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await ly(e.url,cy)}if(n)await Gt(t).catch(()=>{return});return n}function $_(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function ou(e){try{return(await Fr(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function nu(e,t){if(zo(e))return"reusable";let n=await Bn(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await ou(e)){if(n)await Bn(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Ur(e,t);if(!r&&n)await Bn(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function W_(e){if(my()!=="production")return;let t=vt();if(t.discoveryPath===e.discoveryPath)return;let n=await Re(t.discoveryPath);if(n?.url)await Ur(n,t.discoveryPath);else await Gt(t.discoveryPath).catch(()=>{return})}function j_(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return R_(new URL(`./entry.${e}`,import.meta.url))}function fy(e,t){if(P_(e))return[L_];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function q_(e,t){let n=j_(),r=process.execPath?.trim();if(!r)throw Error("unable to resolve runtime executable for hub daemon");let o=C_(r).toLowerCase().includes("bun"),s=fy(n,o);return{launcher:r,args:[...s,"--cwd",e,...H_(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...__(process.env),CLINE_NO_INTERACTIVE:"1",[E_]:"1"}}}function z_(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 K_(e,t={}){if(py())return;let n=q_(e,t),r=F_();try{S_(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)b_(r.fd)}}async function G_(e,t={}){for(let n=0;;n++)try{K_(e,t);return}catch(r){let o=O_[n];if(!z_(r)||o===void 0)throw r;await new Promise((s)=>setTimeout(s,o))}}function BJ(e,t={}){if(py())return;Ko(e,t).catch(()=>{})}async function V_(e,t,n={}){let r=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Fn(n),s=Xt(o.host,o.port,o.pathname),i=(g)=>{if(!r)Hr(g.url,g.authToken);return g};await W_(e).catch(()=>{return});let a=await Re(e.discoveryPath),d=a?.url?void 0:B_(e.discoveryPath),c=!1;if(a?.url){let g=a.authToken;if(!g)c=!0,await Ur(a,e.discoveryPath);else{let f=await Dr(a.url,g);if(f?.url&&zo(f)&&await dt(f.url,{authToken:g}))return tu(e.discoveryPath),i({url:f.url,authToken:g});if(f?.url){if(await nu({...f,authToken:g},e.discoveryPath)==="deferred_busy"&&await dt(f.url,{authToken:g}))return i({url:f.url,authToken:g})}else await Gt(e.discoveryPath).catch(()=>{return})}}let u=await Dr(s);if(u?.url){let g=uy(u,a??d,s);if(zo(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 zi(e.discoveryPath,b)}catch{}return tu(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 nu(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 G_(t,{...p,manageConnectors:n.manageConnectors});let m=Date.now()+dy;while(Date.now()<m){let g=await Re(e.discoveryPath);if(g?.url&&g.authToken){let h=await Dr(g.url,g.authToken);if(h?.url&&zo(h)&&await dt(h.url,{authToken:g.authToken}))return tu(e.discoveryPath),i({url:h.url,authToken:g.authToken})}let f=await Dr(s);if(f?.url&&!zo(f)){let h=uy(f,g??d,s),S=await nu(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,x_))}throw Error(`Timed out after ${dy}ms waiting for detached hub startup.`)}async function Ko(e,t={}){let n=gy();return await Ki(n.discoveryPath,async()=>V_(n,e,t))}var X_=5000,J_=500;async function $J(e={}){let t=gy(),n=e.workspaceRoot??process.cwd(),r=await Re(t.discoveryPath),o=r?.url?await Dr(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await Ko(n)};let s={...o,authToken:o.authToken??r?.authToken,pid:o.pid??r?.pid};if(Un(o).compatible)return{outcome:"already_current",url:o.url,authToken:s.authToken};if(jo(qo(),o)<=0)return{outcome:"hub_not_older",url:o.url,authToken:s.authToken};if(!await Bn(s.url,s.authToken,e.reason??"hub upgrade requested").catch(()=>!1))throw Error(`The running Cline Hub at ${s.url} did not accept a drain request, so it was not replaced. It is replaced automatically once idle when a Cline client next starts, or run 'cline doctor fix' to stop it now.`);let a=async()=>{await Bn(s.url,s.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},d=Date.now()+(e.waitForIdleMs??X_),c;for(;;){try{if(c=(await Fr(s.url,s.authToken)).activeSessionCount,c===0)break}catch{}if(Date.now()>=d)break;await new Promise((p)=>setTimeout(p,J_))}if(c!==0&&e.force!==!0)return await a(),{outcome:"still_busy",url:s.url,authToken:s.authToken,...c!==void 0?{activeSessionCount:c}:{}};if(!await Ur(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 Ko(n),activeSessionCount:c??0}}function lu(){return Z_()==="production"?Ot():vt()}function nx(){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 vy(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 vy(e.data);return String(e)}function rx(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 hy(e){let t=e,n=rx(t.reason);return new Oe("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:au,{closeCode:t.code,closeReason:n||void 0})}function yy(e,t){if(e instanceof Oe)return e;if(e instanceof Error)return new Oe("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new Oe("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new Oe("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new Oe("hub_connect_failed",r?`Failed to connect to hub at ${t.toString()} (${r} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var iu="*",Vi=8000,ox="cline-hub-auth.",Ty=new Map,wy=new Set,sx=3000,ix=3000,ax=100,au="Hub connection closed",dx=250,cx=5000,Sy=0.5;class Oe extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function ux(e){return e instanceof Oe}class Xi extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function JJ(e,t){return e instanceof Xi&&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=mu(e.toString());return r?Ty.get(r):void 0}function lx(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 mu(e){if(!lx(e))return;let t=new URL(Ji(e));return t.search="",t.hash="",t.toString()}function du(e){let t=mu(e);return!!t&&wy.has(t)}function Hr(e,t){let n=mu(e);if(n){if(wy.add(n),t?.trim())Ty.set(n,t)}return e}class $n{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new Oe("hub_connection_closed",au);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(ln.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{i.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let a of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(a));this.reconnectAttempt=0});let s=this.connectPromise;try{await s}catch(i){if(this.connectPromise===s)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=yy(i,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw i}}async openSocket(e,t,n){let r=this.options.resolveConnectionHeaders,o;if(r){let d;try{o=await Promise.race([Promise.resolve().then(()=>r()),new Promise((c,u)=>{d=setTimeout(()=>{u(new Oe("hub_connect_timeout",`Timed out resolving hub connection headers after ${Vi}ms`))},Vi)})])}catch(c){let u=c instanceof Oe?c:new Oe("hub_connect_failed",c instanceof Error?c.message:String(c));if(n===this.connectGeneration)this.lastCloseError=u;throw u}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new Oe("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let s=o?new tx(e.toString(),{headers:{...o}}):new(nx())(e.toString(),t?[`${ox}${t}`]:void 0);this.socket=s;let i=!1,a=new Promise((d,c)=>{let u=!1,l=setTimeout(()=>{if(u)return;u=!0,i=!0;let p=new Oe("hub_connect_timeout",`Timed out connecting to hub after ${Vi}ms`);if(this.socket===s)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{s.close()}catch{}c(p)},Vi);s.addEventListener("open",()=>{if(u)return;u=!0,clearTimeout(l),d()}),s.addEventListener("error",(p)=>{if(u)return;u=!0,clearTimeout(l);let m=yy(p,e);if(this.socket===s)this.lastCloseError=m,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;c(m)}),s.addEventListener("close",(p)=>{if(u)return;u=!0,clearTimeout(l);let m=i?this.lastCloseError:hy(p);if(this.socket===s){if(!i)this.lastCloseError=m,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}c(m)})});return s.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(vy(d)))}),s.addEventListener("close",(d)=>{if(this.socket!==s)return;if(!i)this.lastCloseError=hy(d),this.sawSocketClose=!0;this.registered=!1;for(let c of this.pendingReplies.values())c.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await a,s}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,r={listener:e,sessionId:n};return this.listeners.add(r),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(r))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,r){let o=0,s=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,r)}catch(i){if(!s||o>=1||!await this.recoverLocalHubTransport(i))throw i;o+=1}}async commandOnce(e,t,n,r,o=!0){if(o)await this.connect();r?.beforeDispatch?.();let s=Y_("hubreq_");r?.onDispatch?.(s);let i=ex(e,r?.timeoutMs),a=new Promise((c,u)=>{let l=i===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(s))return;u(new Xi(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===Wi){let c=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Lr(c,d.error.message)}throw new Xi(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!du(this.currentUrl)||!ux(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await uu({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(dx*2**this.reconnectAttempt,cx),t=Math.round(e*(1-Sy)+Math.random()*e*Sy);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(!du(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await uu({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new Oe("hub_connection_closed",au);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new Oe("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),r=(this.subscriptionCounts.get(n)??0)+t;if(r<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,r),t>0&&r===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??iu}subscriptionSessionIdFromKey(e){return e===iu?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[iu,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 Ji(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function dt(e,t){let n=new $n({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function cu(e,t){let n=Ji(e),r=await Vt(n,{authToken:t?.authToken});if(!r)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=Mt(),s=Un(r,o);if(!s.compatible&&!Nr(r))return{status:s.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!Q_(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 px(e){let t=Date.now()+ix;while(Date.now()<t){if(!(await Vt(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,ax))}return!1}function mx(e,t){try{return Ji(e)===Ji(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 YJ(e){return ky(e).activeSessionCount>0}async function Fr(e,t,n){let r=new $n({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await r.command("session.list",{limit:500},void 0,{timeoutMs:sx});return ky(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function Cy(e,t,n){try{return(await Fr(e,t,n)).activeSessionCount===0}catch{return!1}}async function gx(e,t){let n=`${e.discoveryPath}.superseded`,r=await Re(n);if(!r?.url||!r.authToken)return;let o=await cu(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await Cy(o.url,r.authToken,t))return;return Hr(o.url,r.authToken)}async function fx(e={}){if(e.endpoint?.trim()){let o=await cu(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=lu(),n=await Re(t.discoveryPath);if(!n?.url)return await gx(t,e);let r=await cu(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return Hr(r.url,n.authToken);if(r.status==="protocol_mismatch")await Gt(t.discoveryPath).catch(()=>{return});return}async function uu(e={}){let t=await fx(e);if(t&&await dt(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Ko(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function Bn(e,t,n,r){by();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 su(e,t){by();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 hx(e=lu()){let t=await Re(e.discoveryPath);if(!t?.url)return!1;try{if(await su(t.url,t.authToken))return!0}catch{}return!1}async function QJ(e){if(!du(e.url))return;let t=lu(),n=await Re(t.discoveryPath);if(!n?.url||!mx(n.url,e.url))return;if(!await Cy(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await hx())return;if(!await px(n.url))return;return await Gt(t.discoveryPath).catch(()=>{return}),await uu({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveClineBuildEnv as yx}from"@cline/shared";function Sx(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 bx="cline-hub-auth.";function vx(e){return e.host!==void 0||e.port!==void 0||e.pathname!==void 0}function Tx(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 Iy(){return yx()==="production"?Ot():vt()}async function wx(e){let t=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),t)return t;let n=Iy(),r=await Re(n.discoveryPath);if(r?.url&&Tx(e.toString(),r.url))return r.authToken;return}async function kx(e={}){let t=Fn(e);if(!vx(e)){let n=Iy(),r=await Re(n.discoveryPath);if(r?.url)return r.url}return Xt(t.host,t.port,t.pathname)}async function Ay(e){return await new Promise((t,n)=>{(async()=>{let r=new URL(e),o=await wx(r);r.hash="";let s=new WebSocket(r.toString(),o?[`${bx}${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(Sx(d,e))})})().catch(n)})}async function oY(e){try{return(await Ay(e)).close(),!0}catch{return!1}}async function sY(e,t){let n=await kx(e),r=await Ay(n);try{return await r.send({version:t.version??"v1",clientId:t.clientId??"hub-client",...t})}finally{r.close()}}import{existsSync as Cx}from"node:fs";import{isHubDaemonProcess as Ix,resolveClineBuildEnv as Ax}from"@cline/shared";var Rx=1e4,Ex="CLINE_HUB_BUILD_WATCH_INTERVAL_MS";function Px(){let e=Number(process.env[Ex]);return Number.isFinite(e)&&e>0?e:Rx}async function _x(e,t){try{let n=await Fr(e.url,t);return{...e,activeSessionCount:n.activeSessionCount,participantClientCount:n.participantClientCount}}catch{return e}}function xx(){return Ax()==="production"?Ot():vt()}function Mx(e){try{return Cx(`${e}.lock`)}catch{return!1}}async function Ox(){let e=xx();if(Mx(e.discoveryPath))return;let t=await Re(e.discoveryPath).catch(()=>{return});if(!t?.url)return;let n=await Vt(t.url).catch(()=>{return});if(!n?.url)return;let r=Mt(),o=Un(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=qo();if(i.coreVersion&&n.coreVersion&&i.coreVersion===n.coreVersion)return;if(jo(i,n)>0)return await _x(s("outdated_hub"),t.authToken);return s("build_mismatch")}function pY(e){if(Ix()||process.env.CLINE_HUB_PORT?.trim())return()=>{};let t=e.intervalMs??Px(),n,r,o=!1,s=setInterval(()=>{if(o)return;o=!0,Ox().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 gu(e){return e?JSON.parse(JSON.stringify(e)):{}}function Yi(e){let t=e?.session&&typeof e.session==="object"?e.session:void 0;if(!t)return;let n=t.metadata&&typeof t.metadata==="object"?gu(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 Ry(e,t){return e.error?.message??`hub command failed: ${t}`}function Lx(e){let t=gu(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 Ey(e){let t=e?.sessionId;return typeof t==="string"&&t.trim()?t.trim():void 0}function Nx(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 Dx(e){let t=gu(e.payload);if(e.event==="schedule.execution_completed")return{sessionId:e.sessionId?.trim()||Ey(t)||"",eventType:"schedule.execution.completed",payload:t};if(e.event==="schedule.execution_failed")return{sessionId:e.sessionId?.trim()||Ey(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:Lx(e.payload)};case"run.completed":return{sessionId:n,eventType:"runtime.chat.completed",payload:t};default:return}}class Ux{client;constructor(e){this.client=new $n({url:e.address,authToken:e.authToken,clientId:e.clientId,clientType:e.clientType??"hub-session-client",displayName:e.displayName??"hub session client",workspaceRoot:e.workspaceRoot,cwd:e.cwd,metadata:e.metadata})}async connect(){await this.client.connect()}async taskCommand(e,t){return await this.client.connect(),(await this.client.command(e,t)).payload??{}}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(e){await this.client.connect();let t=await this.client.command("session.create",{workspaceRoot:e.workspaceRoot,cwd:e.cwd,sessionConfig:{providerId:e.provider,modelId:e.model,apiKey:e.apiKey,cwd:e.cwd??e.workspaceRoot,workspaceRoot:e.workspaceRoot,systemPrompt:e.systemPrompt??"",mode:e.mode??"act",rules:e.rules,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,enableTools:e.enableTools,enableSpawnAgent:e.enableSpawn!==!1,enableAgentTeams:e.enableTeams!==!1,disableMcpSettingsTools:e.disableMcpSettingsTools,agentPluginPaths:e.agentPluginPaths,missionLogIntervalSteps:e.missionStepInterval,missionLogIntervalMs:e.missionTimeIntervalMs},metadata:{source:e.source??"cli",provider:e.provider,model:e.model,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,prompt:void 0,interactive:e.interactive!==!1},runtimeOptions:{mode:e.mode,systemPrompt:e.systemPrompt,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,autoApproveTools:e.autoApproveTools,toolExecutors:e.toolExecutors,configExtensions:e.configExtensions},modelSelection:{provider:e.provider,model:e.model,apiKey:e.apiKey},toolPolicies:e.toolPolicies}),n=Yi(t.payload);if(!n?.sessionId)throw Error("hub session create returned no session id");return{sessionId:n.sessionId,startResult:{sessionId:n.sessionId,manifestPath:"",messagesPath:n.messagesPath??""}}}async sendRuntimeSession(e,t,n){return await this.client.connect(),{result:(await this.client.command("session.send_input",{prompt:t.prompt,mode:t.config.mode,attachments:t.attachments,delivery:t.delivery,timeoutSeconds:t.config.timeoutSeconds},e,n)).payload?.result}}async stopRuntimeSession(e){return await this.client.connect(),await this.client.command("session.detach",{sessionId:e},e),{applied:!0}}async abortRuntimeSession(e){return await this.client.connect(),await this.client.command("run.abort",{sessionId:e},e),{applied:!0}}async updateSession(e){return await this.client.connect(),await this.client.command("session.update",{sessionId:e.sessionId,metadata:e.metadata},e.sessionId),{updated:!0}}async getSession(e){await this.client.connect();let t;try{t=await this.client.command("session.get",void 0,e)}catch(n){if(ji(n))return;throw n}return Yi(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(Ry(n,"session.messages"));let r=n.payload?.messages;return Array.isArray(r)?r:[]}async restore(e){let t=e.sessionId.trim();if(!t)throw Error("sessionId is required");let n=e.restore?.messages!==!1;if(n&&!e.config)throw Error("config is required when restore.messages is true");await this.client.connect();let r=e.config,o=await this.client.command("session.restore",{sessionId:t,checkpointRunCount:e.checkpointRunCount,restore:e.restore,...r?{workspaceRoot:r.workspaceRoot,cwd:r.cwd,sessionConfig:{providerId:r.provider,modelId:r.model,apiKey:r.apiKey,cwd:r.cwd??r.workspaceRoot,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:r.mode??"act",rules:r.rules,maxIterations:r.maxIterations,enableTools:r.enableTools,enableSpawnAgent:r.enableSpawn!==!1,enableAgentTeams:r.enableTeams!==!1,disableMcpSettingsTools:r.disableMcpSettingsTools,agentPluginPaths:r.agentPluginPaths,missionLogIntervalSteps:r.missionStepInterval,missionLogIntervalMs:r.missionTimeIntervalMs},metadata:{source:r.source??"cli",provider:r.provider,model:r.model,enableTools:r.enableTools,enableSpawn:r.enableSpawn,enableTeams:r.enableTeams,prompt:void 0,interactive:r.interactive!==!1},runtimeOptions:{mode:r.mode,systemPrompt:r.systemPrompt,maxIterations:r.maxIterations,enableTools:r.enableTools,enableSpawn:r.enableSpawn,enableTeams:r.enableTeams,autoApproveTools:r.autoApproveTools,configExtensions:r.configExtensions},modelSelection:{provider:r.provider,model:r.model,apiKey:r.apiKey},toolPolicies:r.toolPolicies}:{}},t);if(!o.ok)throw Error(Ry(o,"session.restore"));let s=Yi(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=Nx(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)=>Yi({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=Dx(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 Hx{client;constructor(e){this.client=new $n({url:e.address,authToken:e.authToken,clientId:e.clientId,clientType:e.clientType??"hub-ui-client",displayName:e.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(e){await this.client.command("ui.notify",e)}async sendShowWindow(e){await this.client.command("ui.show_window",e??{})}async listClients(){let e=await this.client.command("client.list");return Array.isArray(e.payload?.clients)?e.payload.clients:[]}async listSessions(e=200){let t=await this.client.command("session.list",{limit:e});return Array.isArray(t.payload?.sessions)?t.payload.sessions:[]}async searchSessions(e){let t=await this.client.command("session.search",e);return Array.isArray(t.payload?.hits)?t.payload.hits:[]}async toggleSetting(e){let t=await this.client.command("settings.toggle",e);if(!t.ok)throw Error(t.error?.message??"settings.toggle failed");return t.payload}subscribeUI(e){return this.client.subscribe((t)=>{switch(t.event){case"ui.notify":e.onNotify?.(t.payload);break;case"ui.show_window":e.onShowWindow?.(t.payload);break;case"hub.client.registered":e.onClientRegistered?.(t.payload??{});break;case"hub.client.disconnected":e.onClientDisconnected?.(t.payload??{});break;case"session.created":e.onSessionCreated?.(t.payload??{});break;case"session.updated":e.onSessionUpdated?.(t.payload??{});break;case"session.detached":e.onSessionDetached?.(t.payload??{});break}})}}import{normalizeProviderId as uz}from"@cline/llms";import{readdirSync as P1}from"node:fs";import{homedir as _1}from"node:os";import{isAbsolute as x1,join as Bm,resolve as $m}from"node:path";import{captureSdkError as ft,createSessionId as M1,isLikelyAuthError as O1,normalizeUserInput as L1}from"@cline/shared";import{setHomeDirIfUnset as N1}from"@cline/shared/storage";import{decodeJwtPayload as OM,getClineEnvironmentConfig as Jy}from"@cline/shared";import{decodeJwtPayload as zx,getClineEnvironmentConfig as Kx}from"@cline/shared";import{createHash as Fx}from"node:crypto";var Bx;function Ye(e){if(typeof e!=="string"||e.length===0)return"unset";return Fx("sha256").update(e).digest("hex").slice(0,8)}function ce(e){try{Bx?.debug(e)}catch{}}function $x(){let e;return{promise:new Promise((n)=>{e=n}),resolve:e}}async function Wn(e){let t=await import("node:http"),n=e.host??"127.0.0.1",r=e.timeoutMs??300000,o=e.successHtml??Wx,s=$x(),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 Wx=`<!DOCTYPE html>
|
|
313
313
|
<html lang="en">
|