@cerebriline/core 4.100.243 → 4.100.244
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/daemon/entry.js +1 -1
- package/dist/hub/index.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +4 -4
package/dist/hub/daemon/entry.js
CHANGED
|
@@ -1455,7 +1455,7 @@ ${j}`:j,$.mode??h.config.mode),V=this.resolveAbsoluteFilePaths(h.config.cwd,$.us
|
|
|
1455
1455
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
1456
1456
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
1457
1457
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
1458
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[h.sessionId,h.source,h.pid,h.startedAt,null,null,"running",0,h.interactive?1:0,h.provider,h.model,h.cwd,h.workspaceRoot,h.teamName??null,h.enableTools?1:0,h.enableSpawn?1:0,h.enableTeams?1:0,null,null,null,null,0,h.prompt??null,h.metadata?JSON.stringify(h.metadata):null,"","",h.messagesPath,rh()])}}function wJh(h){return{text:h.text,usage:h.usage,inputTokens:h.usage.inputTokens,outputTokens:h.usage.outputTokens,iterations:h.iterations,finishReason:h.finishReason,toolCalls:h.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function FJh(h){return h.mode==="plan"?"plan":h.mode==="yolo"?"yolo":"act"}function kC(h={}){let $=async(Q)=>Q,Z=new C8({sessionService:new I8(new S8),capabilities:{toolExecutors:{submit:$}},fetch:h.fetch,telemetry:h.telemetry});return{async startSession(Q,J){let Y=(Q.cwd?.trim()||Q.workspaceRoot).trim(),X=await Z.startSession({source:d2.CORE,mode:"automation",sessionMetadata:c1(J?.sessionMetadata,{mode:"automation",trigger:Q.source}),interactive:!1,config:{providerId:_Jh(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Y,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:FJh(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,agentPluginPaths:Q.agentPluginPaths,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:X.sessionId,startResult:{sessionId:X.sessionId,manifestPath:X.manifestPath,messagesPath:X.messagesPath}}},async sendSession(Q,J){let Y=await Z.runTurn({sessionId:Q,prompt:J.prompt,userImages:J.attachments?.userImages,userFiles:J.attachments?.userFiles?.map((X)=>X.content)});if(!Y)throw Error("local hub schedule runtime returned no turn result");return{result:wJh(Y)}},async abortSession(Q){return await Z.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await Z.stopSession(Q),{applied:!0}}}}import{CLINE_HUB_DEV_PORT as GJh,CLINE_HUB_PORT as HJh,resolveClineBuildEnv as BJh}from"@cerebriline/shared";var DJh="CLINE_HUB_HOST",qJh="CLINE_HUB_PORT",zJh="CLINE_HUB_PATHNAME",LJh="127.0.0.1",AJh=HJh,fJh="/hub";function SC(h){return BJh(h)==="development"?GJh:AJh}function OJh(h={}){return(h.env??process.env)[DJh]?.trim()||LJh}function ow(h={}){let Z=(h.env??process.env)[qJh]?.trim();if(!Z)return SC(h);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return SC(h);return Q}function NJh(h={}){return(h.env??process.env)[zJh]?.trim()||fJh}function gY(h={},$={}){return{host:h.host??OJh($),port:h.port??ow($),pathname:h.pathname??NJh($)}}import{chmodSync as MJh,existsSync as TJh,mkdirSync as yJh}from"node:fs";import{dirname as RJh}from"node:path";import{loadSqliteDb as EJh}from"@cerebriline/shared/db";var IC=3;class xC extends Error{lockFile;constructor(h){super(`Hub instance lock is held by a live Hub: ${h}. Connect to the running Hub or diagnose it; never replace it.`);this.name="HubLockHeldError",this.lockFile=h}}function cY(h){return h instanceof Error&&h.name==="HubLockHeldError"}function vC(h){return`${h}.instance.lock`}class Y9{db;lockFile;constructor(h,$){this.lockFile=h,this.db=$}get held(){return this.db!==void 0}release(){let h=this.db;if(!h)return;this.db=void 0;try{h.exec("ROLLBACK;")}catch{}h.close?.()}static acquire(h){let $=!1,Z;try{yJh(RJh(h),{recursive:!0}),$=TJh(h),Z=EJh(h)}catch{return new Y9(h,void 0)}try{Z.exec("PRAGMA busy_timeout = 0;"),Z.exec("BEGIN EXCLUSIVE;")}catch(Q){if(Z.close?.(),bJh(Q))throw new xC(h);return new Y9(h,void 0)}if(!$)try{MJh(h,384)}catch{}return new Y9(h,Z)}}function bJh(h){let $=h instanceof Error?h.message:String(h),Z=h?.code;return Z==="SQLITE_BUSY"||Z==="SQLITE_LOCKED"||$.includes("SQLITE_BUSY")||$.includes("SQLITE_LOCKED")||$.includes("database is locked")}import{join as rJh}from"node:path";import{createHash as CJh,randomBytes as dC}from"node:crypto";import{mkdir as ew,open as mC,readFile as pC,rename as PJh,rm as uY,writeFile as kJh}from"node:fs/promises";import{dirname as aC,join as hF}from"node:path";import{isHubProtocolCompatible as SJh}from"@cerebriline/shared";import{resolveClineDataDir as x8,resolveClineDir as Wgh}from"@cerebriline/shared/storage";var IJh="CLINE_HUB_DISCOVERY_PATH",xJh="CLINE_HUB_BUILD_ID",vJh="CLINE_HUB_BUILD_EPOCH_MS",mJh=30000,gJh=15000,gC=100;function cJh(h){return h.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function uJh(h){return CJh("sha256").update(h).digest("hex").slice(0,12)}function lJh(h){if(!Number.isInteger(h)||!h||h<=0)return!1;try{return process.kill(h,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function iC(){return dC(32).toString("hex")}function cC(h){return new Promise(($)=>setTimeout($,h))}function dJh(h){return`${h}.lock`}async function pJh(h){try{let $=JSON.parse(await pC(hF(h,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function tw(h){await uY(h,{recursive:!0,force:!0}).catch(()=>{return})}function S4(){let h=process.env[xJh]?.trim();if(h)return h;return"sdk-v1-1a4964394d75a679fd59b69082126225563ccb3cf9ea367c70703c8a61f1f6ea".trim()||`source-${String(b3.version)}`}function $F(){let h=Number(process.env[vJh]);if(Number.isFinite(h)&&h>0)return h;return Number.isFinite(
|
|
1458
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[h.sessionId,h.source,h.pid,h.startedAt,null,null,"running",0,h.interactive?1:0,h.provider,h.model,h.cwd,h.workspaceRoot,h.teamName??null,h.enableTools?1:0,h.enableSpawn?1:0,h.enableTeams?1:0,null,null,null,null,0,h.prompt??null,h.metadata?JSON.stringify(h.metadata):null,"","",h.messagesPath,rh()])}}function wJh(h){return{text:h.text,usage:h.usage,inputTokens:h.usage.inputTokens,outputTokens:h.usage.outputTokens,iterations:h.iterations,finishReason:h.finishReason,toolCalls:h.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function FJh(h){return h.mode==="plan"?"plan":h.mode==="yolo"?"yolo":"act"}function kC(h={}){let $=async(Q)=>Q,Z=new C8({sessionService:new I8(new S8),capabilities:{toolExecutors:{submit:$}},fetch:h.fetch,telemetry:h.telemetry});return{async startSession(Q,J){let Y=(Q.cwd?.trim()||Q.workspaceRoot).trim(),X=await Z.startSession({source:d2.CORE,mode:"automation",sessionMetadata:c1(J?.sessionMetadata,{mode:"automation",trigger:Q.source}),interactive:!1,config:{providerId:_Jh(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Y,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:FJh(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,agentPluginPaths:Q.agentPluginPaths,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:X.sessionId,startResult:{sessionId:X.sessionId,manifestPath:X.manifestPath,messagesPath:X.messagesPath}}},async sendSession(Q,J){let Y=await Z.runTurn({sessionId:Q,prompt:J.prompt,userImages:J.attachments?.userImages,userFiles:J.attachments?.userFiles?.map((X)=>X.content)});if(!Y)throw Error("local hub schedule runtime returned no turn result");return{result:wJh(Y)}},async abortSession(Q){return await Z.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await Z.stopSession(Q),{applied:!0}}}}import{CLINE_HUB_DEV_PORT as GJh,CLINE_HUB_PORT as HJh,resolveClineBuildEnv as BJh}from"@cerebriline/shared";var DJh="CLINE_HUB_HOST",qJh="CLINE_HUB_PORT",zJh="CLINE_HUB_PATHNAME",LJh="127.0.0.1",AJh=HJh,fJh="/hub";function SC(h){return BJh(h)==="development"?GJh:AJh}function OJh(h={}){return(h.env??process.env)[DJh]?.trim()||LJh}function ow(h={}){let Z=(h.env??process.env)[qJh]?.trim();if(!Z)return SC(h);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return SC(h);return Q}function NJh(h={}){return(h.env??process.env)[zJh]?.trim()||fJh}function gY(h={},$={}){return{host:h.host??OJh($),port:h.port??ow($),pathname:h.pathname??NJh($)}}import{chmodSync as MJh,existsSync as TJh,mkdirSync as yJh}from"node:fs";import{dirname as RJh}from"node:path";import{loadSqliteDb as EJh}from"@cerebriline/shared/db";var IC=3;class xC extends Error{lockFile;constructor(h){super(`Hub instance lock is held by a live Hub: ${h}. Connect to the running Hub or diagnose it; never replace it.`);this.name="HubLockHeldError",this.lockFile=h}}function cY(h){return h instanceof Error&&h.name==="HubLockHeldError"}function vC(h){return`${h}.instance.lock`}class Y9{db;lockFile;constructor(h,$){this.lockFile=h,this.db=$}get held(){return this.db!==void 0}release(){let h=this.db;if(!h)return;this.db=void 0;try{h.exec("ROLLBACK;")}catch{}h.close?.()}static acquire(h){let $=!1,Z;try{yJh(RJh(h),{recursive:!0}),$=TJh(h),Z=EJh(h)}catch{return new Y9(h,void 0)}try{Z.exec("PRAGMA busy_timeout = 0;"),Z.exec("BEGIN EXCLUSIVE;")}catch(Q){if(Z.close?.(),bJh(Q))throw new xC(h);return new Y9(h,void 0)}if(!$)try{MJh(h,384)}catch{}return new Y9(h,Z)}}function bJh(h){let $=h instanceof Error?h.message:String(h),Z=h?.code;return Z==="SQLITE_BUSY"||Z==="SQLITE_LOCKED"||$.includes("SQLITE_BUSY")||$.includes("SQLITE_LOCKED")||$.includes("database is locked")}import{join as rJh}from"node:path";import{createHash as CJh,randomBytes as dC}from"node:crypto";import{mkdir as ew,open as mC,readFile as pC,rename as PJh,rm as uY,writeFile as kJh}from"node:fs/promises";import{dirname as aC,join as hF}from"node:path";import{isHubProtocolCompatible as SJh}from"@cerebriline/shared";import{resolveClineDataDir as x8,resolveClineDir as Wgh}from"@cerebriline/shared/storage";var IJh="CLINE_HUB_DISCOVERY_PATH",xJh="CLINE_HUB_BUILD_ID",vJh="CLINE_HUB_BUILD_EPOCH_MS",mJh=30000,gJh=15000,gC=100;function cJh(h){return h.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function uJh(h){return CJh("sha256").update(h).digest("hex").slice(0,12)}function lJh(h){if(!Number.isInteger(h)||!h||h<=0)return!1;try{return process.kill(h,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function iC(){return dC(32).toString("hex")}function cC(h){return new Promise(($)=>setTimeout($,h))}function dJh(h){return`${h}.lock`}async function pJh(h){try{let $=JSON.parse(await pC(hF(h,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function tw(h){await uY(h,{recursive:!0,force:!0}).catch(()=>{return})}function S4(){let h=process.env[xJh]?.trim();if(h)return h;return"sdk-v1-1a4964394d75a679fd59b69082126225563ccb3cf9ea367c70703c8a61f1f6ea".trim()||`source-${String(b3.version)}`}function $F(){let h=Number(process.env[vJh]);if(Number.isFinite(h)&&h>0)return h;return Number.isFinite(1791575034234)?1791575034234:void 0}function lY(h,$=S4()){let Z=SJh(h);if(!Z.compatible)return Z;let Q=h.buildId?.trim();if(!Q)return{compatible:!1,reason:"missing_build"};if(Q!==$)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function uC(h){return typeof h==="number"&&Number.isFinite(h)&&h>0?h:void 0}function lC(h){let $=h?.trim().split(/[-+]/,1)[0];if(!$)return;let Z=$.split(".").map((Q)=>Number(Q));if(Z.length===0||Z.some((Q)=>!Number.isInteger(Q)||Q<0))return;return Z}function aJh(h,$){for(let Z=0;Z<Math.max(h.length,$.length);Z++){let Q=h[Z]??0,J=$[Z]??0;if(Q!==J)return Q<J?-1:1}return 0}function rC(h,$){let Z=h.buildId?.trim(),Q=$.buildId?.trim();if(Z&&Q&&Z===Q)return 0;let J=uC(h.buildEpochMs),Y=uC($.buildEpochMs);if(J!==void 0&&Y!==void 0&&J!==Y)return J<Y?-1:1;let X=lC(h.coreVersion),j=lC($.coreVersion);if(X&&j){let W=aJh(X,j);if(W!==0)return W}if(Z&&Q&&Z!==Q)return Z<Q?-1:1;return 0}function nC(){return{buildId:S4(),buildEpochMs:$F(),coreVersion:String(b3.version)}}function v8(h,$){let Z=$?.self??nC(),Q=lY(h,Z.buildId??"");if(Q.compatible)return!0;if(Q.reason!=="build_mismatch"&&Q.reason!=="missing_build")return!1;return rC(Z,h)<=0}function dY(h=process.argv[1]?.trim()||process.cwd()){let $=`hub-${uJh(h)}`,Z=process.env[IJh]?.trim()||hF(x8(),"locks","hub","owners",`${cJh($)}.json`);return{ownerId:$,discoveryPath:Z}}async function t2(h){try{let $=JSON.parse(await pC(h,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function pY(h,$,Z){await ZF(h,async()=>{let Q=aC(h);await ew(Q,{recursive:!0});let J=`${h}.${process.pid}.${dC(6).toString("hex")}.tmp`,Y;try{Y=await mC(J,"wx",384),await Y.writeFile(`${JSON.stringify($,null,2)}
|
|
1459
1459
|
`,{encoding:"utf8"}),await Y.sync(),await Y.close(),Y=void 0,Z?.beforePublish?.(),await PJh(J,h);let X;try{X=await mC(Q,"r"),await X.sync()}catch{}finally{await X?.close().catch(()=>{return})}}catch(X){throw await Y?.close().catch(()=>{return}),await uY(J,{force:!0}).catch(()=>{return}),X}})}async function t3(h){await ZF(h,async()=>{await uY(h,{force:!0}).catch(()=>{return})})}async function sC(h,$){return await ZF(h,async()=>{if((await t2(h))?.hubId!==$)return!1;return await uY(h,{force:!0}),!0})}async function oC(h,$,Z){let Q=dJh(h);await ew(aC(Q),{recursive:!0});let J=Date.now()+gJh;while(!0){try{await ew(Q,{recursive:!1})}catch(Y){if((Y instanceof Error&&"code"in Y?String(Y.code):"")!=="EEXIST")throw Y;let j=await pJh(Q);if(!j){if(Date.now()>=J){await tw(Q);continue}await cC(gC);continue}let W=Date.now()-Date.parse(j.acquiredAt);if(!lJh(j.pid)||W>mJh){await tw(Q);continue}if(Date.now()>=J)throw Error(`Timed out waiting for hub ${$} lock ${Q}`);await cC(gC);continue}try{return await kJh(hF(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
1460
1460
|
`,"utf8"),await Z()}finally{await tw(Q)}}}function ZF(h,$){return oC(`${h}.mutation`,"discovery mutation",$)}function QF(h,$){return oC(h,"startup",$)}async function m8(h,$){try{let Z=await fetch($?.authToken?iJh(h):tC(h),{headers:$?.authToken?{authorization:`Bearer ${$.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function g8(h,$,Z="/hub"){return new URL(`ws://${h}:${$}${Z}`).toString()}function tC(h){let $=new URL(h);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function iJh(h){let $=new URL(tC(h));return $.pathname="/status",$.toString()}var nJh="shared:cline",sJh="CLINE_HUB_DISCOVERY_PATH",oJh="hub-production";function e3(h=nJh){return dY(`${h}@${S4()}`)}function X9(){return{ownerId:oJh,discoveryPath:process.env[sJh]?.trim()||rJh(x8(),"locks","hub","production.json")}}function tJh(h){if(typeof h==="string")return h.trim()||void 0;if(!Array.isArray(h))return;return h.map((Z)=>{if(Z&&typeof Z==="object"&&"type"in Z&&Z.type==="text"&&"text"in Z&&typeof Z.text==="string")return Z.text.trim();return""}).filter(Boolean).join(`
|
|
1461
1461
|
`).trim()||void 0}var eC=120,JF="...";function YF(h){let $=h.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=eC)return $;let Z=eC-Buffer.byteLength(JF,"utf8");if(Z<=0)return JF;let Q="";for(let J of $){if(Buffer.byteLength(Q+J,"utf8")>Z)break;Q+=J}return`${Q}${JF}`}async function hP(h){let $=h?.sessionId?.trim()||"unknown",Z=typeof h?.metadata?.messagesPath==="string"?h.metadata.messagesPath:void 0,J=[...await Z9(Z)].reverse().find((W)=>W.role==="assistant"),Y=J?tJh(J.content):void 0,X=h?.workspaceRoot?.trim()||"workspace",j=typeof h?.metadata?.prompt==="string"?h.metadata.prompt.trim():X;return{title:`Task completed (${$})`,body:YF(Y&&Y.length>0?Y:j.length>0?j:X),severity:"info"}}import{resolve as DVh}from"node:path";import{CLINE_DEFAULT_MODEL_ID as qVh,captureSdkError as _X,createSessionId as GG,HUB_CLIENT_TOOL_APPROVAL_CAPABILITY as zVh}from"@cerebriline/shared";import{isChatWorkspacePath as LVh}from"@cerebriline/shared/storage";function c8(h){return!!h&&typeof h==="object"&&!Array.isArray(h)}function XF(h){let $=h?.trim();return $?$:void 0}function eJh(h,$){let Z=h?.trim();if(!Z)return $;let Q=Date.parse(Z);if(!Number.isFinite(Q))return $;return new Date(Q).toISOString()}function $P(h,$){return new Date(new Date(h).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function ZP(h,$){return new Date(new Date(h).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function hYh(h,$){if(!h)return $;return new Date(h).getTime()>=new Date($).getTime()?h:$}function $Yh(h,$){let Z=h.eventId.trim(),Q=h.eventType.trim(),J=h.source.trim(),Y=XF(h.subject),X=XF(h.dedupeKey)??`${Q}:${J}:${Y??Z}`;return{eventId:Z,eventType:Q,source:J,subject:Y,occurredAt:eJh(h.occurredAt,$),workspaceRoot:XF(h.workspaceRoot),payload:c8(h.payload)?h.payload:void 0,attributes:c8(h.attributes)?h.attributes:void 0,dedupeKey:X}}function jF(h,$){if(!$)return;let Z=$.split("."),Q=h;for(let J of Z){if(!c8(Q))return;Q=Q[J]}return Q}function ZYh(h,$){if(h.attributes&&Object.hasOwn(h.attributes,$))return h.attributes[$];if(h.payload&&Object.hasOwn(h.payload,$))return h.payload[$];let Z={eventId:h.eventId,eventType:h.eventType,source:h.source,subject:h.subject,occurredAt:h.occurredAt,workspaceRoot:h.workspaceRoot,dedupeKey:h.dedupeKey,attributes:h.attributes,payload:h.payload},Q=jF(Z,$);if(Q!==void 0)return Q;if(h.attributes){let J=jF(h.attributes,$);if(J!==void 0)return J}if(h.payload)return jF(h.payload,$);return}function aY(h,$){if(Array.isArray($))return $.some((Z)=>aY(h,Z));if(Array.isArray(h))return h.some((Z)=>aY(Z,$));if(c8($)){if(!c8(h))return!1;return Object.entries($).every(([Z,Q])=>aY(h[Z],Q))}return Object.is(h,$)}function QYh(h,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([Z,Q])=>aY(ZYh(h,Z),Q))}class WF{store;nowFn;logger;constructor(h){this.store=h.store,this.nowFn=h.now??(()=>Date.now()),this.logger=h.logger}ingestEvent(h){let $=new Date(this.nowFn()).toISOString(),Z=$Yh(h,$),Q=this.store.insertEventLog(Z,{receivedAtIso:$});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Z.eventType),Y=[],X=[],j=[];for(let U of J){if(!QYh(Z,U.filters)){Y.push({specId:U.specId,externalId:U.externalId,reason:"filter_mismatch",dedupeKey:Z.dedupeKey});continue}X.push(U);let K=this.materializeForSpec(U,Z,Q.record.receivedAt);if(K.run)j.push(K.run);else Y.push({specId:U.specId,externalId:U.externalId,reason:K.reason,dedupeKey:Z.dedupeKey})}let W=X.length===0?"unmatched":j.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:W,matchedSpecCount:X.length,queuedRunCount:j.length,suppressedCount:Y.filter((U)=>U.reason!=="filter_mismatch").length});let V=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:W,matchedSpecCount:X.length,queuedRunCount:j.length}),{event:V??Q.record,duplicate:!1,matchedSpecs:X,queuedRuns:j,suppressions:Y}}catch(J){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:J});throw J}}materializeForSpec(h,$,Z){let Q=$.dedupeKey??$.eventId,J=h.debounceSeconds??0;if(J>0){let W=this.store.findQueuedEventRunForDedupe({specId:h.specId,dedupeKey:Q});if(W){let V=hYh(W.scheduledFor,$P(Z,J)),U=this.store.updateQueuedEventRunForDebounce({runId:W.runId,triggerEventId:$.eventId,scheduledFor:V});if(U)return{run:U,reason:"dedupe_window"}}}let Y=h.dedupeWindowSeconds??0;if(Y>0&&this.store.hasRecentEventRunForDedupe({specId:h.specId,dedupeKey:Q,sinceIso:ZP(Z,Y)}))return{reason:"dedupe_window"};let X=h.cooldownSeconds??0;if(X>0&&this.store.hasRecentEventRunForSpec({specId:h.specId,sinceIso:ZP(Z,X)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:h.specId,specRevision:h.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:J>0?$P(Z,J):Z}),reason:"dedupe_window"}}}class u8{store;nowFn;constructor(h){this.store=h.store,this.nowFn=h.now??(()=>Date.now())}materializeAll(){let h={oneOffQueued:0,scheduleQueued:0},$=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of $)if(this.materializeOneOff(Q))h.oneOffQueued+=1;let Z=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of Z)try{if(this.materializeSchedule(Q))h.scheduleQueued+=1}catch{}return h}materializeOneOff(h){if(h.triggerKind!=="one_off")return!1;if(!h.enabled||h.removed)return!1;if(this.store.hasConsumedOneOffRevision(h.specId,h.revision))return!1;return this.store.enqueueRun({specId:h.specId,specRevision:h.revision,triggerKind:"one_off",scheduledFor:h.nextRunAt??new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(h){if(h.triggerKind!=="schedule")return!1;if(!h.enabled||h.removed)return!1;if(!h.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:h.specId,nowMs:this.nowFn()}).queued}}import{basename as FYh}from"node:path";import{buildClineSystemPrompt as GYh}from"@cerebriline/shared";import{nowIso as XP}from"@cerebriline/shared/db";import{mkdirSync as JYh,writeFileSync as YYh}from"node:fs";import{isAbsolute as XYh,join as JP}from"node:path";import{resolveCronReportsDir as jYh,resolveCronSpecsDir as WYh}from"@cerebriline/shared/storage";function I4(h){if(/[:#\n]/.test(h)||h.includes('"'))return JSON.stringify(h);return h}function N1(h,$){if($===void 0||$===null)return;return`${h}: ${I4($)}`}function YP(h){let $=0;for(let Q of h.matchAll(/`+/g))$=Math.max($,Q[0].length);let Z="`".repeat(Math.max(3,$+1));return`${Z}
|
package/dist/hub/index.js
CHANGED
|
@@ -299,7 +299,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(h){let $=Math.max(1000,Mat
|
|
|
299
299
|
scheduled_for = COALESCE(?, scheduled_for),
|
|
300
300
|
updated_at = ?
|
|
301
301
|
WHERE run_id = ? AND claim_token = ?`).run(h.error??null,h.scheduledFor??null,$,h.runId,h.claimToken).changes??0)>0}attachSessionIdToRun(h,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,G0(),h)}attachReportPathToRun(h,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,G0(),h)}}function b7(h){return h?new Date(h).getTime():void 0}function zx(h){let $=h.metadata?{...h.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function x9(h){let $=h.metadata;return{scheduleId:h.externalId,name:h.title,cronPattern:h.triggerKind==="one_off"?y7:h.scheduleExpr??"",timezone:h.triggerKind==="schedule"?h.timezone:void 0,prompt:h.prompt??"",workspaceRoot:h.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:h.providerId||h.modelId?{providerId:h.providerId??"",modelId:h.modelId??""}:void 0,enabled:h.enabled&&!h.removed&&h.parseStatus==="valid",mode:h.mode==="plan"?"plan":h.mode==="act"?"act":"yolo",systemPrompt:h.systemPrompt,maxIterations:h.maxIterations,timeoutSeconds:h.timeoutSeconds,maxParallel:h.maxParallel??1,createdAt:new Date(h.createdAt).getTime(),updatedAt:new Date(h.updatedAt).getTime(),nextRunAt:b7(h.nextRunAt),lastRunAt:b7(h.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:h.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:zx(h)}}function Lx(h){switch(h){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function aX(h,$){return{executionId:h.runId,scheduleId:$,sessionId:h.sessionId,triggeredAt:new Date(h.scheduledFor??h.createdAt).getTime(),startedAt:b7(h.startedAt),endedAt:b7(h.completedAt),status:Lx(h.status),errorMessage:h.error}}class C7{store;materializer;runner;started=!1;disposed=!1;constructor(h){this.store=new I9({dbPath:h.dbPath}),this.materializer=new E9({store:this.store}),this.runner=new b9({store:this.store,materializer:this.materializer,runtimeHandlers:h.runtimeHandlers,eventPublisher:h.eventPublisher,workspaceRoot:"",specs:h.specs,logger:h.logger,pollIntervalMs:h.pollIntervalMs,claimLeaseSeconds:h.claimLeaseSeconds,globalMaxConcurrency:h.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(h){if(this.validateScheduleTiming(h.cronPattern,h.timezone,h.metadata,!0),!h.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return x9(this.store.createHubSchedule(h))}getSchedule(h){let $=this.store.getHubSchedule(h);return $?x9($):void 0}listSchedules(h={}){return this.store.listHubSchedules(h).map(($)=>x9($))}updateSchedule(h,$){let Z=this.store.getHubSchedule(h);if(!Z)return;let Q=$.workspaceRoot!==void 0?$.workspaceRoot.trim():Z.workspaceRoot,J=$.enabled??Z.enabled,Y=x9(Z),X=$.cronPattern??Y.cronPattern;if(X.trim()===y7&&typeof $.timezone==="string"&&$.timezone.trim())throw Error("timezone is only supported for recurring schedules");if(this.validateScheduleTiming(X,X.trim()===y7?void 0:$.timezone===null?void 0:$.timezone??Y.timezone,$.metadata??Y.metadata,J),J&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule(h,{...$,scheduleId:h});return j?x9(j):void 0}validateScheduleTiming(h,$,Z,Q){if(h.trim()!==y7){LH(h),lX($);return}if($?.trim())throw Error("timezone is only supported for recurring schedules");let J=Z?.[qx];if(typeof J!=="number"||!Number.isFinite(J)||Q&&J<=Date.now())throw Error("runAt must be a future timestamp")}deleteSchedule(h){return this.store.deleteHubSchedule(h)}pauseSchedule(h){return this.updateSchedule(h,{scheduleId:h,enabled:!1})}resumeSchedule(h){return this.updateSchedule(h,{scheduleId:h,enabled:!0})}async triggerScheduleNow(h){let $=this.store.enqueueHubScheduleRun(h,"manual");if(!$)return;await this.runner.tick();let Z=this.store.getRun($.runId)??$;return aX(Z,h)}triggerScheduleNowDetached(h){let $=this.store.enqueueHubScheduleRun(h,"manual");if(!$)return;return this.runner.tick().catch(()=>{return}),aX($,h)}listScheduleExecutions(h){let $=h.scheduleId?this.store.getHubSchedule(h.scheduleId):void 0,Z={specId:$?.specId,limit:h.limit};return this.store.listRuns(Z).map((J)=>{let Y=$??this.store.getSpec(J.specId);if(!Y||Y.source!=="hub-schedule")return;return aX(J,Y.externalId)}).filter((J)=>{if(!J)return!1;return!h.status||J.status===h.status})}getScheduleStats(h){let $=this.listScheduleExecutions({scheduleId:h,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,Y;for(let X of $){if(X.status==="success"||X.status==="completed")Z+=1;if(!Y&&X.status!=="success"&&X.status!=="completed")Y=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:$.length,successRate:Z/$.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:Y}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((h)=>{let $=this.store.getSpec(h.specId);if(!$||$.source!=="hub-schedule"||!h.sessionId)return[];return[{executionId:h.runId,scheduleId:$.externalId,sessionId:h.sessionId,startedAt:h.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&h.startedAt?new Date(new Date(h.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(h=20){let $={triggerKind:"schedule",enabled:!0,limit:h};return this.store.listSpecs($).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,h).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}import{realpathSync as oX,statSync as Cx}from"node:fs";import{isAbsolute as hB,relative as Px,sep as $B}from"node:path";import{ONE_TIME_SCHEDULE_CRON_PATTERN as ZB,ONE_TIME_SCHEDULE_RUN_AT_METADATA_KEY as QB}from"@cerebriline/shared";import{z as h0}from"zod";import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as Ax,captureAgentUnexpectedReasoningTokens as K_h,captureTaskLifecycleEvent as __h,SDK_ERROR_TELEMETRY_EVENT as fx,TASK_CANCELLED_EVENT as Ox,TASK_FIRST_CHUNK_RECEIVED_EVENT as Nx,TASK_PROVIDER_REQUEST_STARTED_EVENT as Mx,TASK_PROVIDER_STREAM_FAILED_EVENT as Tx,TASK_PROVIDER_STREAM_STARTED_EVENT as Rx}from"@cerebriline/shared";var Ex=500,Oh={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:Ax},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",AUTH_REFRESH_SOFT_FAILURE:"user.auth_refresh_soft_failure",AUTH_RUN_RETRY:"user.auth_run_retry",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MISTAKE_LIMIT_REACHED:"task.mistake_limit_reached",PROVIDER_REQUEST_STARTED:Mx,PROVIDER_STREAM_STARTED:Rx,FIRST_CHUNK_RECEIVED:Nx,PROVIDER_STREAM_FAILED:Tx,CANCELLED:Ox,MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped",COMPACTION_BUDGET_EMERGENCY:"task.compaction_budget_emergency"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:fx,TOOL_TIMEOUT:"sdk.tool_timeout",PLAN_MODE_COMMAND_BLOCKED:"sdk.plan_mode_command_blocked"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}};function Th(h,$,Z){h?.capture({event:$,properties:Z})}function iX(h){if(!h)return;return h.substring(0,Ex)}function yx(h){if(typeof h==="string")return"Error";return h.name?.trim()||h.constructor?.name||"Error"}function bx(h){return typeof h==="string"?h:h.message}function bH(h,$){return h.some((Z)=>$.has(Z.trim().toLowerCase()))}function CH(h,$){let Z=[...$.vcs_types],Q={root_count:$.root_count,vcs_types:Z,is_multi_root:$.root_count>1,has_git:bH(Z,new Set(["git"])),has_mercurial:bH(Z,new Set(["mercurial","hg"]))};if($.init_duration_ms!==void 0)Q.init_duration_ms=$.init_duration_ms;if($.feature_flag_enabled!==void 0)Q.feature_flag_enabled=$.feature_flag_enabled;if($.is_remote_workspace!==void 0)Q.is_remote_workspace=$.is_remote_workspace;Th(h,Oh.WORKSPACE.INITIALIZED,Q)}function PH(h,$,Z){Th(h,Oh.WORKSPACE.INIT_ERROR,{error_type:yx($),error_message:iX(bx($)),fallback_to_single_root:Z.fallback_to_single_root,workspace_count:Z.workspace_count??0})}function f$(h,$){Th(h,Oh.USER.AUTH_STARTED,{provider:$})}function O$(h,$,Z){Th(h,Oh.USER.AUTH_SUCCEEDED,{provider:$,...Z})}function t4(h,$,Z,Q){Th(h,Oh.USER.AUTH_FAILED,{provider:$,errorMessage:iX(Z),...Q?.requestId?{request_id:Q.requestId}:{}})}function N$(h,$,Z,Q){Th(h,Oh.USER.AUTH_LOGGED_OUT,{provider:$,reason:Z,...Q})}function e4(h,$,Z){Th(h,Oh.USER.AUTH_REFRESH_SOFT_FAILURE,{provider:$,...Z})}function kH(h,$,Z){Th(h,Oh.USER.AUTH_RUN_RETRY,{provider:$,recovered:Z?.recovered})}function SH(h,$){h?.captureRequired(Oh.USER.TELEMETRY_OPT_OUT,$)}function M$(h,$){let Z=$.id?.trim();if(Z)h?.setDistinctId(Z);h?.updateCommonProperties({user_id:Z||$.id,account_id:$.id,account_email:$.email,provider:$.provider,organization_id:$.organizationId,organization_name:$.organizationName,member_id:$.memberId})}function IH(h,$){Th(h,Oh.TASK.CREATED,$)}function xH(h,$){Th(h,Oh.TASK.RESTARTED,$)}function rX(h,$){Th(h,Oh.TASK.COMPLETED,$)}function P7(h,$){Th(h,Oh.TASK.CONVERSATION_TURN,{...$,timestamp:new Date().toISOString()})}function vH(h,$){Th(h,Oh.TASK.TOKEN_USAGE,$)}function mH(h,$,Z){Th(h,Oh.TASK.MODE_SWITCH,{ulid:$,mode:Z})}function W4(h,$){Th(h,Oh.TASK.TOOL_USED,$)}function gH(h,$){Th(h,Oh.TASK.SKILL_USED,$)}function cH(h,$){Th(h,Oh.TASK.DIFF_EDIT_FAILED,$)}function uH(h,$){Th(h,Oh.TASK.MISTAKE_LIMIT_REACHED,{...$,timestamp:new Date().toISOString()})}function lH(h,$){Th(h,Oh.SDK.TOOL_TIMEOUT,dH($))}function k7(h,$){Th(h,Oh.SDK.PLAN_MODE_COMMAND_BLOCKED,dH($))}function dH(h){let $={};for(let[Z,Q]of Object.entries(h))if(Q!==void 0)$[Z]=Q;return $}function pH(h,$,Z){Th(h,Oh.TASK.MENTION_USED,{mentionType:$,contentLength:Z,timestamp:new Date().toISOString()})}function aH(h,$,Z,Q){Th(h,Oh.TASK.MENTION_FAILED,{mentionType:$,errorType:Z,errorMessage:iX(Q),timestamp:new Date().toISOString()})}function iH(h,$,Z,Q,J){Th(h,Oh.TASK.MENTION_SEARCH_RESULTS,{queryLength:$.length,resultCount:Z,searchType:Q,isEmpty:J,timestamp:new Date().toISOString()})}function T$(h,$){Th(h,Oh.TASK.AGENT_CREATED,{...$,timestamp:new Date().toISOString()})}function rH(h,$){Th(h,Oh.TASK.AGENT_TEAM_CREATED,{...$,timestamp:new Date().toISOString()})}function nX(h,$){Th(h,$.event==="ended"?Oh.TASK.SUBAGENT_COMPLETED:Oh.TASK.SUBAGENT_STARTED,{...$,timestamp:new Date().toISOString()})}function nH(h,$,Z,Q){Th(h,Oh.HOOKS.DISCOVERY_COMPLETED,{hookName:$,globalCount:Z,workspaceCount:Q,totalCount:Z+Q,timestamp:new Date().toISOString()})}function sH(h,$){Th(h,Oh.TASK.COMPACTION_EXECUTED,{...$,timestamp:new Date().toISOString()})}function oH(h,$){Th(h,Oh.TASK.COMPACTION_SKIPPED,{...$,timestamp:new Date().toISOString()})}function tH(h,$){Th(h,Oh.TASK.COMPACTION_BUDGET_EMERGENCY,{...$,timestamp:new Date().toISOString()})}var kx=h0.enum(["create","update","list","get","pause","resume","delete","run_now"]),Sx=h0.object({provider_id:h0.string().min(1),model_id:h0.string().min(1).optional()}),b$=h0.object({operation:kx,schedule_id:h0.string().min(1).optional(),schedule_type:h0.enum(["once","recurring"]).optional(),name:h0.string().min(1).optional(),prompt:h0.string().min(1).optional(),run_at:h0.string().datetime({offset:!0}).optional(),cron_pattern:h0.string().min(1).optional(),timezone:h0.string().min(1).nullable().optional(),enabled:h0.boolean().optional(),mode:h0.enum(["act","plan","yolo"]).optional(),system_prompt:h0.string().nullable().optional(),max_iterations:h0.number().int().positive().nullable().optional(),timeout_seconds:h0.number().int().positive().nullable().optional(),max_parallel:h0.number().int().positive().max(32).optional(),tags:h0.array(h0.string().min(1)).optional(),model_selection:Sx.optional(),limit:h0.number().int().positive().max(200).optional()});function R$(h,$,Z,Q){if(!JB.has($.operation))return;W4(h.telemetry,{ulid:Z.sessionId??Z.conversationId??Z.agentId,tool:`tasks.scheduled.${$.operation}`,success:Q,agentId:Z.agentId})}var JB=new Set(["create","update","pause","resume","delete","run_now"]);function y$(h,$){let Z=h?.trim();if(!Z)throw Error(`${$} is required for this operation`);return Z}function tX(h,$){try{let Z=oX.native(h);if(!Cx(Z).isDirectory())throw Error("not a directory");return Z}catch{throw Error(`${$} does not resolve to an existing safe path`)}}function Ix(h,$){try{return oX.native(h)===oX.native($)}catch{return!1}}function YB(h,$,Z){let Q=Px(h,$);if(Q===".."||Q.startsWith(`..${$B}`)||hB(Q))throw Error(`${Z} is outside the workspace scope`)}function XB(h,$,Z){return tX(hB($)?$:`${h}${$B}${$}`,Z)}function xx(h){let $=tX(h.workspaceRoot,"workspaceRoot"),Z=h.cwd?XB($,h.cwd,"cwd"):$;return YB($,Z,"cwd"),{...h,workspaceRoot:$,cwd:Z}}function E$(h,$){if(!h)throw Error("schedule does not exist");if(!Ix(h.workspaceRoot,$.workspaceRoot))throw Error("schedule is outside this session's workspace scope");let Z=tX(h.workspaceRoot,"schedule workspaceRoot");if(h.cwd){let Q=XB(Z,h.cwd,"schedule cwd");YB(Z,Q,"schedule cwd")}}function eH(h){if(!h)return;return{providerId:h.provider_id.trim(),modelId:h.model_id?.trim()||void 0}}function sX(h){if(!h)return;return[...new Set(h.map(($)=>$.trim()).filter(Boolean))]}function jB(h){let $=Date.parse(y$(h,"run_at"));if(!Number.isFinite($))throw Error("run_at must be an ISO timestamp");if($<=Date.now())throw Error("run_at must be in the future");return $}function vx(h){if(h.schedule_type==="once"){if(h.cron_pattern)throw Error("cron_pattern cannot be used with a one-time schedule");if(h.timezone)throw Error("timezone is encoded in run_at for a one-time schedule");return{cronPattern:ZB,metadata:{[QB]:jB(h.run_at)}}}if(h.schedule_type==="recurring"){if(h.run_at)throw Error("run_at cannot be used with a recurring schedule");return{cronPattern:y$(h.cron_pattern,"cron_pattern"),timezone:h.timezone?.trim()||void 0}}throw Error("schedule_type is required for create")}function mx(h){if(h.run_at&&h.cron_pattern)throw Error("run_at and cron_pattern cannot be updated together");if(h.schedule_type==="once"||h.run_at){if(h.cron_pattern)throw Error("cron_pattern cannot be used with a one-time schedule");if(h.timezone)throw Error("timezone is encoded in run_at for a one-time schedule");return{cronPattern:ZB,timezone:null,metadata:{[QB]:jB(h.run_at)}}}if(h.schedule_type==="recurring"||h.cron_pattern)return{cronPattern:y$(h.cron_pattern,"cron_pattern"),timezone:h.timezone===null?null:h.timezone?.trim()||void 0};return{timezone:h.timezone===null?null:h.timezone?.trim()||void 0}}function v9(h){return y$(h.schedule_id,"schedule_id")}async function eX(h,$,Z){let Q=b$.safeParse($);if(!Q.success)return{ok:!1,error:{code:"invalid_schedule_input",message:Q.error.issues[0]?.message??"Invalid schedule input"}};let J=Q.data;try{if(!Z.sessionId)throw Error("tasks requires a Hub session");let Y=await h.resolveSessionDefaults(Z.sessionId);if(!Y?.workspaceRoot.trim())throw Error("tasks could not resolve the current workspace");let X=xx(Y);if(JB.has(J.operation)&&!X.interactive)throw Error("schedule mutations require an interactive user session");switch(J.operation){case"create":{let j=h.schedules.createSchedule({name:y$(J.name,"name"),...vx(J),prompt:y$(J.prompt,"prompt"),workspaceRoot:X.workspaceRoot,cwd:X.cwd,modelSelection:eH(J.model_selection)??X.modelSelection,enabled:J.enabled,mode:J.mode??"yolo",systemPrompt:J.system_prompt??void 0,maxIterations:J.max_iterations??void 0,timeoutSeconds:J.timeout_seconds??void 0,maxParallel:J.max_parallel??1,createdBy:`agent:${Z.agentId}`,tags:sX(J.tags)});return h.publish?.("schedule.created",{schedule:j},Z.sessionId),R$(h,J,Z,!0),{ok:!0,operation:J.operation,schedule:j}}case"update":{let j=v9(J);E$(h.schedules.getSchedule(j),X);let W=h.schedules.updateSchedule(j,{scheduleId:j,...mx(J),name:J.name?.trim()||void 0,prompt:J.prompt?.trim()||void 0,modelSelection:eH(J.model_selection),enabled:J.enabled,mode:J.mode,systemPrompt:J.system_prompt,maxIterations:J.max_iterations,timeoutSeconds:J.timeout_seconds,maxParallel:J.max_parallel,tags:sX(J.tags)});if(!W)throw Error("schedule does not exist");return h.publish?.("schedule.updated",{schedule:W},Z.sessionId),R$(h,J,Z,!0),{ok:!0,operation:J.operation,schedule:W}}case"list":{let j=h.schedules.listSchedules({enabled:J.enabled,tags:sX(J.tags),workspaceRoot:X.workspaceRoot,limit:J.limit??50}).filter((W)=>{try{return E$(W,X),!0}catch{return!1}}).slice(0,J.limit??50);return{ok:!0,operation:J.operation,schedules:j}}case"get":{let j=h.schedules.getSchedule(v9(J));return E$(j,X),{ok:!0,operation:J.operation,schedule:j}}case"pause":case"resume":{let j=v9(J);E$(h.schedules.getSchedule(j),X);let W=J.operation==="pause"?h.schedules.pauseSchedule(j):h.schedules.resumeSchedule(j);if(!W)throw Error("schedule does not exist");return h.publish?.("schedule.updated",{schedule:W},Z.sessionId),R$(h,J,Z,!0),{ok:!0,operation:J.operation,schedule:W}}case"delete":{let j=v9(J);E$(h.schedules.getSchedule(j),X);let W=h.schedules.deleteSchedule(j);if(!W)throw Error("schedule does not exist");return h.publish?.("schedule.deleted",{deleted:W,scheduleId:j},Z.sessionId),R$(h,J,Z,!0),{ok:!0,operation:J.operation,deleted:W}}case"run_now":{let j=v9(J);E$(h.schedules.getSchedule(j),X);let W=h.schedules.triggerScheduleNowDetached(j);if(!W)throw Error("schedule does not exist");return h.publish?.("schedule.triggered",{execution:W},Z.sessionId),R$(h,J,Z,!0),{ok:!0,operation:J.operation,execution:W}}}}catch(Y){return R$(h,J,Z,!1),{ok:!1,operation:J.operation,error:{code:"schedule_operation_failed",message:Y instanceof Error?Y.message:String(Y)}}}}import{metrics as wv,trace as Fv}from"@opentelemetry/api";import{logs as Gv}from"@opentelemetry/api-logs";import{OTLPLogExporter as Hv}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as Bv}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as Dv}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as qv}from"@opentelemetry/resources";import{BatchLogRecordProcessor as zv,ConsoleLogRecordExporter as Lv,LoggerProvider as Av}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as fv,MeterProvider as Ov,PeriodicExportingMetricReader as OB}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as Nv,ConsoleSpanExporter as Mv,SimpleSpanProcessor as Tv}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as Rv}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as Ev,ATTR_SERVICE_VERSION as yv}from"@opentelemetry/semantic-conventions";import{mkdirSync as gx,readFileSync as cx,statSync as ux,writeFileSync as lx}from"node:fs";import{dirname as dx}from"node:path";import{CONFIGURABLE_MODEL_TOOL_NAMES as WB}from"@cerebriline/shared";import{resolveGlobalSettingsPath as VB}from"@cerebriline/shared/storage";import{z as U0}from"zod";var hj=U0.preprocess((h)=>Array.isArray(h)?h.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,U0.array(U0.string()).optional()).transform((h)=>{if(!h)return;let $=[...new Set(h)].sort((Z,Q)=>Z.localeCompare(Q));return $.length>0?$:void 0}),px=U0.enum(["basic","agentic"]).catch("agentic"),ax=U0.partialRecord(U0.enum(WB),U0.object({enabled:U0.boolean()}).strip()).optional(),ix=U0.record(U0.string(),U0.object({enabled:U0.boolean()}).strip()).optional().catch(void 0),rx=U0.enum(["plan","act"]),$j=U0.object({telemetryOptOut:U0.boolean().default(!1).catch(!1),autoUpdateEnabled:U0.boolean().default(!0).catch(!0),compactionStrategy:px.optional(),compactionEnabled:U0.boolean().optional().catch(void 0),planActMode:rx.optional().catch(void 0),toolAutoApprove:U0.boolean().optional().catch(void 0),tuiTheme:U0.string().optional().catch(void 0),disabledTools:hj.optional(),tools:ax,disabledPlugins:hj.optional(),disabledAgentPlugins:hj.optional(),bundledSkills:ix}).strip().transform((h)=>{let $={autoUpdateEnabled:h.autoUpdateEnabled,telemetryOptOut:h.telemetryOptOut};if(h.compactionStrategy)$.compactionStrategy=h.compactionStrategy;if(h.compactionEnabled!==void 0)$.compactionEnabled=h.compactionEnabled;if(h.planActMode)$.planActMode=h.planActMode;if(h.toolAutoApprove!==void 0)$.toolAutoApprove=h.toolAutoApprove;if(h.tuiTheme?.trim())$.tuiTheme=h.tuiTheme.trim();if(h.disabledTools?.length)$.disabledTools=h.disabledTools;if(h.tools&&Object.keys(h.tools).length>0)$.tools=h.tools;if(h.disabledPlugins?.length)$.disabledPlugins=h.disabledPlugins;if(h.disabledAgentPlugins?.length)$.disabledAgentPlugins=h.disabledAgentPlugins;if(h.bundledSkills&&Object.keys(h.bundledSkills).length>0)$.bundledSkills=h.bundledSkills;return $});function S7(){return $j.parse({})}var I7;function nx(){I7=void 0}function sx(h){if(h.disabledTools)Object.freeze(h.disabledTools);if(h.tools){for(let $ of Object.values(h.tools))Object.freeze($);Object.freeze(h.tools)}if(h.disabledPlugins)Object.freeze(h.disabledPlugins);if(h.disabledAgentPlugins)Object.freeze(h.disabledAgentPlugins);return Object.freeze(h)}function ox(h){let $;try{$=cx(h,"utf8")}catch{return S7()}try{let Z=$j.safeParse(JSON.parse($));return Z.success?Z.data:S7()}catch{return S7()}}function tx(){let h=VB(),$=ux(h,{throwIfNoEntry:!1}),Z=$?.mtimeMs??0,Q=$?.size??0,J=I7;if(J&&J.path===h&&J.mtimeMs===Z&&J.size===Q)return J;let Y=sx($?ox(h):S7());return I7={path:h,mtimeMs:Z,size:Q,value:Y},I7}function R0(){return tx().value}function h3(h,$={}){let Z=VB(),Q=R0();gx(dx(Z),{recursive:!0});let J=$j.parse(h);if(!Q.telemetryOptOut&&J.telemetryOptOut)SH($.telemetry);lx(Z,`${JSON.stringify(J,null,2)}
|
|
302
|
-
`,"utf8"),nx()}function UB(){return R0().telemetryOptOut}function $3(h){return new Set(h??R0().disabledTools??[])}function KB(h){return new Set(h??R0().disabledPlugins??[])}function m9(h){return new Set(h??R0().disabledAgentPlugins??[])}function _B(h){return WB.includes(h)}function ex(){return R0().tools??{}}function Zj(h){return ex()[h]?.enabled===!0}function hv(h,$){let Z=R0();h3({...Z,tools:{...Z.tools,[h]:{enabled:$}}})}function wB(h){if(_B(h)){let J=Zj(h);return hv(h,!J),J}let $=R0(),Z=new Set($.disabledTools??[]),Q=Z.has(h);if(Q)Z.delete(h);else Z.add(h);return h3({...$,disabledTools:[...Z]}),!Q}function $v(h,$){let Z=[...new Set(h.map((X)=>X.trim()).filter(Boolean))];if(Z.length===0)return;let Q=R0(),J=$3(Q.disabledTools),Y={...Q.tools};for(let X of Z){if(_B(X)){Y[X]={enabled:!$};continue}if($)J.add(X);else J.delete(X)}h3({...Q,disabledTools:[...J],tools:Y})}function FB(h,$){return $v([h],$),$}function GB(h,$){let Z=h.trim();if(!Z)return;let Q=R0(),J=KB(Q.disabledPlugins);if($)J.add(Z);else J.delete(Z);h3({...Q,disabledPlugins:[...J]})}function HB(h,$){let Z=h.trim();if(!Z)return;let Q=R0(),J=m9(Q.disabledAgentPlugins);if($)J.add(Z);else J.delete(Z);h3({...Q,disabledAgentPlugins:[...J]})}function BB(h,$){let Z=KB($);if(Z.size===0)return[...h];return h.filter((Q)=>!Z.has(Q))}function V4(h,$){let Z=$3($);if(Z.size===0)return[...h];return h.filter((Q)=>!Z.has(Q.name))}function DB(h,$){if(!h||h.length===0)return h;let Z=$3($);if(Z.size===0)return h;return h.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(J,Y)=>Q.setup?.({...J,registerTool:(X)=>{if(!Z.has(X.name))J.registerTool(X)}},Y)}})}import{existsSync as Zv,mkdirSync as Qv,readFileSync as Jv,writeFileSync as Yv}from"node:fs";import{resolve as Xv}from"node:path";import{resolveSessionDataDir as jv}from"@cerebriline/shared/storage";import{nanoid as Wv}from"nanoid";import*as Vv from"node-machine-id";var Uv="machine-id",qB,zB=!1;function LB(){if(!zB)qB=AB(),zB=!0;return qB??fB()}function g9(h){let $=h?.trim();if($)return $;let Z=AB();if(Z)return Z;return fB()}function Kv(){let h=Vv;return h.machineIdSync??h.default?.machineIdSync}function AB(){try{let h=Kv();if(!h)return;return h().trim()||void 0}catch{return}}function fB(){let h=jv(),$=Xv(h,Uv);try{if(Zv($)){let Q=Jv($,"utf8").trim();if(Q.length>0)return Q}}catch{}let Z=`cl-${Wv()}`;try{Qv(h,{recursive:!0}),Yv($,Z,"utf8")}catch{}return Z}class Qj{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(h){this.name=h.name??"OpenTelemetryAdapter",this.metadata={...h.metadata},this.meterProvider=h.meterProvider,this.loggerProvider=h.loggerProvider,this.meter=h.meterProvider?.getMeter("cline")??null,this.logger=h.loggerProvider?.getLogger("cline")??null,this.enabled=h.enabled??!0,this.distinctId=h.distinctId,this.commonProperties=h.commonProperties?{...h.commonProperties}:{}}emit(h,$){if(!this.isEnabled())return;this.emitLog(h,$,!1)}emitRequired(h,$){this.emitLog(h,$,!0)}recordCounter(h,$,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let Y=this.counters.get(h);if(!Y)Y=this.meter.createCounter(h,Q?{description:Q}:void 0),this.counters.set(h,Y);Y.add($,this.flattenProperties(this.buildAttributes(Z)))}recordHistogram(h,$,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let Y=this.histograms.get(h);if(!Y)Y=this.meter.createHistogram(h,Q?{description:Q}:void 0),this.histograms.set(h,Y);Y.record($,this.flattenProperties(this.buildAttributes(Z)))}recordGauge(h,$,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let Y=this.buildAttributes(Z),X=JSON.stringify(Y),j=this.gaugeValues.get(h);if($===null){if(j){if(j.delete(X),j.size===0)this.gaugeValues.delete(h),this.gauges.delete(h)}return}let W=j;if(!W)W=new Map,this.gaugeValues.set(h,W);if(!this.gauges.has(h)){let V=this.meter.createObservableGauge(h,Q?{description:Q}:void 0);V.addCallback((U)=>{for(let K of this.snapshotGaugeSeries(h))U.observe(K.value,this.flattenProperties(K.attributes))}),this.gauges.set(h,V)}W.set(X,{value:$,attributes:Y})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(h){this.distinctId=h}setCommonProperties(h){this.commonProperties={...h}}updateCommonProperties(h){this.commonProperties={...this.commonProperties,...h}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(h,$,Z){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes($,Z));this.logger.emit({severityText:"INFO",body:h,attributes:Q})}buildAttributes(h,$=!1){return{...this.commonProperties,...this.metadata,...h,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(h){let $=this.gaugeValues.get(h);if(!$)return[];return Array.from($.values(),(Z)=>({value:Z.value,attributes:Z.attributes?{...Z.attributes}:void 0}))}flattenProperties(h,$="",Z=new WeakSet,Q=0){if(!h)return{};let J={},Y=100,X=10;for(let[j,W]of Object.entries(h)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let V=$?`${$}.${j}`:j;if(W===null||W===void 0){J[V]=String(W);continue}if(Array.isArray(W)){let U=W.length>Y?W.slice(0,Y):W;try{J[V]=JSON.stringify(U)}catch{J[V]="[UnserializableArray]"}if(W.length>Y)J[`${V}_truncated`]=!0,J[`${V}_original_length`]=W.length;continue}if(typeof W==="object"){if(W instanceof Date){J[V]=W.toISOString();continue}if(W instanceof Error){J[V]=W.message;continue}if(Z.has(W)){J[V]="[Circular]";continue}if(Q>=X){J[V]="[MaxDepthExceeded]";continue}Z.add(W),Object.assign(J,this.flattenProperties(W,V,Z,Q+1));continue}if(_v(W)){J[V]=W;continue}try{J[V]=JSON.stringify(W)}catch{J[V]=String(W)}}return J}}function _v(h){return typeof h==="string"||typeof h==="number"||typeof h==="boolean"}class Jj{name;logger;enabled;constructor(h={}){this.name=h.name??"TelemetryLoggerSink",this.logger=h.logger,this.enabled=h.enabled??!0}emit(h,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:h,properties:$})}emitRequired(h,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:h,properties:$})}recordCounter(h,$,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:h,value:$,attributes:Z,description:Q,required:J===!0})}recordHistogram(h,$,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:h,value:$,attributes:Z,description:Q,required:J===!0})}recordGauge(h,$,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:h,value:$,attributes:Z,description:Q,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class x7{adapters;metadata;distinctId;deviceId;commonProperties;constructor(h={}){if(this.adapters=[...h.adapters??[]],h.logger)this.adapters.push(new Jj({logger:h.logger}));this.metadata={...h.metadata??{}},this.distinctId=h.distinctId,this.deviceId=h.deviceId??LB(),this.commonProperties={...h.commonProperties??{}}}addAdapter(h){this.adapters.push(h)}setDistinctId(h){this.distinctId=h}setMetadata(h){this.metadata={...h}}updateMetadata(h){this.metadata={...this.metadata,...h}}setCommonProperties(h){this.commonProperties={...h}}updateCommonProperties(h){this.commonProperties={...this.commonProperties,...h}}isEnabled(){return this.adapters.some((h)=>h.isEnabled())}capture(h){let $=this.buildAttributes(h.properties);for(let Z of this.adapters)Z.emit(h.event,$)}captureRequired(h,$){let Z=this.buildAttributes($);for(let Q of this.adapters)Q.emitRequired(h,Z)}recordCounter(h,$,Z,Q,J=!1){let Y=this.buildAttributes(Z);for(let X of this.adapters)X.recordCounter(h,$,Y,Q,J)}recordHistogram(h,$,Z,Q,J=!1){let Y=this.buildAttributes(Z);for(let X of this.adapters)X.recordHistogram(h,$,Y,Q,J)}recordGauge(h,$,Z,Q,J=!1){let Y=this.buildAttributes(Z);for(let X of this.adapters)X.recordGauge(h,$,Y,Q,J)}async flush(){await Promise.all(this.adapters.map((h)=>h.flush()))}async dispose(){await Promise.all(this.adapters.map((h)=>h.dispose()))}buildAttributes(h){return{...this.commonProperties,...h,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{},device_id:this.deviceId}}}class NB{distinctId;metadata;commonProperties;constructor(h={}){this.distinctId=h.distinctId,this.metadata={...h.metadata??{}},this.commonProperties={...h.commonProperties??{}}}setDistinctId(h){this.distinctId=h}setMetadata(h){this.metadata={...h}}updateMetadata(h){this.metadata={...this.metadata,...h}}setCommonProperties(h){this.commonProperties={...h}}updateCommonProperties(h){this.commonProperties={...this.commonProperties,...h}}isEnabled(){return!1}capture(h){this.resolveProperties(h.properties)}captureRequired(h,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(h){return{...this.commonProperties,...h,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class MB{meterProvider;loggerProvider;tracerProvider;options;constructor(h={}){this.options=h;let $=qv({[Ev]:h.serviceName??"cline",...h.serviceVersion?{[yv]:h.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)wv.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)Gv.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(h="cline",$){return Fv.getTracer(h,$??this.options.serviceVersion)}createAdapter(h){return new Qj({...h,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(h){let $=this.createAdapter({name:h.name,enabled:this.options.enabled,metadata:h.metadata});return new x7({...h,adapters:[$],distinctId:g9(h.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(h){let $=Yj(this.options.metricsExporter);if($.length===0)return null;let Z=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(Z*0.8)),J=$.map((Y)=>Sv(Y,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Z,timeout:Q})).filter((Y)=>Y!==null);if(J.length===0)return null;return new Ov({resource:h,readers:J})}createTracerProvider(h){let $=Yj(this.options.tracesExporter);if($.length===0)return null;let Z=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let Y of $){let X=kv(Y,{endpoint:Z,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(X)J.push(X)}if(J.length===0)return null;return new Rv({resource:h,spanProcessors:J})}createLoggerProvider(h){let $=Yj(this.options.logsExporter);if($.length===0)return null;let Z=$.map((Q)=>{let J=Pv(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new zv(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(Z.length===0)return null;return new Av({resource:h,processors:Z})}}function bv(h){let $=new MB(h),Z=$.createTelemetryService(h),Q=()=>{Z.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:h.enabled??!0,logsExporter:Array.isArray(h.logsExporter)?h.logsExporter.join(","):h.logsExporter,metricsExporter:Array.isArray(h.metricsExporter)?h.metricsExporter.join(","):h.metricsExporter,tracesExporter:Array.isArray(h.tracesExporter)?h.tracesExporter.join(","):h.tracesExporter,otlpProtocol:h.otlpProtocol,hasOtlpEndpoint:Boolean(h.otlpEndpoint),serviceName:h.serviceName,serviceVersion:h.serviceVersion})};if(!h.deferProviderCreatedEvent)Q();return{provider:$,telemetry:Z,emitProviderCreated:Q}}function TB(h){if(UB())return{telemetry:new NB(h)};if(h.enabled!==!0)return{telemetry:new x7({...h,distinctId:g9(h.distinctId)})};return bv(h)}function Cv(h){let{telemetry:$,provider:Z,emitProviderCreated:Q}=TB(h);return{telemetry:$,provider:Z,flush:async()=>{let X=Z;if(X&&typeof X.forceFlush==="function")try{await X.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),Z?.dispose()])},...h.deferProviderCreatedEvent&&Q?{emitProviderCreated:Q}:{}}}function Yj(h){if(!h)return[];return(Array.isArray(h)?h:h.split(",")).map((Z)=>Z.trim()).filter((Z)=>Z==="console"||Z==="otlp")}function Pv(h,$){if(h==="console")return new Lv;if(!$.endpoint)return null;let Z=Xj($.endpoint,"/v1/logs");return new Hv({url:Z,headers:$.headers})}function kv(h,$){if(h==="console")return new Tv(new Mv);if(!$.endpoint)return null;let Z=Xj($.endpoint,"/v1/traces");return new Nv(new Dv({url:Z,headers:$.headers}))}function Sv(h,$){if(h==="console")return new OB({exporter:new fv,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let Z=Xj($.endpoint,"/v1/metrics");return new OB({exporter:new Bv({url:Z,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function Xj(h,$){let Z=new URL(h),Q=Z.pathname.endsWith("/")?Z.pathname.slice(0,-1):Z.pathname;return Z.pathname=Q.endsWith($)?Q:`${Q}${$}`,Z.toString()}import{createTool as gv,zodToJsonSchema as cv}from"@cerebriline/shared";import{z as Z2}from"zod";import{resolve as RB}from"node:path";import{z as Fh}from"zod";var EB=Fh.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),Iv=Fh.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),yB=Fh.union([Fh.literal(0),Fh.literal(1),Fh.literal(2),Fh.literal(3),Fh.literal(4),Fh.literal(5)]),xv=Fh.object({provider_id:Fh.string().min(1),model_id:Fh.string().min(1).optional()}),v7=Fh.object({operation:Fh.enum(["create","update","list","get"]),task_id:Fh.string().min(1).optional(),expected_revision:Fh.number().int().positive().optional(),type:EB.optional(),title:Fh.string().min(1).optional(),description:Fh.string().nullable().optional(),instructions:Fh.string().min(1).optional(),scope:Fh.enum(["workspace","global"]).optional(),workspace_root:Fh.string().min(1).nullable().optional(),cwd:Fh.string().min(1).nullable().optional(),resource_paths:Fh.array(Fh.string().min(1)).optional(),priority:yB.optional(),assignee:Fh.string().min(1).nullable().optional(),model_selection:xv.nullable().optional(),mode:Fh.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Fh.string().nullable().optional(),max_iterations:Fh.number().int().positive().nullable().optional(),timeout_seconds:Fh.number().int().positive().nullable().optional(),available_at:Fh.string().datetime().optional(),expires_at:Fh.string().datetime().optional(),automation_eligible:Fh.boolean().optional(),statuses:Fh.array(Iv).optional(),types:Fh.array(EB).optional(),priorities:Fh.array(yB).optional(),limit:Fh.number().int().positive().max(500).optional()}),vv=new Set(["create","update"]);function jj(h,$,Z,Q){if(!vv.has($.operation))return;W4(h.telemetry,{ulid:Z.sessionId??Z.conversationId??Z.agentId,tool:`tasks.todo.${$.operation}`,success:Q,agentId:Z.agentId})}function C$(h,$){let Z=h?.trim();if(!Z)throw Error(`${$} is required for this operation`);return Z}function bB(h){if(h===void 0||h===null)return h;return{providerId:h.provider_id,modelId:h.model_id}}function PB(h,$){return RB(h)===RB($)}function CB(h,$){if(!h)throw Error("task does not exist");if($.workspaceRoot){if(h.scope!=="workspace"||!h.workspaceRoot||!PB(h.workspaceRoot,$.workspaceRoot))throw Error("task is outside this session's workspace scope");return}if(h.scope!=="global")throw Error("task is outside this session's global scope")}function mv(h,$){let Z=$.workspaceRoot?"workspace":"global";if(h.scope&&h.scope!==Z)throw Error(`this session can only manage ${Z} tasks`);if(h.workspace_root!==void 0){if(!$.workspaceRoot||h.workspace_root===null||!PB(h.workspace_root,$.workspaceRoot))throw Error(`this session can only manage ${Z} tasks`)}return Z}async function kB(h,$,Z){let Q=v7.safeParse($);if(!Q.success)return{ok:!1,error:{code:"invalid_task_input",message:Q.error.issues[0]?.message??"Invalid task input"}};let J=Q.data,Y={kind:"agent",id:Z.agentId,agentId:Z.agentId,sessionId:Z.sessionId};try{if(!Z.sessionId)throw Error("tasks requires a Hub session");let X=await h.resolveSessionDefaults(Z.sessionId);if(!X)throw Error("tasks could not resolve the current session");let j=mv(J,X);switch(J.operation){case"create":{let W={type:C$(J.type,"type"),title:C$(J.title,"title"),description:J.description??void 0,instructions:C$(J.instructions,"instructions"),scope:j,workspaceRoot:X.workspaceRoot,cwd:j==="workspace"?(J.cwd??X.cwd)?.trim()||void 0:void 0,resourcePaths:J.resource_paths,priority:J.priority,assignee:J.assignee??void 0,modelSelection:bB(J.model_selection)??X.modelSelection,mode:J.mode??void 0,systemPrompt:J.system_prompt??void 0,maxIterations:J.max_iterations??void 0,timeoutSeconds:J.timeout_seconds??void 0,availableAt:J.available_at,expiresAt:C$(J.expires_at,"expires_at"),automationEligible:J.automation_eligible,createdBy:Y,originSessionId:Z.sessionId,originTaskId:X.originTaskId},V={ok:!0,operation:J.operation,task:await h.manager.createTask(W)};return jj(h,J,Z,!0),V}case"update":{let W=C$(J.task_id,"task_id");if(CB(await h.manager.getTask(W),X),!J.expected_revision)throw Error("expected_revision is required for update");let V={ok:!0,operation:J.operation,task:await h.manager.updateTask({taskId:W,expectedRevision:J.expected_revision,type:J.type,title:J.title,description:J.description,instructions:J.instructions,scope:j,workspaceRoot:X.workspaceRoot??null,cwd:J.cwd,resourcePaths:J.resource_paths,priority:J.priority,assignee:J.assignee,modelSelection:bB(J.model_selection),mode:J.mode,systemPrompt:J.system_prompt,maxIterations:J.max_iterations,timeoutSeconds:J.timeout_seconds,availableAt:J.available_at,expiresAt:J.expires_at,automationEligible:J.automation_eligible,updatedBy:Y})};return jj(h,J,Z,!0),V}case"list":{let W={statuses:J.statuses,types:J.types,scope:j,workspaceRoot:X.workspaceRoot,priorities:J.priorities,automationEligible:J.automation_eligible,limit:J.limit};return{ok:!0,operation:J.operation,tasks:await h.manager.listTasks(W)}}case"get":{let W=await h.manager.getTask(C$(J.task_id,"task_id"));return CB(W,X),{ok:!0,operation:J.operation,task:W}}}}catch(X){return jj(h,J,Z,!1),{ok:!1,operation:J.operation,error:{code:"task_operation_failed",message:X instanceof Error?X.message:String(X)}}}}var c9="tasks",SB='# 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 may include an IANA `timezone`.\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.',uv="# 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 may include an IANA `timezone`.\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.",lv=v7.extend({kind:Z2.literal("todo")}).strict(),IB=b$.extend({kind:Z2.literal("scheduled")}).strict(),xB=Z2.discriminatedUnion("kind",[lv,IB]),dv=Z2.discriminatedUnion("kind",[IB]),vB=["create","update","list","get","pause","resume","delete","run_now"],pv=Z2.object({...b$.shape,...v7.shape,kind:Z2.enum(["todo","scheduled"]),operation:Z2.enum(vB)}).strict(),av=Z2.object({...b$.shape,kind:Z2.enum(["scheduled"]),operation:Z2.enum(vB)}).strict();function Wj(h){let $=h.todo;return gv({name:c9,description:$?'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:cv($?pv:av),retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let J=($?xB:dv).safeParse(Z);if(!J.success)return{ok:!1,kind:typeof Z==="object"&&Z!==null&&"kind"in Z&&(Z.kind==="todo"||Z.kind==="scheduled")?Z.kind:void 0,error:{code:"invalid_tasks_input",message:J.error.issues[0]?.message??"Invalid tasks input"}};if(J.data.kind==="todo"){if(!$)return{ok:!1,kind:"todo",error:{code:"invalid_tasks_input",message:'kind "todo" is not available in this session'}};return{kind:"todo",...await kB($,J.data,Q)}}return{kind:"scheduled",...await eX(h.scheduled,J.data,Q)}}})}function Vj(h){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:($)=>{$.registerRule({id:"hub:task-guidance",content:h?.todoEnabled===!1?uv:SB,whenToolAvailable:c9})}}}import{createSessionId as Jg,isHubProtocolCompatible as Yg,resolveClineBuildEnv as Xg,resolveHubCommandTimeoutMs as jg}from"@cerebriline/shared";var m7="session_not_found";class P$ extends Error{sessionId;code="session_not_found";constructor(h,$){super($??(h?`session not found: ${h}`:"session not found"));this.sessionId=h;this.name="SessionNotFoundError"}}function g7(h){return h instanceof P$||typeof h==="object"&&h!==null&&"code"in h&&h.code==="session_not_found"}import{spawn as Nm}from"node:child_process";import{closeSync as Mm,mkdirSync as Tm,openSync as Rm,readFileSync as Em,unlinkSync as ym}from"node:fs";import{basename as bm,dirname as Cm,join as Pm}from"node:path";import{fileURLToPath as km}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as Sm,isHubDaemonProcess as ZD,resolveClineBuildEnv as QD,withResolvedClineBuildEnv as Im}from"@cerebriline/shared";import{createHash as iv,randomBytes as pB}from"node:crypto";import{existsSync as rv}from"node:fs";import{mkdir as Kj,open as gB,readFile as aB,rename as nv,rm as u7,writeFile as sv}from"node:fs/promises";import{dirname as iB,join as _j}from"node:path";import{isHubProtocolCompatible as ov}from"@cerebriline/shared";import{resolveClineDataDir as u9,resolveClineDir as Hwh}from"@cerebriline/shared/storage";var c7="0.0.82";var Z3={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:c7,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"}},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:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var tv="CLINE_HUB_DISCOVERY_PATH",ev="CLINE_HUB_BUILD_ID",hm="CLINE_HUB_BUILD_EPOCH_MS",$m=30000,Zm=15000,cB=100;function Qm(h){return h.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Jm(h){return iv("sha256").update(h).digest("hex").slice(0,12)}function Ym(h){if(!Number.isInteger(h)||!h||h<=0)return!1;try{return process.kill(h,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function rB(){return pB(32).toString("hex")}function uB(h){return new Promise(($)=>setTimeout($,h))}function Xm(h){return`${h}.lock`}async function jm(h){try{let $=JSON.parse(await aB(_j(h,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function Uj(h){await u7(h,{recursive:!0,force:!0}).catch(()=>{return})}function Q2(){let h=process.env[ev]?.trim();if(h)return h;return"sdk-v1-1a4964394d75a679fd59b69082126225563ccb3cf9ea367c70703c8a61f1f6ea".trim()||`source-${String(Z3.version)}`}function wj(){let h=Number(process.env[hm]);if(Number.isFinite(h)&&h>0)return h;return Number.isFinite(1791572362115)?1791572362115:void 0}function Q3(h,$=Q2()){let Z=ov(h);if(!Z.compatible)return Z;let Q=h.buildId?.trim();if(!Q)return{compatible:!1,reason:"missing_build"};if(Q!==$)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function lB(h){return typeof h==="number"&&Number.isFinite(h)&&h>0?h:void 0}function dB(h){let $=h?.trim().split(/[-+]/,1)[0];if(!$)return;let Z=$.split(".").map((Q)=>Number(Q));if(Z.length===0||Z.some((Q)=>!Number.isInteger(Q)||Q<0))return;return Z}function Wm(h,$){for(let Z=0;Z<Math.max(h.length,$.length);Z++){let Q=h[Z]??0,J=$[Z]??0;if(Q!==J)return Q<J?-1:1}return 0}function l9(h,$){let Z=h.buildId?.trim(),Q=$.buildId?.trim();if(Z&&Q&&Z===Q)return 0;let J=lB(h.buildEpochMs),Y=lB($.buildEpochMs);if(J!==void 0&&Y!==void 0&&J!==Y)return J<Y?-1:1;let X=dB(h.coreVersion),j=dB($.coreVersion);if(X&&j){let W=Wm(X,j);if(W!==0)return W}if(Z&&Q&&Z!==Q)return Z<Q?-1:1;return 0}function d9(){return{buildId:Q2(),buildEpochMs:wj(),coreVersion:String(Z3.version)}}function k$(h,$){let Z=$?.self??d9(),Q=Q3(h,Z.buildId??"");if(Q.compatible)return!0;if(Q.reason!=="build_mismatch"&&Q.reason!=="missing_build")return!1;return l9(Z,h)<=0}function J3(h=process.argv[1]?.trim()||process.cwd()){let $=`hub-${Jm(h)}`,Z=process.env[tv]?.trim()||_j(u9(),"locks","hub","owners",`${Qm($)}.json`);return{ownerId:$,discoveryPath:Z}}function Dwh(h=`hub-${Date.now().toString(36)}`){return J3(h)}async function H0(h){try{let $=JSON.parse(await aB(h,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function l7(h,$,Z){await Fj(h,async()=>{let Q=iB(h);await Kj(Q,{recursive:!0});let J=`${h}.${process.pid}.${pB(6).toString("hex")}.tmp`,Y;try{Y=await gB(J,"wx",384),await Y.writeFile(`${JSON.stringify($,null,2)}
|
|
302
|
+
`,"utf8"),nx()}function UB(){return R0().telemetryOptOut}function $3(h){return new Set(h??R0().disabledTools??[])}function KB(h){return new Set(h??R0().disabledPlugins??[])}function m9(h){return new Set(h??R0().disabledAgentPlugins??[])}function _B(h){return WB.includes(h)}function ex(){return R0().tools??{}}function Zj(h){return ex()[h]?.enabled===!0}function hv(h,$){let Z=R0();h3({...Z,tools:{...Z.tools,[h]:{enabled:$}}})}function wB(h){if(_B(h)){let J=Zj(h);return hv(h,!J),J}let $=R0(),Z=new Set($.disabledTools??[]),Q=Z.has(h);if(Q)Z.delete(h);else Z.add(h);return h3({...$,disabledTools:[...Z]}),!Q}function $v(h,$){let Z=[...new Set(h.map((X)=>X.trim()).filter(Boolean))];if(Z.length===0)return;let Q=R0(),J=$3(Q.disabledTools),Y={...Q.tools};for(let X of Z){if(_B(X)){Y[X]={enabled:!$};continue}if($)J.add(X);else J.delete(X)}h3({...Q,disabledTools:[...J],tools:Y})}function FB(h,$){return $v([h],$),$}function GB(h,$){let Z=h.trim();if(!Z)return;let Q=R0(),J=KB(Q.disabledPlugins);if($)J.add(Z);else J.delete(Z);h3({...Q,disabledPlugins:[...J]})}function HB(h,$){let Z=h.trim();if(!Z)return;let Q=R0(),J=m9(Q.disabledAgentPlugins);if($)J.add(Z);else J.delete(Z);h3({...Q,disabledAgentPlugins:[...J]})}function BB(h,$){let Z=KB($);if(Z.size===0)return[...h];return h.filter((Q)=>!Z.has(Q))}function V4(h,$){let Z=$3($);if(Z.size===0)return[...h];return h.filter((Q)=>!Z.has(Q.name))}function DB(h,$){if(!h||h.length===0)return h;let Z=$3($);if(Z.size===0)return h;return h.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(J,Y)=>Q.setup?.({...J,registerTool:(X)=>{if(!Z.has(X.name))J.registerTool(X)}},Y)}})}import{existsSync as Zv,mkdirSync as Qv,readFileSync as Jv,writeFileSync as Yv}from"node:fs";import{resolve as Xv}from"node:path";import{resolveSessionDataDir as jv}from"@cerebriline/shared/storage";import{nanoid as Wv}from"nanoid";import*as Vv from"node-machine-id";var Uv="machine-id",qB,zB=!1;function LB(){if(!zB)qB=AB(),zB=!0;return qB??fB()}function g9(h){let $=h?.trim();if($)return $;let Z=AB();if(Z)return Z;return fB()}function Kv(){let h=Vv;return h.machineIdSync??h.default?.machineIdSync}function AB(){try{let h=Kv();if(!h)return;return h().trim()||void 0}catch{return}}function fB(){let h=jv(),$=Xv(h,Uv);try{if(Zv($)){let Q=Jv($,"utf8").trim();if(Q.length>0)return Q}}catch{}let Z=`cl-${Wv()}`;try{Qv(h,{recursive:!0}),Yv($,Z,"utf8")}catch{}return Z}class Qj{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(h){this.name=h.name??"OpenTelemetryAdapter",this.metadata={...h.metadata},this.meterProvider=h.meterProvider,this.loggerProvider=h.loggerProvider,this.meter=h.meterProvider?.getMeter("cline")??null,this.logger=h.loggerProvider?.getLogger("cline")??null,this.enabled=h.enabled??!0,this.distinctId=h.distinctId,this.commonProperties=h.commonProperties?{...h.commonProperties}:{}}emit(h,$){if(!this.isEnabled())return;this.emitLog(h,$,!1)}emitRequired(h,$){this.emitLog(h,$,!0)}recordCounter(h,$,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let Y=this.counters.get(h);if(!Y)Y=this.meter.createCounter(h,Q?{description:Q}:void 0),this.counters.set(h,Y);Y.add($,this.flattenProperties(this.buildAttributes(Z)))}recordHistogram(h,$,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let Y=this.histograms.get(h);if(!Y)Y=this.meter.createHistogram(h,Q?{description:Q}:void 0),this.histograms.set(h,Y);Y.record($,this.flattenProperties(this.buildAttributes(Z)))}recordGauge(h,$,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let Y=this.buildAttributes(Z),X=JSON.stringify(Y),j=this.gaugeValues.get(h);if($===null){if(j){if(j.delete(X),j.size===0)this.gaugeValues.delete(h),this.gauges.delete(h)}return}let W=j;if(!W)W=new Map,this.gaugeValues.set(h,W);if(!this.gauges.has(h)){let V=this.meter.createObservableGauge(h,Q?{description:Q}:void 0);V.addCallback((U)=>{for(let K of this.snapshotGaugeSeries(h))U.observe(K.value,this.flattenProperties(K.attributes))}),this.gauges.set(h,V)}W.set(X,{value:$,attributes:Y})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(h){this.distinctId=h}setCommonProperties(h){this.commonProperties={...h}}updateCommonProperties(h){this.commonProperties={...this.commonProperties,...h}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(h,$,Z){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes($,Z));this.logger.emit({severityText:"INFO",body:h,attributes:Q})}buildAttributes(h,$=!1){return{...this.commonProperties,...this.metadata,...h,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(h){let $=this.gaugeValues.get(h);if(!$)return[];return Array.from($.values(),(Z)=>({value:Z.value,attributes:Z.attributes?{...Z.attributes}:void 0}))}flattenProperties(h,$="",Z=new WeakSet,Q=0){if(!h)return{};let J={},Y=100,X=10;for(let[j,W]of Object.entries(h)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let V=$?`${$}.${j}`:j;if(W===null||W===void 0){J[V]=String(W);continue}if(Array.isArray(W)){let U=W.length>Y?W.slice(0,Y):W;try{J[V]=JSON.stringify(U)}catch{J[V]="[UnserializableArray]"}if(W.length>Y)J[`${V}_truncated`]=!0,J[`${V}_original_length`]=W.length;continue}if(typeof W==="object"){if(W instanceof Date){J[V]=W.toISOString();continue}if(W instanceof Error){J[V]=W.message;continue}if(Z.has(W)){J[V]="[Circular]";continue}if(Q>=X){J[V]="[MaxDepthExceeded]";continue}Z.add(W),Object.assign(J,this.flattenProperties(W,V,Z,Q+1));continue}if(_v(W)){J[V]=W;continue}try{J[V]=JSON.stringify(W)}catch{J[V]=String(W)}}return J}}function _v(h){return typeof h==="string"||typeof h==="number"||typeof h==="boolean"}class Jj{name;logger;enabled;constructor(h={}){this.name=h.name??"TelemetryLoggerSink",this.logger=h.logger,this.enabled=h.enabled??!0}emit(h,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:h,properties:$})}emitRequired(h,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:h,properties:$})}recordCounter(h,$,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:h,value:$,attributes:Z,description:Q,required:J===!0})}recordHistogram(h,$,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:h,value:$,attributes:Z,description:Q,required:J===!0})}recordGauge(h,$,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:h,value:$,attributes:Z,description:Q,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class x7{adapters;metadata;distinctId;deviceId;commonProperties;constructor(h={}){if(this.adapters=[...h.adapters??[]],h.logger)this.adapters.push(new Jj({logger:h.logger}));this.metadata={...h.metadata??{}},this.distinctId=h.distinctId,this.deviceId=h.deviceId??LB(),this.commonProperties={...h.commonProperties??{}}}addAdapter(h){this.adapters.push(h)}setDistinctId(h){this.distinctId=h}setMetadata(h){this.metadata={...h}}updateMetadata(h){this.metadata={...this.metadata,...h}}setCommonProperties(h){this.commonProperties={...h}}updateCommonProperties(h){this.commonProperties={...this.commonProperties,...h}}isEnabled(){return this.adapters.some((h)=>h.isEnabled())}capture(h){let $=this.buildAttributes(h.properties);for(let Z of this.adapters)Z.emit(h.event,$)}captureRequired(h,$){let Z=this.buildAttributes($);for(let Q of this.adapters)Q.emitRequired(h,Z)}recordCounter(h,$,Z,Q,J=!1){let Y=this.buildAttributes(Z);for(let X of this.adapters)X.recordCounter(h,$,Y,Q,J)}recordHistogram(h,$,Z,Q,J=!1){let Y=this.buildAttributes(Z);for(let X of this.adapters)X.recordHistogram(h,$,Y,Q,J)}recordGauge(h,$,Z,Q,J=!1){let Y=this.buildAttributes(Z);for(let X of this.adapters)X.recordGauge(h,$,Y,Q,J)}async flush(){await Promise.all(this.adapters.map((h)=>h.flush()))}async dispose(){await Promise.all(this.adapters.map((h)=>h.dispose()))}buildAttributes(h){return{...this.commonProperties,...h,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{},device_id:this.deviceId}}}class NB{distinctId;metadata;commonProperties;constructor(h={}){this.distinctId=h.distinctId,this.metadata={...h.metadata??{}},this.commonProperties={...h.commonProperties??{}}}setDistinctId(h){this.distinctId=h}setMetadata(h){this.metadata={...h}}updateMetadata(h){this.metadata={...this.metadata,...h}}setCommonProperties(h){this.commonProperties={...h}}updateCommonProperties(h){this.commonProperties={...this.commonProperties,...h}}isEnabled(){return!1}capture(h){this.resolveProperties(h.properties)}captureRequired(h,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(h){return{...this.commonProperties,...h,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class MB{meterProvider;loggerProvider;tracerProvider;options;constructor(h={}){this.options=h;let $=qv({[Ev]:h.serviceName??"cline",...h.serviceVersion?{[yv]:h.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)wv.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)Gv.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(h="cline",$){return Fv.getTracer(h,$??this.options.serviceVersion)}createAdapter(h){return new Qj({...h,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(h){let $=this.createAdapter({name:h.name,enabled:this.options.enabled,metadata:h.metadata});return new x7({...h,adapters:[$],distinctId:g9(h.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(h){let $=Yj(this.options.metricsExporter);if($.length===0)return null;let Z=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(Z*0.8)),J=$.map((Y)=>Sv(Y,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Z,timeout:Q})).filter((Y)=>Y!==null);if(J.length===0)return null;return new Ov({resource:h,readers:J})}createTracerProvider(h){let $=Yj(this.options.tracesExporter);if($.length===0)return null;let Z=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let Y of $){let X=kv(Y,{endpoint:Z,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(X)J.push(X)}if(J.length===0)return null;return new Rv({resource:h,spanProcessors:J})}createLoggerProvider(h){let $=Yj(this.options.logsExporter);if($.length===0)return null;let Z=$.map((Q)=>{let J=Pv(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new zv(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(Z.length===0)return null;return new Av({resource:h,processors:Z})}}function bv(h){let $=new MB(h),Z=$.createTelemetryService(h),Q=()=>{Z.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:h.enabled??!0,logsExporter:Array.isArray(h.logsExporter)?h.logsExporter.join(","):h.logsExporter,metricsExporter:Array.isArray(h.metricsExporter)?h.metricsExporter.join(","):h.metricsExporter,tracesExporter:Array.isArray(h.tracesExporter)?h.tracesExporter.join(","):h.tracesExporter,otlpProtocol:h.otlpProtocol,hasOtlpEndpoint:Boolean(h.otlpEndpoint),serviceName:h.serviceName,serviceVersion:h.serviceVersion})};if(!h.deferProviderCreatedEvent)Q();return{provider:$,telemetry:Z,emitProviderCreated:Q}}function TB(h){if(UB())return{telemetry:new NB(h)};if(h.enabled!==!0)return{telemetry:new x7({...h,distinctId:g9(h.distinctId)})};return bv(h)}function Cv(h){let{telemetry:$,provider:Z,emitProviderCreated:Q}=TB(h);return{telemetry:$,provider:Z,flush:async()=>{let X=Z;if(X&&typeof X.forceFlush==="function")try{await X.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),Z?.dispose()])},...h.deferProviderCreatedEvent&&Q?{emitProviderCreated:Q}:{}}}function Yj(h){if(!h)return[];return(Array.isArray(h)?h:h.split(",")).map((Z)=>Z.trim()).filter((Z)=>Z==="console"||Z==="otlp")}function Pv(h,$){if(h==="console")return new Lv;if(!$.endpoint)return null;let Z=Xj($.endpoint,"/v1/logs");return new Hv({url:Z,headers:$.headers})}function kv(h,$){if(h==="console")return new Tv(new Mv);if(!$.endpoint)return null;let Z=Xj($.endpoint,"/v1/traces");return new Nv(new Dv({url:Z,headers:$.headers}))}function Sv(h,$){if(h==="console")return new OB({exporter:new fv,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let Z=Xj($.endpoint,"/v1/metrics");return new OB({exporter:new Bv({url:Z,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function Xj(h,$){let Z=new URL(h),Q=Z.pathname.endsWith("/")?Z.pathname.slice(0,-1):Z.pathname;return Z.pathname=Q.endsWith($)?Q:`${Q}${$}`,Z.toString()}import{createTool as gv,zodToJsonSchema as cv}from"@cerebriline/shared";import{z as Z2}from"zod";import{resolve as RB}from"node:path";import{z as Fh}from"zod";var EB=Fh.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),Iv=Fh.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),yB=Fh.union([Fh.literal(0),Fh.literal(1),Fh.literal(2),Fh.literal(3),Fh.literal(4),Fh.literal(5)]),xv=Fh.object({provider_id:Fh.string().min(1),model_id:Fh.string().min(1).optional()}),v7=Fh.object({operation:Fh.enum(["create","update","list","get"]),task_id:Fh.string().min(1).optional(),expected_revision:Fh.number().int().positive().optional(),type:EB.optional(),title:Fh.string().min(1).optional(),description:Fh.string().nullable().optional(),instructions:Fh.string().min(1).optional(),scope:Fh.enum(["workspace","global"]).optional(),workspace_root:Fh.string().min(1).nullable().optional(),cwd:Fh.string().min(1).nullable().optional(),resource_paths:Fh.array(Fh.string().min(1)).optional(),priority:yB.optional(),assignee:Fh.string().min(1).nullable().optional(),model_selection:xv.nullable().optional(),mode:Fh.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Fh.string().nullable().optional(),max_iterations:Fh.number().int().positive().nullable().optional(),timeout_seconds:Fh.number().int().positive().nullable().optional(),available_at:Fh.string().datetime().optional(),expires_at:Fh.string().datetime().optional(),automation_eligible:Fh.boolean().optional(),statuses:Fh.array(Iv).optional(),types:Fh.array(EB).optional(),priorities:Fh.array(yB).optional(),limit:Fh.number().int().positive().max(500).optional()}),vv=new Set(["create","update"]);function jj(h,$,Z,Q){if(!vv.has($.operation))return;W4(h.telemetry,{ulid:Z.sessionId??Z.conversationId??Z.agentId,tool:`tasks.todo.${$.operation}`,success:Q,agentId:Z.agentId})}function C$(h,$){let Z=h?.trim();if(!Z)throw Error(`${$} is required for this operation`);return Z}function bB(h){if(h===void 0||h===null)return h;return{providerId:h.provider_id,modelId:h.model_id}}function PB(h,$){return RB(h)===RB($)}function CB(h,$){if(!h)throw Error("task does not exist");if($.workspaceRoot){if(h.scope!=="workspace"||!h.workspaceRoot||!PB(h.workspaceRoot,$.workspaceRoot))throw Error("task is outside this session's workspace scope");return}if(h.scope!=="global")throw Error("task is outside this session's global scope")}function mv(h,$){let Z=$.workspaceRoot?"workspace":"global";if(h.scope&&h.scope!==Z)throw Error(`this session can only manage ${Z} tasks`);if(h.workspace_root!==void 0){if(!$.workspaceRoot||h.workspace_root===null||!PB(h.workspace_root,$.workspaceRoot))throw Error(`this session can only manage ${Z} tasks`)}return Z}async function kB(h,$,Z){let Q=v7.safeParse($);if(!Q.success)return{ok:!1,error:{code:"invalid_task_input",message:Q.error.issues[0]?.message??"Invalid task input"}};let J=Q.data,Y={kind:"agent",id:Z.agentId,agentId:Z.agentId,sessionId:Z.sessionId};try{if(!Z.sessionId)throw Error("tasks requires a Hub session");let X=await h.resolveSessionDefaults(Z.sessionId);if(!X)throw Error("tasks could not resolve the current session");let j=mv(J,X);switch(J.operation){case"create":{let W={type:C$(J.type,"type"),title:C$(J.title,"title"),description:J.description??void 0,instructions:C$(J.instructions,"instructions"),scope:j,workspaceRoot:X.workspaceRoot,cwd:j==="workspace"?(J.cwd??X.cwd)?.trim()||void 0:void 0,resourcePaths:J.resource_paths,priority:J.priority,assignee:J.assignee??void 0,modelSelection:bB(J.model_selection)??X.modelSelection,mode:J.mode??void 0,systemPrompt:J.system_prompt??void 0,maxIterations:J.max_iterations??void 0,timeoutSeconds:J.timeout_seconds??void 0,availableAt:J.available_at,expiresAt:C$(J.expires_at,"expires_at"),automationEligible:J.automation_eligible,createdBy:Y,originSessionId:Z.sessionId,originTaskId:X.originTaskId},V={ok:!0,operation:J.operation,task:await h.manager.createTask(W)};return jj(h,J,Z,!0),V}case"update":{let W=C$(J.task_id,"task_id");if(CB(await h.manager.getTask(W),X),!J.expected_revision)throw Error("expected_revision is required for update");let V={ok:!0,operation:J.operation,task:await h.manager.updateTask({taskId:W,expectedRevision:J.expected_revision,type:J.type,title:J.title,description:J.description,instructions:J.instructions,scope:j,workspaceRoot:X.workspaceRoot??null,cwd:J.cwd,resourcePaths:J.resource_paths,priority:J.priority,assignee:J.assignee,modelSelection:bB(J.model_selection),mode:J.mode,systemPrompt:J.system_prompt,maxIterations:J.max_iterations,timeoutSeconds:J.timeout_seconds,availableAt:J.available_at,expiresAt:J.expires_at,automationEligible:J.automation_eligible,updatedBy:Y})};return jj(h,J,Z,!0),V}case"list":{let W={statuses:J.statuses,types:J.types,scope:j,workspaceRoot:X.workspaceRoot,priorities:J.priorities,automationEligible:J.automation_eligible,limit:J.limit};return{ok:!0,operation:J.operation,tasks:await h.manager.listTasks(W)}}case"get":{let W=await h.manager.getTask(C$(J.task_id,"task_id"));return CB(W,X),{ok:!0,operation:J.operation,task:W}}}}catch(X){return jj(h,J,Z,!1),{ok:!1,operation:J.operation,error:{code:"task_operation_failed",message:X instanceof Error?X.message:String(X)}}}}var c9="tasks",SB='# 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 may include an IANA `timezone`.\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.',uv="# 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 may include an IANA `timezone`.\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.",lv=v7.extend({kind:Z2.literal("todo")}).strict(),IB=b$.extend({kind:Z2.literal("scheduled")}).strict(),xB=Z2.discriminatedUnion("kind",[lv,IB]),dv=Z2.discriminatedUnion("kind",[IB]),vB=["create","update","list","get","pause","resume","delete","run_now"],pv=Z2.object({...b$.shape,...v7.shape,kind:Z2.enum(["todo","scheduled"]),operation:Z2.enum(vB)}).strict(),av=Z2.object({...b$.shape,kind:Z2.enum(["scheduled"]),operation:Z2.enum(vB)}).strict();function Wj(h){let $=h.todo;return gv({name:c9,description:$?'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:cv($?pv:av),retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let J=($?xB:dv).safeParse(Z);if(!J.success)return{ok:!1,kind:typeof Z==="object"&&Z!==null&&"kind"in Z&&(Z.kind==="todo"||Z.kind==="scheduled")?Z.kind:void 0,error:{code:"invalid_tasks_input",message:J.error.issues[0]?.message??"Invalid tasks input"}};if(J.data.kind==="todo"){if(!$)return{ok:!1,kind:"todo",error:{code:"invalid_tasks_input",message:'kind "todo" is not available in this session'}};return{kind:"todo",...await kB($,J.data,Q)}}return{kind:"scheduled",...await eX(h.scheduled,J.data,Q)}}})}function Vj(h){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:($)=>{$.registerRule({id:"hub:task-guidance",content:h?.todoEnabled===!1?uv:SB,whenToolAvailable:c9})}}}import{createSessionId as Jg,isHubProtocolCompatible as Yg,resolveClineBuildEnv as Xg,resolveHubCommandTimeoutMs as jg}from"@cerebriline/shared";var m7="session_not_found";class P$ extends Error{sessionId;code="session_not_found";constructor(h,$){super($??(h?`session not found: ${h}`:"session not found"));this.sessionId=h;this.name="SessionNotFoundError"}}function g7(h){return h instanceof P$||typeof h==="object"&&h!==null&&"code"in h&&h.code==="session_not_found"}import{spawn as Nm}from"node:child_process";import{closeSync as Mm,mkdirSync as Tm,openSync as Rm,readFileSync as Em,unlinkSync as ym}from"node:fs";import{basename as bm,dirname as Cm,join as Pm}from"node:path";import{fileURLToPath as km}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as Sm,isHubDaemonProcess as ZD,resolveClineBuildEnv as QD,withResolvedClineBuildEnv as Im}from"@cerebriline/shared";import{createHash as iv,randomBytes as pB}from"node:crypto";import{existsSync as rv}from"node:fs";import{mkdir as Kj,open as gB,readFile as aB,rename as nv,rm as u7,writeFile as sv}from"node:fs/promises";import{dirname as iB,join as _j}from"node:path";import{isHubProtocolCompatible as ov}from"@cerebriline/shared";import{resolveClineDataDir as u9,resolveClineDir as Hwh}from"@cerebriline/shared/storage";var c7="0.0.82";var Z3={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:c7,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"}},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:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var tv="CLINE_HUB_DISCOVERY_PATH",ev="CLINE_HUB_BUILD_ID",hm="CLINE_HUB_BUILD_EPOCH_MS",$m=30000,Zm=15000,cB=100;function Qm(h){return h.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Jm(h){return iv("sha256").update(h).digest("hex").slice(0,12)}function Ym(h){if(!Number.isInteger(h)||!h||h<=0)return!1;try{return process.kill(h,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function rB(){return pB(32).toString("hex")}function uB(h){return new Promise(($)=>setTimeout($,h))}function Xm(h){return`${h}.lock`}async function jm(h){try{let $=JSON.parse(await aB(_j(h,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function Uj(h){await u7(h,{recursive:!0,force:!0}).catch(()=>{return})}function Q2(){let h=process.env[ev]?.trim();if(h)return h;return"sdk-v1-1a4964394d75a679fd59b69082126225563ccb3cf9ea367c70703c8a61f1f6ea".trim()||`source-${String(Z3.version)}`}function wj(){let h=Number(process.env[hm]);if(Number.isFinite(h)&&h>0)return h;return Number.isFinite(1791575034234)?1791575034234:void 0}function Q3(h,$=Q2()){let Z=ov(h);if(!Z.compatible)return Z;let Q=h.buildId?.trim();if(!Q)return{compatible:!1,reason:"missing_build"};if(Q!==$)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function lB(h){return typeof h==="number"&&Number.isFinite(h)&&h>0?h:void 0}function dB(h){let $=h?.trim().split(/[-+]/,1)[0];if(!$)return;let Z=$.split(".").map((Q)=>Number(Q));if(Z.length===0||Z.some((Q)=>!Number.isInteger(Q)||Q<0))return;return Z}function Wm(h,$){for(let Z=0;Z<Math.max(h.length,$.length);Z++){let Q=h[Z]??0,J=$[Z]??0;if(Q!==J)return Q<J?-1:1}return 0}function l9(h,$){let Z=h.buildId?.trim(),Q=$.buildId?.trim();if(Z&&Q&&Z===Q)return 0;let J=lB(h.buildEpochMs),Y=lB($.buildEpochMs);if(J!==void 0&&Y!==void 0&&J!==Y)return J<Y?-1:1;let X=dB(h.coreVersion),j=dB($.coreVersion);if(X&&j){let W=Wm(X,j);if(W!==0)return W}if(Z&&Q&&Z!==Q)return Z<Q?-1:1;return 0}function d9(){return{buildId:Q2(),buildEpochMs:wj(),coreVersion:String(Z3.version)}}function k$(h,$){let Z=$?.self??d9(),Q=Q3(h,Z.buildId??"");if(Q.compatible)return!0;if(Q.reason!=="build_mismatch"&&Q.reason!=="missing_build")return!1;return l9(Z,h)<=0}function J3(h=process.argv[1]?.trim()||process.cwd()){let $=`hub-${Jm(h)}`,Z=process.env[tv]?.trim()||_j(u9(),"locks","hub","owners",`${Qm($)}.json`);return{ownerId:$,discoveryPath:Z}}function Dwh(h=`hub-${Date.now().toString(36)}`){return J3(h)}async function H0(h){try{let $=JSON.parse(await aB(h,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function l7(h,$,Z){await Fj(h,async()=>{let Q=iB(h);await Kj(Q,{recursive:!0});let J=`${h}.${process.pid}.${pB(6).toString("hex")}.tmp`,Y;try{Y=await gB(J,"wx",384),await Y.writeFile(`${JSON.stringify($,null,2)}
|
|
303
303
|
`,{encoding:"utf8"}),await Y.sync(),await Y.close(),Y=void 0,Z?.beforePublish?.(),await nv(J,h);let X;try{X=await gB(Q,"r"),await X.sync()}catch{}finally{await X?.close().catch(()=>{return})}}catch(X){throw await Y?.close().catch(()=>{return}),await u7(J,{force:!0}).catch(()=>{return}),X}})}async function b2(h){await Fj(h,async()=>{await u7(h,{force:!0}).catch(()=>{return})})}async function nB(h,$){return await Fj(h,async()=>{if((await H0(h))?.hubId!==$)return!1;return await u7(h,{force:!0}),!0})}async function sB(h,$,Z){let Q=Xm(h);await Kj(iB(Q),{recursive:!0});let J=Date.now()+Zm;while(!0){try{await Kj(Q,{recursive:!1})}catch(Y){if((Y instanceof Error&&"code"in Y?String(Y.code):"")!=="EEXIST")throw Y;let j=await jm(Q);if(!j){if(Date.now()>=J){await Uj(Q);continue}await uB(cB);continue}let W=Date.now()-Date.parse(j.acquiredAt);if(!Ym(j.pid)||W>$m){await Uj(Q);continue}if(Date.now()>=J)throw Error(`Timed out waiting for hub ${$} lock ${Q}`);await uB(cB);continue}try{return await sv(_j(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
304
304
|
`,"utf8"),await Z()}finally{await Uj(Q)}}}function Fj(h,$){return sB(`${h}.mutation`,"discovery mutation",$)}function d7(h,$){return sB(h,"startup",$)}async function C2(h,$){try{let Z=await fetch($?.authToken?Vm(h):oB(h),{headers:$?.authToken?{authorization:`Bearer ${$.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function P2(h,$,Z="/hub"){return new URL(`ws://${h}:${$}${Z}`).toString()}function oB(h){let $=new URL(h);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function Vm(h){let $=new URL(oB(h));return $.pathname="/status",$.toString()}function qwh(h){return rv(h)}import{CLINE_HUB_DEV_PORT as Um,CLINE_HUB_PORT as Km,resolveClineBuildEnv as _m}from"@cerebriline/shared";var wm="CLINE_HUB_HOST",Fm="CLINE_HUB_PORT",Gm="CLINE_HUB_PATHNAME",Hm="127.0.0.1",Bm=Km,Dm="/hub";function tB(h){return _m(h)==="development"?Um:Bm}function qm(h={}){return(h.env??process.env)[wm]?.trim()||Hm}function p7(h={}){let Z=(h.env??process.env)[Fm]?.trim();if(!Z)return tB(h);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return tB(h);return Q}function zm(h={}){return(h.env??process.env)[Gm]?.trim()||Dm}function Y3(h={},$={}){return{host:h.host??qm($),port:h.port??p7($),pathname:h.pathname??zm($)}}import{join as Lm}from"node:path";var Am="shared:cline",fm="CLINE_HUB_DISCOVERY_PATH",Om="hub-production";function Mwh(h){let $=n4(h.trim());return J3(`workspace:${$||h.trim()}`)}function S1(h=Am){return J3(`${h}@${Q2()}`)}function J2(){return{ownerId:Om,discoveryPath:process.env[fm]?.trim()||Lm(u9(),"locks","hub","production.json")}}var xm=8000,vm=200,eB=3000,mm=100,gm=[100,250,500,1000,2000],cm="--cline-hub-daemon",um=3,lm=60000,Bj=new Map,xwh={resetRetireAttempts(){Bj.clear()}};function dm(h,$=Date.now()){let Z=Bj.get(h);if(!Z||$-Z.windowStartedAt>lm)return Bj.set(h,{count:1,windowStartedAt:$}),!0;return Z.count+=1,Z.count<=um}function pm(h){return[...h.host?["--host",h.host]:[],...typeof h.port==="number"?["--port",String(h.port)]:[],...h.pathname?["--pathname",h.pathname]:[]]}function am(){try{let h=Pm(u9(),"logs","hub-daemon.log");return Tm(Cm(h),{recursive:!0}),{fd:Rm(h,"a"),logPath:h}}catch{return}}function JD(){return QD()==="production"?J2():S1()}function p9(h){return k$(h)}function im(h){try{let $=JSON.parse(Em(`${h}.superseded`,"utf8"));return{url:typeof $.url==="string"?$.url:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0}}catch{return}}function Gj(h){try{ym(`${h}.superseded`)}catch{}}function hD(h,$,Z){if(!$||$.url!==Z)return h;return{...h,authToken:h.authToken??$.authToken,pid:h.pid??$.pid}}async function S$(h,$){try{return await C2(h,{authToken:$})}catch{return}}async function $D(h,$){let Z=Date.now()+$;while(Date.now()<Z){if(!(await S$(h))?.url)return!0;await new Promise((J)=>setTimeout(J,mm))}return!1}async function I$(h,$){if(!dm(h.url))return!1;await X3(h.url,h.authToken,"retired by newer install").catch(()=>!1),await qj(h.url,h.authToken).catch(()=>!1);let Z=await $D(h.url,eB);if(!Z&&h.pid&&rm(h.pid)){try{process.kill(h.pid,"SIGTERM")}catch{}Z=await $D(h.url,eB)}if(Z)await b2($).catch(()=>{return});return Z}function rm(h){try{return process.kill(h,0),!0}catch($){return $?.code==="EPERM"}}async function Dj(h){try{return(await v$(h.url,h.authToken)).activeSessionCount>0}catch{return!1}}async function Hj(h,$){if(p9(h))return"reusable";let Z=await X3(h.url,h.authToken,"retired by newer install").catch(()=>!1);if(await Dj(h)){if(Z)await X3(h.url,h.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let Q=await I$(h,$);if(!Q&&Z)await X3(h.url,h.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return Q?"retired":"failed"}async function nm(h){if(QD()!=="production")return;let $=S1();if($.discoveryPath===h.discoveryPath)return;let Z=await H0($.discoveryPath);if(Z?.url)await I$(Z,$.discoveryPath);else await b2($.discoveryPath).catch(()=>{return})}function sm(){let h=import.meta.url.endsWith(".ts")?"ts":"js";return km(new URL(`./entry.${h}`,import.meta.url))}function om(h,$){let Z=sm(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=bm(Q).toLowerCase().includes("bun"),Y=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),j=Y?[cm]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...j,"--cwd",h,...pm($)],cwd:h,env:{...Im(process.env),CLINE_NO_INTERACTIVE:"1",[Sm]:"1"}}}function tm(h){if(!h||typeof h!=="object")return!1;if(("code"in h?h.code:void 0)==="ETXTBSY")return!0;let Z="message"in h?h.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function em(h,$={}){if(ZD())return;let Z=om(h,$),Q=am();try{Nm(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)Mm(Q.fd)}}async function hg(h,$={}){for(let Z=0;;Z++)try{em(h,$);return}catch(Q){let J=gm[Z];if(!tm(Q)||J===void 0)throw Q;await new Promise((Y)=>setTimeout(Y,J))}}function vwh(h,$={}){if(ZD())return;a9(h,$).catch(()=>{})}async function $g(h,$,Z={}){let Q=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=Y3(Z),Y=P2(J.host,J.port,J.pathname),X=(F)=>{if(!Q)x$(F.url,F.authToken);return F};await nm(h).catch(()=>{return});let j=await H0(h.discoveryPath),W=j?.url?void 0:im(h.discoveryPath),V=!1;if(j?.url){let F=j.authToken;if(!F)V=!0,await I$(j,h.discoveryPath);else{let G=await S$(j.url,F);if(G?.url&&p9(G)&&await G1(G.url,{authToken:F}))return Gj(h.discoveryPath),X({url:G.url,authToken:F});if(G?.url){if(await Hj({...G,authToken:F},h.discoveryPath)==="deferred_busy"&&await G1(G.url,{authToken:F}))return X({url:G.url,authToken:F})}else await b2(h.discoveryPath).catch(()=>{return})}}let U=await S$(Y);if(U?.url){let F=hD(U,j??W,Y);if(p9(U)){let H=[U.authToken,j?.authToken,W?.authToken].filter((D)=>typeof D==="string"&&D.trim().length>0);for(let D of H){if(!await G1(U.url,{authToken:D}))continue;let L={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:D,host:U.host,port:U.port,url:U.url,pid:U.pid??j?.pid??W?.pid,startedAt:U.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await l7(h.discoveryPath,L)}catch{}return Gj(h.discoveryPath),X({url:U.url,authToken:D})}throw Error(`A compatible Cline Hub is already running at ${Y}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${V?" 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 G=await Hj(F,h.discoveryPath);if(G==="deferred_busy"){for(let H of[F.authToken,j?.authToken].filter((B)=>typeof B==="string"&&B.trim().length>0))if(await G1(U.url,{authToken:H}))return X({url:U.url,authToken:H});if(Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An older Cline Hub is running at ${Y} 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(G==="failed"&&Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is already running at ${Y} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let _=Z.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await hg($,_);let w=Date.now()+xm;while(Date.now()<w){let F=await H0(h.discoveryPath);if(F?.url&&F.authToken){let H=await S$(F.url,F.authToken);if(H?.url&&p9(H)&&await G1(H.url,{authToken:F.authToken}))return Gj(h.discoveryPath),X({url:H.url,authToken:F.authToken})}let G=await S$(Y);if(G?.url&&!p9(G)){let H=hD(G,F??W,Y),B=await Hj(H,h.discoveryPath);if(B==="deferred_busy"&&F?.authToken&&await G1(G.url,{authToken:F.authToken}))return X({url:G.url,authToken:F.authToken});if(B==="failed"&&Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is still running at ${Y} 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,vm))}throw Error("Timed out waiting for detached hub startup.")}async function a9(h,$={}){let Z=JD();return await d7(Z.discoveryPath,async()=>$g(Z,h,$))}var Zg=5000,Qg=500;async function mwh(h={}){let $=JD(),Z=h.workspaceRoot??process.cwd(),Q=await H0($.discoveryPath),J=Q?.url?await S$(Q.url,Q.authToken):void 0;if(!J?.url)return{outcome:"started",...await a9(Z)};let Y={...J,authToken:J.authToken??Q?.authToken,pid:J.pid??Q?.pid};if(Q3(J).compatible)return{outcome:"already_current",url:J.url,authToken:Y.authToken};if(l9(d9(),J)<=0)return{outcome:"hub_not_older",url:J.url,authToken:Y.authToken};if(!await X3(Y.url,Y.authToken,h.reason??"hub upgrade requested").catch(()=>!1))throw Error(`The running Cline Hub at ${Y.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 j=async()=>{await X3(Y.url,Y.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},W=Date.now()+(h.waitForIdleMs??Zg),V;for(;;){try{if(V=(await v$(Y.url,Y.authToken)).activeSessionCount,V===0)break}catch{}if(Date.now()>=W)break;await new Promise((_)=>setTimeout(_,Qg))}if(V!==0&&h.force!==!0)return await j(),{outcome:"still_busy",url:Y.url,authToken:Y.authToken,...V!==void 0?{activeSessionCount:V}:{}};if(!await I$(Y,$.discoveryPath))throw await j(),Error(`The running Cline Hub at ${Y.url} could not be stopped. Run 'cline doctor fix' to stop stale hub daemons, then try again.`);return{outcome:"replaced",...await a9(Z),activeSessionCount:V??0}}function Nj(){return Xg()==="production"?J2():S1()}function Wg(){let h=globalThis.WebSocket;if(!h)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return h}function WD(h){if(typeof h==="string")return h;if(h instanceof Uint8Array)return Buffer.from(h).toString();if(h instanceof ArrayBuffer)return Buffer.from(h).toString();if(Array.isArray(h))return Buffer.concat(h.map(($)=>Buffer.from($))).toString();if(h&&typeof h==="object"&&"data"in h&&typeof h.data<"u")return WD(h.data);return String(h)}function Vg(h){if(typeof h==="string")return h;if(h instanceof Uint8Array)return Buffer.from(h).toString("utf8");if(h instanceof ArrayBuffer)return Buffer.from(h).toString("utf8");return""}function YD(h){let $=h,Z=Vg($.reason);return new H1("hub_connection_closed",$.code||Z?`Hub connection closed (code=${$.code??0}${Z?`, reason=${Z}`:""})`:Lj,{closeCode:$.code,closeReason:Z||void 0})}function Ug(h,$){if(h instanceof H1)return h;if(h instanceof Error)return new H1("hub_connect_failed",h.message);if(h&&typeof h==="object"&&"error"in h&&h.error instanceof Error)return new H1("hub_connect_failed",h.error.message);let Z=h&&typeof h==="object"&&"message"in h&&typeof h.message==="string"?h.message.trim():"";if(Z)return new H1("hub_connect_failed",Z);let Q=h&&typeof h==="object"&&"type"in h&&typeof h.type==="string"?h.type.trim():"";return new H1("hub_connect_failed",Q?`Failed to connect to hub at ${$.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var zj="*",XD=8000,Kg="cline-hub-auth.",VD=new Map,UD=new Set,_g=3000,wg=3000,Fg=100,Lj="Hub connection closed",Gg=250,Hg=5000,jD=0.5;class H1 extends Error{code;details;constructor(h,$,Z){super($);this.code=h;this.details=Z;this.name="HubTransportError"}}function Bg(h){return h instanceof H1}class a7 extends Error{command;code;constructor(h,$,Z){super(Z);this.command=h;this.code=$;this.name="HubCommandError"}}function awh(h,$){return h instanceof a7&&h.code==="hub_command_timeout"&&($===void 0||h.command===$)}function Mj(h){let $=h.searchParams.get("authToken")?.trim();if(h.searchParams.delete("authToken"),$)return $;let Z=Tj(h.toString());return Z?VD.get(Z):void 0}function Dg(h){try{let Z=new URL(h).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function Tj(h){if(!Dg(h))return;let $=new URL(i7(h));return $.search="",$.hash="",$.toString()}function Aj(h){let $=Tj(h);return!!$&&UD.has($)}function x$(h,$){let Z=Tj(h);if(Z){if(UD.add(Z),$?.trim())VD.set(Z,$)}return h}class j3{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new H1("hub_connection_closed",Lj);sawSocketClose=!1;registered=!1;capabilities;constructor(h){this.options=h;this.clientId=h.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=h.url,this.capabilities=[...h.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(h){if(this.capabilities=h.map(($)=>({...$})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let h=new URL(this.currentUrl),$=this.options.authToken?.trim()||Mj(h);h.hash="";let Q=new(Wg())(h.toString(),$?[`${Kg}${$}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((Y,X)=>{let j=!1,W=setTimeout(()=>{if(j)return;j=!0,J=!0,this.lastCloseError=new H1("hub_connect_timeout",`Timed out connecting to hub after ${XD}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},XD);Q.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(W),Y()}),Q.addEventListener("error",(V)=>{if(j)return;j=!0,clearTimeout(W),this.lastCloseError=Ug(V,h),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(V)=>{if(j)return;if(j=!0,clearTimeout(W),!J)this.lastCloseError=YD(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(WD(Y)))}),Q.addEventListener("close",(Y)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=YD(Y),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Y of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Y));this.reconnectAttempt=0}subscribe(h,$){let Z=$?.sessionId?.trim()||void 0,Q={listener:h,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command(h,$,Z,Q){let J=0,Y=h!=="client.register"&&h!=="client.unregister";while(!0)try{return await this.commandOnce(h,$,Z,Q)}catch(X){if(!Y||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce(h,$,Z,Q){await this.connect();let J=Jg("hubreq_"),Y=jg(h,Q?.timeoutMs),X=new Promise((W,V)=>{let U=Y===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;V(new a7(h,"hub_command_timeout",`Hub command ${h} timed out after ${Y}ms (hub=${this.currentUrl}, requestId=${J}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Y);this.pendingReplies.set(J,{resolve:(K)=>{if(U)clearTimeout(U);W(K)},reject:(K)=>{if(U)clearTimeout(U);V(K)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:h,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:Y,payload:$}})}catch(W){throw this.pendingReplies.delete(J),W}let j=await X;if(!j.ok){if(j.error?.code===m7){let W=Z??(typeof $?.sessionId==="string"?$.sessionId:void 0);throw new P$(W,j.error.message)}throw new a7(h,j.error?.code,j.error?.message??`Hub command ${h} failed`)}return j}async recoverLocalHubTransport(h){if(!Aj(this.currentUrl)||!Bg(h))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await Oj({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let h=Math.min(Gg*2**this.reconnectAttempt,Hg),$=Math.round(h*(1-jD)+Math.random()*h*jD);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Aj(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let h=await Oj({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(h){this.currentUrl=h,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let h=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!h)return;this.lastCloseError=new H1("hub_connection_closed",Lj),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{h.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(h){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new H1("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(h))}sendSubscriptionFrame(h,$){let Z=h==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId($)):void 0;this.sendFrame({kind:h,clientId:this.clientId,...$?{sessionId:$}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(h,$){let Z=this.subscriptionKeyForSessionId(h),Q=(this.subscriptionCounts.get(Z)??0)+$;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",h);return}if(this.subscriptionCounts.set(Z,Q),$>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",h)}subscriptionKeyForSessionId(h){return h??zj}subscriptionSessionIdFromKey(h){return h===zj?void 0:h}handleFrame(h){switch(h.kind){case"reply":{let $=h.envelope.requestId;if(!$)return;let Z=this.pendingReplies.get($);if(!Z)return;this.pendingReplies.delete($),Z.resolve(h.envelope);return}case"event":{let $=h.envelope.sequence;if(typeof $==="number"){let Z=h.envelope.sessionId?.trim();for(let Q of[zj,Z]){if(!Q||!this.subscriptionCounts.has(Q))continue;let J=this.lastEventSequenceByKey.get(Q)??0;if($>J)this.lastEventSequenceByKey.set(Q,$)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==h.envelope.sessionId?.trim())continue;Z.listener(h.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function i7(h){let $=new URL(h);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function G1(h,$){let Z=new j3({url:h,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function fj(h,$){let Z=i7(h),Q=await C2(Z,{authToken:$?.authToken});if(!Q)return{status:"unreachable",url:Z};if($?.requireCurrentBuild){let J=Q2(),Y=Q3(Q,J);if(!Y.compatible&&!k$(Q))return{status:Y.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!Yg(Q).compatible)return{status:"protocol_mismatch",url:Z};if($?.verifyConnection===!0&&!await G1(Z,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function qg(h){let $=Date.now()+wg;while(Date.now()<$){if(!(await C2(h).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,Fg))}return!1}function zg(h,$){try{return i7(h)===i7($)}catch{return!1}}function KD(h){let $=h&&typeof h==="object"&&Array.isArray(h.sessions)?h.sessions:[],Z=0,Q=new Set;for(let J of $){if(!J||typeof J!=="object")continue;let Y=J.participants;if(!Array.isArray(Y)||Y.length===0)continue;Z+=1;for(let X of Y){let j=X&&typeof X==="object"?X.clientId:void 0;if(typeof j==="string"&&j.trim())Q.add(j)}}return{activeSessionCount:Z,participantClientCount:Q.size}}function iwh(h){return KD(h).activeSessionCount>0}async function v$(h,$,Z){let Q=new j3({url:h,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:_g});return KD(J.payload)}finally{await Q.dispose().catch(()=>{return})}}async function _D(h,$,Z){try{return(await v$(h,$,Z)).activeSessionCount===0}catch{return!1}}async function Lg(h,$){let Z=`${h.discoveryPath}.superseded`,Q=await H0(Z);if(!Q?.url||!Q.authToken)return;let J=await fj(Q.url,{authToken:Q.authToken});if(J.status!=="compatible")return;if(await _D(J.url,Q.authToken,$))return;return x$(J.url,Q.authToken)}async function Ag(h={}){if(h.endpoint?.trim()){let J=await fj(h.endpoint);return J.status==="compatible"?J.url:void 0}let $=Nj(),Z=await H0($.discoveryPath);if(!Z?.url)return await Lg($,h);let Q=await fj(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if(Q.status==="compatible")return x$(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await b2($.discoveryPath).catch(()=>{return});return}async function Oj(h={}){let $=await Ag(h);if($&&await G1($,{workspaceRoot:h.workspaceRoot,cwd:h.cwd}))return $;if(h.endpoint?.trim())return;try{return(await a9(h.workspaceRoot??process.cwd())).url}catch{return}}async function X3(h,$,Z,Q){let J=new URL(h),Y=$?.trim()||Mj(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";if(J.pathname="/drain",J.hash="",Z)J.searchParams.set("reason",Z);if(Q?.off)J.searchParams.set("off","1");return(await fetch(J,{method:"POST",headers:Y?{authorization:`Bearer ${Y}`}:void 0})).ok}async function qj(h,$){let Z=new URL(h),Q=$?.trim()||Mj(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function fg(h=Nj()){let $=await H0(h.discoveryPath);if(!$?.url)return!1;try{if(await qj($.url,$.authToken))return!0}catch{}return!1}async function rwh(h){if(!Aj(h.url))return;let $=Nj(),Z=await H0($.discoveryPath);if(!Z?.url||!zg(Z.url,h.url))return;if(!await _D(Z.url,Z.authToken,{workspaceRoot:h.workspaceRoot,cwd:h.cwd}))return;if(!await fg())return;if(!await qg(Z.url))return;return await b2($.discoveryPath).catch(()=>{return}),await Oj({workspaceRoot:h.workspaceRoot,cwd:h.cwd})}import{resolveClineBuildEnv as Og}from"@cerebriline/shared";function Ng(h,$){if(h instanceof Error)return h;if(h&&typeof h==="object"&&"message"in h&&typeof h.message==="string"&&h.message.trim())return Error(h.message.trim());let Z=h&&typeof h==="object"&&"type"in h&&typeof h.type==="string"?h.type.trim():"";return Error(Z?`Failed to connect to hub at ${$} (${Z} event before socket open).`:`Failed to connect to hub at ${$}.`)}var Mg="cline-hub-auth.";function Tg(h){return h.host!==void 0||h.port!==void 0||h.pathname!==void 0}function Rg(h,$){let Z=new URL(h),Q=new URL($);return Z.search="",Z.hash="",Q.search="",Q.hash="",Z.toString()===Q.toString()}function wD(){return Og()==="production"?J2():S1()}async function Eg(h){let $=h.searchParams.get("authToken")?.trim();if(h.searchParams.delete("authToken"),$)return $;let Z=wD(),Q=await H0(Z.discoveryPath);if(Q?.url&&Rg(h.toString(),Q.url))return Q.authToken;return}async function yg(h={}){let $=Y3(h);if(!Tg(h)){let Z=wD(),Q=await H0(Z.discoveryPath);if(Q?.url)return Q.url}return P2($.host,$.port,$.pathname)}async function FD(h){return await new Promise(($,Z)=>{(async()=>{let Q=new URL(h),J=await Eg(Q);Q.hash="";let Y=new WebSocket(Q.toString(),J?[`${Mg}${J}`]:void 0),X=new Map,j=0;Y.addEventListener("open",()=>{$({send(W){let V=W.requestId??`hub-client-${++j}`;return new Promise((U,K)=>{X.set(V,{resolve:U,reject:K});let _={kind:"command",envelope:{...W,requestId:V}};Y.send(JSON.stringify(_))})},close(){Y.close()}})}),Y.addEventListener("message",(W)=>{let V=JSON.parse(String(W.data));if(V.kind==="reply"&&V.envelope.requestId){let U=X.get(V.envelope.requestId);if(U)X.delete(V.envelope.requestId),U.resolve(V.envelope)}}),Y.addEventListener("close",()=>{for(let W of X.values())W.reject(Error("Hub connection closed"));X.clear()}),Y.addEventListener("error",(W)=>{Z(Ng(W,h))})})().catch(Z)})}async function hFh(h){try{return(await FD(h)).close(),!0}catch{return!1}}async function $Fh(h,$){let Z=await yg(h),Q=await FD(Z);try{return await Q.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{Q.close()}}import{existsSync as bg}from"node:fs";import{isHubDaemonProcess as Cg,resolveClineBuildEnv as Pg}from"@cerebriline/shared";var kg=1e4,Sg="CLINE_HUB_BUILD_WATCH_INTERVAL_MS";function Ig(){let h=Number(process.env[Sg]);return Number.isFinite(h)&&h>0?h:kg}async function xg(h,$){try{let Z=await v$(h.url,$);return{...h,activeSessionCount:Z.activeSessionCount,participantClientCount:Z.participantClientCount}}catch{return h}}function vg(){return Pg()==="production"?J2():S1()}function mg(h){try{return bg(`${h}.lock`)}catch{return!1}}async function gg(){let h=vg();if(mg(h.discoveryPath))return;let $=await H0(h.discoveryPath).catch(()=>{return});if(!$?.url)return;let Z=await C2($.url).catch(()=>{return});if(!Z?.url)return;let Q=Q2(),J=Q3(Z,Q);if(J.compatible)return;let Y=(j)=>({url:Z.url,reason:j,hubBuildId:Z.buildId,hubCoreVersion:Z.coreVersion,expectedBuildId:Q});if(J.reason==="unsupported_protocol")return Y("unsupported_protocol");let X=d9();if(X.coreVersion&&Z.coreVersion&&X.coreVersion===Z.coreVersion)return;if(l9(X,Z)>0)return await xg(Y("outdated_hub"),$.authToken);return Y("build_mismatch")}function WFh(h){if(Cg()||process.env.CLINE_HUB_PORT?.trim())return()=>{};let $=h.intervalMs??Ig(),Z,Q,J=!1,Y=setInterval(()=>{if(J)return;J=!0,gg().then((X)=>{if(!X){Z=void 0,Q=void 0;return}let j=`${X.reason}:${X.hubBuildId??""}`;if(j===Z)return;if(X.reason==="outdated_hub"&&Q!==j){Q=j;return}Q=void 0,Z=j,h.onMismatch(X)}).catch(()=>{return}).finally(()=>{J=!1})},$);return Y.unref?.(),()=>{clearInterval(Y)}}function Rj(h){return h?JSON.parse(JSON.stringify(h)):{}}function r7(h){let $=h?.session&&typeof h.session==="object"?h.session:void 0;if(!$)return;let Z=$.metadata&&typeof $.metadata==="object"?Rj($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,status:typeof $.status==="string"?$.status:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function GD(h,$){return h.error?.message??`hub command failed: ${$}`}function cg(h){let $=Rj(h);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let Z=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...$,error:Z.text.trim()};let Q=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...$,error:Q.message.trim()};return $}function HD(h){let $=h?.sessionId;return typeof $==="string"&&$.trim()?$.trim():void 0}function ug(h){let $=h?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let Z=$;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function lg(h){let $=Rj(h.payload);if(h.event==="schedule.execution_completed")return{sessionId:h.sessionId?.trim()||HD($)||"",eventType:"schedule.execution.completed",payload:$};if(h.event==="schedule.execution_failed")return{sessionId:h.sessionId?.trim()||HD($)||"",eventType:"schedule.execution.failed",payload:$};let Z=h.sessionId?.trim();if(!Z)return;switch(h.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:$};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:$};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:$};case"assistant.media":return{sessionId:Z,eventType:"runtime.chat.media",payload:$};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:$};case"session.notice":return{sessionId:Z,eventType:"runtime.chat.notice",payload:$};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:$};case"tool.updated":return{sessionId:Z,eventType:"runtime.chat.tool_call_update",payload:$};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:$};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:$};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:$};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:cg(h.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:$};default:return}}class dg{options;client;metadataApplied=!1;constructor(h){this.options=h;this.client=new j3({url:h.address,authToken:h.authToken,clientId:h.clientId,clientType:h.clientType??"hub-session-client",displayName:h.displayName??"hub session client",workspaceRoot:h.workspaceRoot,cwd:h.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}async taskCommand(h,$){return await this.ensureMetadataApplied(),(await this.client.command(h,$)).payload??{}}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(h){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:h.workspaceRoot,cwd:h.cwd,sessionConfig:{providerId:h.provider,modelId:h.model,apiKey:h.apiKey,cwd:h.cwd??h.workspaceRoot,workspaceRoot:h.workspaceRoot,systemPrompt:h.systemPrompt??"",mode:h.mode??"act",rules:h.rules,maxIterations:h.maxIterations,timeoutSeconds:h.timeoutSeconds,enableTools:h.enableTools,enableSpawnAgent:h.enableSpawn!==!1,enableAgentTeams:h.enableTeams===!0,disableMcpSettingsTools:h.disableMcpSettingsTools,agentPluginPaths:h.agentPluginPaths,missionLogIntervalSteps:h.missionStepInterval,missionLogIntervalMs:h.missionTimeIntervalMs},metadata:{source:h.source??"cli",provider:h.provider,model:h.model,enableTools:h.enableTools,enableSpawn:h.enableSpawn,enableTeams:h.enableTeams,prompt:void 0,interactive:h.interactive!==!1},runtimeOptions:{mode:h.mode,systemPrompt:h.systemPrompt,maxIterations:h.maxIterations,timeoutSeconds:h.timeoutSeconds,enableTools:h.enableTools,enableSpawn:h.enableSpawn,enableTeams:h.enableTeams,autoApproveTools:h.autoApproveTools,toolExecutors:h.toolExecutors,configExtensions:h.configExtensions},modelSelection:{provider:h.provider,model:h.model,apiKey:h.apiKey},toolPolicies:h.toolPolicies}),Z=r7($.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession(h,$,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:$.prompt,mode:$.config.mode,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},h,Z)).payload?.result}}async stopRuntimeSession(h){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:h},h),{applied:!0}}async abortRuntimeSession(h){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:h},h),{applied:!0}}async updateSession(h){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:h.sessionId,metadata:h.metadata},h.sessionId),{updated:!0}}async getSession(h){await this.ensureMetadataApplied();let $;try{$=await this.client.command("session.get",void 0,h)}catch(Z){if(g7(Z))return;throw Z}return r7($.payload)}async readMessages(h){let $=h.trim();if(!$)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:$},$);if(!Z.ok)throw Error(GD(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async restore(h){let $=h.sessionId.trim();if(!$)throw Error("sessionId is required");let Z=h.restore?.messages!==!1;if(Z&&!h.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=h.config,J=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:h.checkpointRunCount,restore:h.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams===!0,disableMcpSettingsTools:Q.disableMcpSettingsTools,agentPluginPaths:Q.agentPluginPaths,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},$);if(!J.ok)throw Error(GD(J,"session.restore"));let Y=r7(J.payload);if(Z&&!Y?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,j=ug(J.payload);return{sessionId:Y?.sessionId,startResult:Y?.sessionId?{sessionId:Y.sessionId,manifestPath:"",messagesPath:Y.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:j}}async listSessions(h){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:h?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((Q)=>r7({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async searchSessions(h){await this.ensureMetadataApplied();let $=await this.client.command("session.search",h);return Array.isArray($.payload?.hits)?$.payload.hits:[]}async deleteSession(h,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:h,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(h){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:h.approvalId,approved:h.approved,payload:h.reason?{reason:h.reason}:void 0,responderClientId:h.responderClientId})}streamEvents(h,$){let Z=new Set((h.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),Q=this.client.subscribe((J)=>{let Y=lg(J);if(!Y)return;if(Z.size>0&&!Z.has(Y.sessionId))return;$.onEvent?.(Y)});return this.ensureMetadataApplied().catch((J)=>{$.onError?.(J instanceof Error?J:Error(String(J)))}),Q}streamTeamProgress(h,$){let Z=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;$.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{$.onError?.(Q instanceof Error?Q:Error(String(Q)))}),Z}async createSchedule(h){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",h)).payload?.schedule}async listSchedules(h){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(h){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:h})).payload?.schedule}async updateSchedule(h,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:h,...$})).payload?.schedule}async pauseSchedule(h){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:h})).payload?.schedule}async resumeSchedule(h){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:h})).payload?.schedule}async deleteSchedule(h){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:h})).payload?.deleted===!0}async triggerScheduleNow(h){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:h})).payload?.execution}async listScheduleExecutions(h,$){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:h,limit:$});return Array.isArray(Z.payload?.executions)?Z.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let h=await this.client.command("schedule.active");return Array.isArray(h.payload?.executions)?h.payload?.executions:[]}async getUpcomingScheduledRuns(h){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:h});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}async createTask(h){return(await this.taskCommand("task.create",h)).task}async listTasks(h={}){let $=await this.taskCommand("task.list",h);return Array.isArray($.tasks)?$.tasks:[]}async getTask(h){return(await this.taskCommand("task.get",{taskId:h})).task}async updateTask(h){return(await this.taskCommand("task.update",h)).task}async approveTask(h,$){return(await this.taskCommand("task.approve",{taskId:h,expectedRevision:$})).task}async cancelTask(h,$,Z){return(await this.taskCommand("task.cancel",{taskId:h,reason:Z,expectedRevision:$})).task}async runTask(h,$){return await this.taskCommand("task.run",{taskId:h,expectedRevision:$})}async getTaskAutomation(){return(await this.taskCommand("task.automation.get",{})).policy}async setTaskAutomation(h){return(await this.taskCommand("task.automation.set",{policy:h})).policy}}class pg{client;constructor(h){this.client=new j3({url:h.address,authToken:h.authToken,clientId:h.clientId,clientType:h.clientType??"hub-ui-client",displayName:h.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(h){await this.client.command("ui.notify",h)}async sendShowWindow(h){await this.client.command("ui.show_window",h??{})}async listClients(){let h=await this.client.command("client.list");return Array.isArray(h.payload?.clients)?h.payload.clients:[]}async listSessions(h=200){let $=await this.client.command("session.list",{limit:h});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}async searchSessions(h){let $=await this.client.command("session.search",h);return Array.isArray($.payload?.hits)?$.payload.hits:[]}async toggleSetting(h){let $=await this.client.command("settings.toggle",h);if(!$.ok)throw Error($.error?.message??"settings.toggle failed");return $.payload}subscribeUI(h){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":h.onNotify?.($.payload);break;case"ui.show_window":h.onShowWindow?.($.payload);break;case"hub.client.registered":h.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":h.onClientDisconnected?.($.payload??{});break;case"session.created":h.onSessionCreated?.($.payload??{});break;case"session.updated":h.onSessionUpdated?.($.payload??{});break;case"session.detached":h.onSessionDetached?.($.payload??{});break}})}}import{normalizeProviderId as Vjh}from"@cerebriline/llms";import{readdirSync as LXh}from"node:fs";import{readFile as AXh}from"node:fs/promises";import{homedir as fXh}from"node:os";import{isAbsolute as pP,join as W$,resolve as xF}from"node:path";import{releasePolykvSwarmsOf as cP}from"@cerebriline/llms";import{applyPromptTemplateToTools as OXh,captureSdkError as R1,createSessionId as NXh,isLikelyAuthError as MXh,normalizeUserInput as TXh}from"@cerebriline/shared";import{setHomeDirIfUnset as RXh}from"@cerebriline/shared/storage";import{decodeJwtPayload as gc,getClineEnvironmentConfig as vD}from"@cerebriline/shared";import{decodeJwtPayload as tg,getClineEnvironmentConfig as eg}from"@cerebriline/shared";import{createHash as ag}from"node:crypto";var ig;function h1(h){if(typeof h!=="string"||h.length===0)return"unset";return ag("sha256").update(h).digest("hex").slice(0,8)}function ph(h){try{ig?.debug(h)}catch{}}function rg(){let h;return{promise:new Promise((Z)=>{h=Z}),resolve:h}}async function W3(h){let $=await import("node:http"),Z=h.host??"127.0.0.1",Q=h.timeoutMs??300000,J=h.successHtml??ng,Y=rg(),X=!1,j=null,W=null,V=null,U=(w)=>{if(X)return;X=!0,Y.resolve(w)},K=()=>{if(j)clearTimeout(j),j=null;let w=V;if(V=null,W)W.close(),W.closeAllConnections?.(),W=null;if(w!==null&&h.onClose)Promise.resolve(h.onClose({host:Z,port:w})).catch(()=>{})},_=async()=>{return j=setTimeout(()=>{K(),U(null)},Q),Y.promise};for(let w of h.ports){let F=$.createServer((H,B)=>{try{let D=new URL(H.url||"",`http://${Z}:${w}`);if(D.pathname!==h.callbackPath){B.statusCode=404,B.end("Not found");return}let L={url:D,code:D.searchParams.get("code")??void 0,state:D.searchParams.get("state")??void 0,provider:D.searchParams.get("provider")??void 0,error:D.searchParams.get("error")??void 0};if(L.error){B.statusCode=400,B.end(`Authentication failed: ${L.error}`),K(),U(L);return}if(!L.code){B.statusCode=400,B.end("Missing authorization code");return}if(h.expectedState&&L.state!==h.expectedState){B.statusCode=400,B.end("State mismatch");return}B.statusCode=200,B.setHeader("Content-Type","text/html; charset=utf-8"),B.end(J),K(),U(L)}catch{B.statusCode=500,B.end("Internal error")}}),G=await new Promise((H)=>{let B=(D)=>{F.off("error",B),H({bound:!1,error:D})};F.once("error",B),F.listen(w,Z,()=>{F.off("error",B),W=F,H({bound:!0})})});if(G.error){if(G.error.code==="EADDRINUSE")continue;throw K(),G.error}if(G.bound){V=w;let H=`http://${Z}:${w}${h.callbackPath}`;if(h.onListening)await Promise.resolve(h.onListening({host:Z,port:w,callbackUrl:H})).catch(()=>{});return{callbackUrl:H,waitForCallback:_,cancelWait:()=>{K(),U(null)},close:()=>{K(),U(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var ng=`<!DOCTYPE html>
|
|
305
305
|
<html lang="en">
|
package/dist/index.js
CHANGED
|
@@ -4497,7 +4497,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(h){let $=Math.max(1000,Mat
|
|
|
4497
4497
|
`)[0]?.trim())}function $4(h){if(!h)return;let $={...h},Z=$9(typeof $.title==="string"?$.title:void 0);if(Z)$.title=Z;else delete $.title;return Object.keys($).length>0?$:void 0}function jJ(h){let $=$4(h.metadata)??{},Z=h.title!==void 0?$9(h.title):LL(h.prompt);if(Z)$.title=Z;return Object.keys($).length>0?$:void 0}function wL(h){let $=s9(h.metadata),Z={source:h.source,mode:$?.mode??"user",sessionId:h.sessionId,...h.parentSessionId?{parentThreadId:h.parentSessionId}:{},...h.agentId?{subagent:h.agentId}:{},...$?.version?{version:$.version}:{},...$?.trigger?{trigger:$.trigger}:{}};if(h9(h.sessionId))return{agent:"teammate",sessionId:h.sessionId,taskType:"team",origin:Z};if(k8(h.sessionId))return{agent:"subagent",sessionId:h.sessionId,taskType:"subagent_task",origin:Z};return{agent:"lead",sessionId:h.sessionId,origin:Z}}function AL(h){return{version:1,updated_at:h.updatedAt,agent:h.context.agent,sessionId:h.context.sessionId,...h.context.taskType?{taskType:h.context.taskType}:{},origin:h.context.origin,messages:OK(h.messages),...h.systemPrompt?{system_prompt:h.systemPrompt}:{}}}function rv(h,$,Z){BUh(zUh(h),{recursive:!0}),DUh(h,`${JSON.stringify(AL({updatedAt:$,context:Z,messages:[]}),null,2)}
|
|
4498
4498
|
`,"utf8")}function nv(h,$){return I1.parse({version:1,session_id:h.sessionId,source:h.source,pid:h.pid,started_at:h.startedAt,ended_at:$?.endedAt??h.endedAt??void 0,exit_code:$?.exitCode??h.exitCode??void 0,status:$?.status??h.status,interactive:h.interactive,provider:h.provider,model:h.model,cwd:h.cwd,workspace_root:h.workspaceRoot,team_name:h.teamName??void 0,enable_tools:h.enableTools,enable_spawn:h.enableSpawn,enable_teams:h.enableTeams,prompt:h.prompt??void 0,metadata:$?.metadata??h.metadata??void 0,messages_path:h.messagesPath??void 0})}async function sv(h,$,Z){let Q=0;while(!0){let J=await h();if(J===void 0)return{updated:!1};let X=await $(J);if(typeof X==="object"&&X!==null&&"updated"in X&&X.updated===!1){if(Q+=1,Q>=Z)return X;continue}return X}}import{existsSync as OL}from"node:fs";import{readFile as OUh}from"node:fs/promises";import{join as NUh}from"node:path";class WJ{listeners=new Set;subscribe(h,$){let Z={listener:h,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit(h){let $=h.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==$)continue;Z.listener(h)}}get size(){return this.listeners.size}}function ov(h,$,Z){let Q=h?.trim();if(Q&&OL(Q))return Q;let J=Z?.trim();if(J){let X=NUh(J,$,`${$}.messages.json`);if(OL(X))return X}return Q||void 0}async function Z9(h){let $=h?.trim();if(!$||!OL($))return[];try{let Z=(await OUh($,"utf8")).trim();if(!Z)return[];let Q=JSON.parse(Z);if(Array.isArray(Q))return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q.messages;if(Array.isArray(J))return J}return[]}catch{return[]}}function NL(h){return h?{...h}:void 0}async function tv(h,$){if(!(h.hookName==="tool_call"||!!h.parent_agent_id))return;await $.queueSpawnRequest(h);let Q=await $.upsertSubagentSessionFromHook(h);if(!Q)return;await $.appendSubagentHookAudit(Q,h),await $.applySubagentStatus(Q,h)}function VJ(h){if(typeof h!=="string")return;let $=h.trim();return $.length>0?$:void 0}function $2(h){let $=VJ(h);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function MK(h){return typeof h==="number"&&Number.isFinite(h)?h:void 0}function RUh(h){if(!h||typeof h!=="object"||Array.isArray(h))return;return{...h}}function fL(h){let $=h??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function EUh(h){if(h===0)return 0;return Math.min(Math.max(h*2,20),2000)}function PUh(h){return h.isSubagent!==!0&&!VJ(h.parentSessionId)}function bUh(h){let $=h.match(/\d{13,}/g);if(!$||$.length===0)return 0;let Z=0;for(let Q of $){let J=Number.parseInt(Q,10);if(Number.isFinite(J)&&J>Z)Z=J}return Z}function TL(h){let $=h9(h.session_id)?.rootSessionId??k8(h.session_id)?.rootSessionId;return{sessionId:h.session_id,source:h.source,pid:h.pid,startedAt:h.started_at,endedAt:h.ended_at??null,exitCode:h.exit_code??null,status:h.status,interactive:h.interactive,provider:h.provider,model:h.model,cwd:h.cwd,workspaceRoot:h.workspace_root,teamName:h.team_name,enableTools:h.enable_tools,enableSpawn:h.enable_spawn,enableTeams:h.enable_teams,isSubagent:$!==void 0,...$!==void 0?{parentSessionId:$}:{},prompt:h.prompt,metadata:h.metadata,messagesPath:h.messages_path,updatedAt:h.ended_at??h.started_at}}async function yUh(h){let $=fL(h);if($===0)return[];let Z=Zg(),J=(await MUh(Z,{withFileTypes:!0}).catch(()=>[])).filter((Y)=>Y.isDirectory()).map((Y)=>({entry:Y,recency:bUh(Y.name.trim())})).sort((Y,j)=>j.recency-Y.recency||j.entry.name.localeCompare(Y.entry.name));return(await Promise.all(J.map(async({entry:Y})=>{let j=Y.name.trim();if(!j)return;let W=$g(Z,j,`${j}.json`),V=await hg(W,"utf8").catch(()=>{return});if(!V)return;let K;try{K=JSON.parse(V)}catch{return}let U=I1.safeParse(K);if(!U.success)return;return TL(U.data)}))).filter((Y)=>Boolean(Y)).sort((Y,j)=>j.startedAt.localeCompare(Y.startedAt)).slice(0,$)}async function kUh(h,$,Z){let Q=fL($);if(Q===0)return await h.listSessions(0),[];let J=Z.includeSubagents?Q:EUh(Q),X=await h.listSessions(J);return(Z.includeSubagents?X:X.filter(PUh)).slice(0,Q)}function SUh(h){if(typeof h==="string")return h.trim();let $=[];for(let Z of h){if(!Z||typeof Z!=="object")continue;let Q=Z;if(Q.type!=="text")continue;let J=Q.text?.trim();if(J)$.push(J)}return $.join(`
|
|
4499
4499
|
`).trim()}function ev(h){return h.replace(/\s+/g," ").trim()}function IUh(h,$){if(h.length<=$)return h;return`${h.slice(0,Math.max(0,$-3)).trimEnd()}...`}function xUh(h){for(let $ of["user","assistant"])for(let Z of h){if(Z.role!==$)continue;let Q=ev(SUh(Z.content));if(!Q)continue;let J=$==="user"?ev(TUh(Q)):Q,X=CUh(J.split(`
|
|
4500
|
-
`)[0]??J);return IUh(X,50)}return}function vUh(h){let $=0;for(let Z of h)$+=MK(Z.metrics?.cost)??0;return $}function gUh(h){let $,Z;for(let Q=h.length-1;Q>=0;Q-=1){let J=h[Q];if(!$)$=$2(J.modelInfo?.provider);if(!Z)Z=$2(J.modelInfo?.id);if($&&Z)break}return{provider:$,model:Z}}function mUh(h){return $2(h?.provider)??$2(h?.provider&&typeof h.provider==="object"&&!Array.isArray(h.provider)?h.provider.id:void 0)}function cUh(h){return $2(h?.model)??$2(h?.model&&typeof h.model==="object"&&!Array.isArray(h.model)?h.model.id:void 0)}function ML(h,$){let Z=RUh(h.metadata),Q=VJ($?.title)??VJ(Z?.title),J=MK($?.totalCost)??MK(Z?.totalCost),X=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...h,provider:$2($?.provider)??$2(h.provider)??mUh(Z)??"",model:$2($?.model)??$2(h.model)??cUh(Z)??"",metadata:X}}function uUh(h){let $=h.content;if(!Array.isArray($))return!1;return $.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function lUh(h,$){if(h.status!=="running"||h.interactive!==!0)return!1;let Z=$.at(-1);return Z?.role==="assistant"&&!uUh(Z)}async function dUh(h,$){return await Promise.all($.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await h.readSessionMessages(Z.sessionId);return lUh(Z,Q)?{...Z,status:"idle"}:Z}))}async function pUh(h,$){return await Promise.all($.map(async(Z)=>{let Q=ML(Z),J=Boolean(VJ(Q.metadata?.title)),X=Boolean($2(Q.provider)),Y=Boolean($2(Q.model)),j=MK(Q.metadata?.totalCost),W=j!==void 0&&j>0;if(J&&X&&Y&&W)return Q;let V=await h.readSessionMessages(Z.sessionId);if(V.length===0)return Q;let K=gUh(V),U=vUh(V);return ML(Z,{title:J?void 0:xUh(V),provider:X?void 0:K.provider,model:Y?void 0:K.model,totalCost:W||U<=0?void 0:U})}))}async function CL(h,$={}){let Z=fL($.limit),Q=$.includeSubagents===!0,J=await kUh(h,Z,{includeSubagents:Q}),X=$.includeManifestFallback===!0&&J.length<Z?await yUh(Math.min(Math.max(Z*2,100),500)):[],Y=new Map;for(let V of[...J,...X.filter((K)=>Q||!K.isSubagent)]){if(Y.has(V.sessionId))continue;Y.set(V.sessionId,V)}let j=X.length===0?J:Array.from(Y.values()).sort((V,K)=>K.startedAt.localeCompare(V.startedAt)).slice(0,Z),W=await Promise.all((await dUh(h,j)).map(iUh));if($.hydrate===!1)return W.map((V)=>ML(V));return await pUh(h,W)}var aUh="stale_session_reconciler";async function iUh(h){let $=h.metadata;if($?.terminal_marker_source!==aUh)return h;let Z=h.endedAt??void 0;if(Z&&Z===$.terminal_marker_at&&h.messagesPath){let Q=await fUh(h.messagesPath).then((J)=>J.mtime.toISOString()).catch(()=>{return});if(Q&&Q<Z&&Q>=h.startedAt)Z=Q}return Z?{...h,endedAt:Z,updatedAt:Z}:h}async function rUh(h){let $=h.trim();if(!$)return;let Z=$g(Zg(),$,`${$}.json`),Q=await hg(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=I1.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function nUh(h,$={}){let Z=new Map;return await CL({listSessions:async(J)=>{let X=await h.listSessions(J);Z.clear();for(let Y of X)Z.set(Y.sessionId,Y);return X.map(YJ)},readSessionMessages:async(J)=>{let X=Z.get(J)?.messagesPath??await rUh(J);return await Z9(X)}},$)}import{captureSdkError as Tp}from"@cerebriline/shared";import{createSessionId as jHh,isHubProtocolCompatible as WHh,resolveClineBuildEnv as VHh,resolveHubCommandTimeoutMs as KHh}from"@cerebriline/shared";import{spawn as CGh}from"node:child_process";import{closeSync as RGh,mkdirSync as EGh,openSync as PGh,readFileSync as bGh,unlinkSync as yGh}from"node:fs";import{basename as kGh,dirname as SGh,join as IGh}from"node:path";import{fileURLToPath as xGh}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as vGh,isHubDaemonProcess as qg,resolveClineBuildEnv as Lg,withResolvedClineBuildEnv as gGh}from"@cerebriline/shared";import{createHash as sUh,randomBytes as Wg}from"node:crypto";import{existsSync as oUh}from"node:fs";import{mkdir as EL,open as Qg,readFile as Vg,rename as tUh,rm as fK,writeFile as eUh}from"node:fs/promises";import{dirname as Kg,join as PL}from"node:path";import{isHubProtocolCompatible as hGh}from"@cerebriline/shared";import{resolveClineDataDir as KJ,resolveClineDir as Lth}from"@cerebriline/shared/storage";var $Gh="CLINE_HUB_DISCOVERY_PATH",ZGh="CLINE_HUB_BUILD_ID",QGh="CLINE_HUB_BUILD_EPOCH_MS",JGh=30000,XGh=15000,Jg=100;function YGh(h){return h.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function jGh(h){return sUh("sha256").update(h).digest("hex").slice(0,12)}function WGh(h){if(!Number.isInteger(h)||!h||h<=0)return!1;try{return process.kill(h,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function Ug(){return Wg(32).toString("hex")}function Xg(h){return new Promise(($)=>setTimeout($,h))}function VGh(h){return`${h}.lock`}async function KGh(h){try{let $=JSON.parse(await Vg(PL(h,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function RL(h){await fK(h,{recursive:!0,force:!0}).catch(()=>{return})}function B$(){let h=process.env[ZGh]?.trim();if(h)return h;return"sdk-v1-1a4964394d75a679fd59b69082126225563ccb3cf9ea367c70703c8a61f1f6ea".trim()||`source-${String(N6.version)}`}function bL(){let h=Number(process.env[QGh]);if(Number.isFinite(h)&&h>0)return h;return Number.isFinite(
|
|
4500
|
+
`)[0]??J);return IUh(X,50)}return}function vUh(h){let $=0;for(let Z of h)$+=MK(Z.metrics?.cost)??0;return $}function gUh(h){let $,Z;for(let Q=h.length-1;Q>=0;Q-=1){let J=h[Q];if(!$)$=$2(J.modelInfo?.provider);if(!Z)Z=$2(J.modelInfo?.id);if($&&Z)break}return{provider:$,model:Z}}function mUh(h){return $2(h?.provider)??$2(h?.provider&&typeof h.provider==="object"&&!Array.isArray(h.provider)?h.provider.id:void 0)}function cUh(h){return $2(h?.model)??$2(h?.model&&typeof h.model==="object"&&!Array.isArray(h.model)?h.model.id:void 0)}function ML(h,$){let Z=RUh(h.metadata),Q=VJ($?.title)??VJ(Z?.title),J=MK($?.totalCost)??MK(Z?.totalCost),X=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...h,provider:$2($?.provider)??$2(h.provider)??mUh(Z)??"",model:$2($?.model)??$2(h.model)??cUh(Z)??"",metadata:X}}function uUh(h){let $=h.content;if(!Array.isArray($))return!1;return $.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function lUh(h,$){if(h.status!=="running"||h.interactive!==!0)return!1;let Z=$.at(-1);return Z?.role==="assistant"&&!uUh(Z)}async function dUh(h,$){return await Promise.all($.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await h.readSessionMessages(Z.sessionId);return lUh(Z,Q)?{...Z,status:"idle"}:Z}))}async function pUh(h,$){return await Promise.all($.map(async(Z)=>{let Q=ML(Z),J=Boolean(VJ(Q.metadata?.title)),X=Boolean($2(Q.provider)),Y=Boolean($2(Q.model)),j=MK(Q.metadata?.totalCost),W=j!==void 0&&j>0;if(J&&X&&Y&&W)return Q;let V=await h.readSessionMessages(Z.sessionId);if(V.length===0)return Q;let K=gUh(V),U=vUh(V);return ML(Z,{title:J?void 0:xUh(V),provider:X?void 0:K.provider,model:Y?void 0:K.model,totalCost:W||U<=0?void 0:U})}))}async function CL(h,$={}){let Z=fL($.limit),Q=$.includeSubagents===!0,J=await kUh(h,Z,{includeSubagents:Q}),X=$.includeManifestFallback===!0&&J.length<Z?await yUh(Math.min(Math.max(Z*2,100),500)):[],Y=new Map;for(let V of[...J,...X.filter((K)=>Q||!K.isSubagent)]){if(Y.has(V.sessionId))continue;Y.set(V.sessionId,V)}let j=X.length===0?J:Array.from(Y.values()).sort((V,K)=>K.startedAt.localeCompare(V.startedAt)).slice(0,Z),W=await Promise.all((await dUh(h,j)).map(iUh));if($.hydrate===!1)return W.map((V)=>ML(V));return await pUh(h,W)}var aUh="stale_session_reconciler";async function iUh(h){let $=h.metadata;if($?.terminal_marker_source!==aUh)return h;let Z=h.endedAt??void 0;if(Z&&Z===$.terminal_marker_at&&h.messagesPath){let Q=await fUh(h.messagesPath).then((J)=>J.mtime.toISOString()).catch(()=>{return});if(Q&&Q<Z&&Q>=h.startedAt)Z=Q}return Z?{...h,endedAt:Z,updatedAt:Z}:h}async function rUh(h){let $=h.trim();if(!$)return;let Z=$g(Zg(),$,`${$}.json`),Q=await hg(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=I1.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function nUh(h,$={}){let Z=new Map;return await CL({listSessions:async(J)=>{let X=await h.listSessions(J);Z.clear();for(let Y of X)Z.set(Y.sessionId,Y);return X.map(YJ)},readSessionMessages:async(J)=>{let X=Z.get(J)?.messagesPath??await rUh(J);return await Z9(X)}},$)}import{captureSdkError as Tp}from"@cerebriline/shared";import{createSessionId as jHh,isHubProtocolCompatible as WHh,resolveClineBuildEnv as VHh,resolveHubCommandTimeoutMs as KHh}from"@cerebriline/shared";import{spawn as CGh}from"node:child_process";import{closeSync as RGh,mkdirSync as EGh,openSync as PGh,readFileSync as bGh,unlinkSync as yGh}from"node:fs";import{basename as kGh,dirname as SGh,join as IGh}from"node:path";import{fileURLToPath as xGh}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as vGh,isHubDaemonProcess as qg,resolveClineBuildEnv as Lg,withResolvedClineBuildEnv as gGh}from"@cerebriline/shared";import{createHash as sUh,randomBytes as Wg}from"node:crypto";import{existsSync as oUh}from"node:fs";import{mkdir as EL,open as Qg,readFile as Vg,rename as tUh,rm as fK,writeFile as eUh}from"node:fs/promises";import{dirname as Kg,join as PL}from"node:path";import{isHubProtocolCompatible as hGh}from"@cerebriline/shared";import{resolveClineDataDir as KJ,resolveClineDir as Lth}from"@cerebriline/shared/storage";var $Gh="CLINE_HUB_DISCOVERY_PATH",ZGh="CLINE_HUB_BUILD_ID",QGh="CLINE_HUB_BUILD_EPOCH_MS",JGh=30000,XGh=15000,Jg=100;function YGh(h){return h.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function jGh(h){return sUh("sha256").update(h).digest("hex").slice(0,12)}function WGh(h){if(!Number.isInteger(h)||!h||h<=0)return!1;try{return process.kill(h,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function Ug(){return Wg(32).toString("hex")}function Xg(h){return new Promise(($)=>setTimeout($,h))}function VGh(h){return`${h}.lock`}async function KGh(h){try{let $=JSON.parse(await Vg(PL(h,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function RL(h){await fK(h,{recursive:!0,force:!0}).catch(()=>{return})}function B$(){let h=process.env[ZGh]?.trim();if(h)return h;return"sdk-v1-1a4964394d75a679fd59b69082126225563ccb3cf9ea367c70703c8a61f1f6ea".trim()||`source-${String(N6.version)}`}function bL(){let h=Number(process.env[QGh]);if(Number.isFinite(h)&&h>0)return h;return Number.isFinite(1791575034234)?1791575034234:void 0}function Q9(h,$=B$()){let Z=hGh(h);if(!Z.compatible)return Z;let Q=h.buildId?.trim();if(!Q)return{compatible:!1,reason:"missing_build"};if(Q!==$)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function Yg(h){return typeof h==="number"&&Number.isFinite(h)&&h>0?h:void 0}function jg(h){let $=h?.trim().split(/[-+]/,1)[0];if(!$)return;let Z=$.split(".").map((Q)=>Number(Q));if(Z.length===0||Z.some((Q)=>!Number.isInteger(Q)||Q<0))return;return Z}function UGh(h,$){for(let Z=0;Z<Math.max(h.length,$.length);Z++){let Q=h[Z]??0,J=$[Z]??0;if(Q!==J)return Q<J?-1:1}return 0}function UJ(h,$){let Z=h.buildId?.trim(),Q=$.buildId?.trim();if(Z&&Q&&Z===Q)return 0;let J=Yg(h.buildEpochMs),X=Yg($.buildEpochMs);if(J!==void 0&&X!==void 0&&J!==X)return J<X?-1:1;let Y=jg(h.coreVersion),j=jg($.coreVersion);if(Y&&j){let W=UGh(Y,j);if(W!==0)return W}if(Z&&Q&&Z!==Q)return Z<Q?-1:1;return 0}function GJ(){return{buildId:B$(),buildEpochMs:bL(),coreVersion:String(N6.version)}}function S8(h,$){let Z=$?.self??GJ(),Q=Q9(h,Z.buildId??"");if(Q.compatible)return!0;if(Q.reason!=="build_mismatch"&&Q.reason!=="missing_build")return!1;return UJ(Z,h)<=0}function J9(h=process.argv[1]?.trim()||process.cwd()){let $=`hub-${jGh(h)}`,Z=process.env[$Gh]?.trim()||PL(KJ(),"locks","hub","owners",`${YGh($)}.json`);return{ownerId:$,discoveryPath:Z}}function Ath(h=`hub-${Date.now().toString(36)}`){return J9(h)}async function g0(h){try{let $=JSON.parse(await Vg(h,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function TK(h,$,Z){await yL(h,async()=>{let Q=Kg(h);await EL(Q,{recursive:!0});let J=`${h}.${process.pid}.${Wg(6).toString("hex")}.tmp`,X;try{X=await Qg(J,"wx",384),await X.writeFile(`${JSON.stringify($,null,2)}
|
|
4501
4501
|
`,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,Z?.beforePublish?.(),await tUh(J,h);let Y;try{Y=await Qg(Q,"r"),await Y.sync()}catch{}finally{await Y?.close().catch(()=>{return})}}catch(Y){throw await X?.close().catch(()=>{return}),await fK(J,{force:!0}).catch(()=>{return}),Y}})}async function Z4(h){await yL(h,async()=>{await fK(h,{force:!0}).catch(()=>{return})})}async function Gg(h,$){return await yL(h,async()=>{if((await g0(h))?.hubId!==$)return!1;return await fK(h,{force:!0}),!0})}async function Hg(h,$,Z){let Q=VGh(h);await EL(Kg(Q),{recursive:!0});let J=Date.now()+XGh;while(!0){try{await EL(Q,{recursive:!1})}catch(X){if((X instanceof Error&&"code"in X?String(X.code):"")!=="EEXIST")throw X;let j=await KGh(Q);if(!j){if(Date.now()>=J){await RL(Q);continue}await Xg(Jg);continue}let W=Date.now()-Date.parse(j.acquiredAt);if(!WGh(j.pid)||W>JGh){await RL(Q);continue}if(Date.now()>=J)throw Error(`Timed out waiting for hub ${$} lock ${Q}`);await Xg(Jg);continue}try{return await eUh(PL(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
4502
4502
|
`,"utf8"),await Z()}finally{await RL(Q)}}}function yL(h,$){return Hg(`${h}.mutation`,"discovery mutation",$)}function CK(h,$){return Hg(h,"startup",$)}async function Q4(h,$){try{let Z=await fetch($?.authToken?GGh(h):Fg(h),{headers:$?.authToken?{authorization:`Bearer ${$.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function J4(h,$,Z="/hub"){return new URL(`ws://${h}:${$}${Z}`).toString()}function Fg(h){let $=new URL(h);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function GGh(h){let $=new URL(Fg(h));return $.pathname="/status",$.toString()}function Oth(h){return oUh(h)}import{CLINE_HUB_DEV_PORT as HGh,CLINE_HUB_PORT as FGh,resolveClineBuildEnv as _Gh}from"@cerebriline/shared";var BGh="CLINE_HUB_HOST",DGh="CLINE_HUB_PORT",zGh="CLINE_HUB_PATHNAME",qGh="127.0.0.1",LGh=FGh,wGh="/hub";function _g(h){return _Gh(h)==="development"?HGh:LGh}function AGh(h={}){return(h.env??process.env)[BGh]?.trim()||qGh}function RK(h={}){let Z=(h.env??process.env)[DGh]?.trim();if(!Z)return _g(h);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return _g(h);return Q}function OGh(h={}){return(h.env??process.env)[zGh]?.trim()||wGh}function X9(h={},$={}){return{host:h.host??AGh($),port:h.port??RK($),pathname:h.pathname??OGh($)}}import{join as NGh}from"node:path";var MGh="shared:cline",fGh="CLINE_HUB_DISCOVERY_PATH",TGh="hub-production";function Eth(h){let $=W3(h.trim());return J9(`workspace:${$||h.trim()}`)}function b2(h=MGh){return J9(`${h}@${B$()}`)}function D$(){return{ownerId:TGh,discoveryPath:process.env[fGh]?.trim()||NGh(KJ(),"locks","hub","production.json")}}var mGh=8000,cGh=200,Bg=3000,uGh=100,lGh=[100,250,500,1000,2000],dGh="--cline-hub-daemon",pGh=3,aGh=60000,IL=new Map,cth={resetRetireAttempts(){IL.clear()}};function iGh(h,$=Date.now()){let Z=IL.get(h);if(!Z||$-Z.windowStartedAt>aGh)return IL.set(h,{count:1,windowStartedAt:$}),!0;return Z.count+=1,Z.count<=pGh}function rGh(h){return[...h.host?["--host",h.host]:[],...typeof h.port==="number"?["--port",String(h.port)]:[],...h.pathname?["--pathname",h.pathname]:[]]}function nGh(){try{let h=IGh(KJ(),"logs","hub-daemon.log");return EGh(SGh(h),{recursive:!0}),{fd:PGh(h,"a"),logPath:h}}catch{return}}function wg(){return Lg()==="production"?D$():b2()}function HJ(h){return S8(h)}function sGh(h){try{let $=JSON.parse(bGh(`${h}.superseded`,"utf8"));return{url:typeof $.url==="string"?$.url:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0}}catch{return}}function kL(h){try{yGh(`${h}.superseded`)}catch{}}function Dg(h,$,Z){if(!$||$.url!==Z)return h;return{...h,authToken:h.authToken??$.authToken,pid:h.pid??$.pid}}async function I8(h,$){try{return await Q4(h,{authToken:$})}catch{return}}async function zg(h,$){let Z=Date.now()+$;while(Date.now()<Z){if(!(await I8(h))?.url)return!0;await new Promise((J)=>setTimeout(J,uGh))}return!1}async function x8(h,$){if(!iGh(h.url))return!1;await Y9(h.url,h.authToken,"retired by newer install").catch(()=>!1),await vL(h.url,h.authToken).catch(()=>!1);let Z=await zg(h.url,Bg);if(!Z&&h.pid&&oGh(h.pid)){try{process.kill(h.pid,"SIGTERM")}catch{}Z=await zg(h.url,Bg)}if(Z)await Z4($).catch(()=>{return});return Z}function oGh(h){try{return process.kill(h,0),!0}catch($){return $?.code==="EPERM"}}async function xL(h){try{return(await g8(h.url,h.authToken)).activeSessionCount>0}catch{return!1}}async function SL(h,$){if(HJ(h))return"reusable";let Z=await Y9(h.url,h.authToken,"retired by newer install").catch(()=>!1);if(await xL(h)){if(Z)await Y9(h.url,h.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let Q=await x8(h,$);if(!Q&&Z)await Y9(h.url,h.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return Q?"retired":"failed"}async function tGh(h){if(Lg()!=="production")return;let $=b2();if($.discoveryPath===h.discoveryPath)return;let Z=await g0($.discoveryPath);if(Z?.url)await x8(Z,$.discoveryPath);else await Z4($.discoveryPath).catch(()=>{return})}function eGh(){let h=import.meta.url.endsWith(".ts")?"ts":"js";return xGh(new URL(`./entry.${h}`,import.meta.url))}function hHh(h,$){let Z=eGh(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=kGh(Q).toLowerCase().includes("bun"),X=Z.startsWith("/$bunfs/"),Y=J&&Z.toLowerCase().endsWith(".ts"),j=X?[dGh]:[...Y?["--conditions=development"]:[],Z];return{launcher:Q,args:[...j,"--cwd",h,...rGh($)],cwd:h,env:{...gGh(process.env),CLINE_NO_INTERACTIVE:"1",[vGh]:"1"}}}function $Hh(h){if(!h||typeof h!=="object")return!1;if(("code"in h?h.code:void 0)==="ETXTBSY")return!0;let Z="message"in h?h.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function ZHh(h,$={}){if(qg())return;let Z=hHh(h,$),Q=nGh();try{CGh(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)RGh(Q.fd)}}async function QHh(h,$={}){for(let Z=0;;Z++)try{ZHh(h,$);return}catch(Q){let J=lGh[Z];if(!$Hh(Q)||J===void 0)throw Q;await new Promise((X)=>setTimeout(X,J))}}function Ag(h,$={}){if(qg())return;FJ(h,$).catch(()=>{})}async function JHh(h,$,Z={}){let Q=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=X9(Z),X=J4(J.host,J.port,J.pathname),Y=(F)=>{if(!Q)v8(F.url,F.authToken);return F};await tGh(h).catch(()=>{return});let j=await g0(h.discoveryPath),W=j?.url?void 0:sGh(h.discoveryPath),V=!1;if(j?.url){let F=j.authToken;if(!F)V=!0,await x8(j,h.discoveryPath);else{let _=await I8(j.url,F);if(_?.url&&HJ(_)&&await Z2(_.url,{authToken:F}))return kL(h.discoveryPath),Y({url:_.url,authToken:F});if(_?.url){if(await SL({..._,authToken:F},h.discoveryPath)==="deferred_busy"&&await Z2(_.url,{authToken:F}))return Y({url:_.url,authToken:F})}else await Z4(h.discoveryPath).catch(()=>{return})}}let K=await I8(X);if(K?.url){let F=Dg(K,j??W,X);if(HJ(K)){let B=[K.authToken,j?.authToken,W?.authToken].filter((z)=>typeof z==="string"&&z.trim().length>0);for(let z of B){if(!await Z2(K.url,{authToken:z}))continue;let L={hubId:K.hubId??`repaired-${K.port}`,protocolVersion:K.protocolVersion,minClientProtocolVersion:K.minClientProtocolVersion,maxClientProtocolVersion:K.maxClientProtocolVersion,capabilities:K.capabilities,coreVersion:K.coreVersion,buildId:K.buildId,authToken:z,host:K.host,port:K.port,url:K.url,pid:K.pid??j?.pid??W?.pid,startedAt:K.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await TK(h.discoveryPath,L)}catch{}return kL(h.discoveryPath),Y({url:K.url,authToken:z})}throw Error(`A compatible Cline Hub is already running at ${X}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${V?" 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 _=await SL(F,h.discoveryPath);if(_==="deferred_busy"){for(let B of[F.authToken,j?.authToken].filter((D)=>typeof D==="string"&&D.trim().length>0))if(await Z2(K.url,{authToken:B}))return Y({url:K.url,authToken:B});if(Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An older Cline Hub is running at ${X} 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(_==="failed"&&Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is already running at ${X} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=Z.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await QHh($,G);let H=Date.now()+mGh;while(Date.now()<H){let F=await g0(h.discoveryPath);if(F?.url&&F.authToken){let B=await I8(F.url,F.authToken);if(B?.url&&HJ(B)&&await Z2(B.url,{authToken:F.authToken}))return kL(h.discoveryPath),Y({url:B.url,authToken:F.authToken})}let _=await I8(X);if(_?.url&&!HJ(_)){let B=Dg(_,F??W,X),D=await SL(B,h.discoveryPath);if(D==="deferred_busy"&&F?.authToken&&await Z2(_.url,{authToken:F.authToken}))return Y({url:_.url,authToken:F.authToken});if(D==="failed"&&Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is still running at ${X} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((B)=>setTimeout(B,cGh))}throw Error("Timed out waiting for detached hub startup.")}async function FJ(h,$={}){let Z=wg();return await CK(Z.discoveryPath,async()=>JHh(Z,h,$))}var XHh=5000,YHh=500;async function uth(h={}){let $=wg(),Z=h.workspaceRoot??process.cwd(),Q=await g0($.discoveryPath),J=Q?.url?await I8(Q.url,Q.authToken):void 0;if(!J?.url)return{outcome:"started",...await FJ(Z)};let X={...J,authToken:J.authToken??Q?.authToken,pid:J.pid??Q?.pid};if(Q9(J).compatible)return{outcome:"already_current",url:J.url,authToken:X.authToken};if(UJ(GJ(),J)<=0)return{outcome:"hub_not_older",url:J.url,authToken:X.authToken};if(!await Y9(X.url,X.authToken,h.reason??"hub upgrade requested").catch(()=>!1))throw Error(`The running Cline Hub at ${X.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 j=async()=>{await Y9(X.url,X.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},W=Date.now()+(h.waitForIdleMs??XHh),V;for(;;){try{if(V=(await g8(X.url,X.authToken)).activeSessionCount,V===0)break}catch{}if(Date.now()>=W)break;await new Promise((G)=>setTimeout(G,YHh))}if(V!==0&&h.force!==!0)return await j(),{outcome:"still_busy",url:X.url,authToken:X.authToken,...V!==void 0?{activeSessionCount:V}:{}};if(!await x8(X,$.discoveryPath))throw await j(),Error(`The running Cline Hub at ${X.url} could not be stopped. Run 'cline doctor fix' to stop stale hub daemons, then try again.`);return{outcome:"replaced",...await FJ(Z),activeSessionCount:V??0}}function lL(){return VHh()==="production"?D$():b2()}function UHh(){let h=globalThis.WebSocket;if(!h)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return h}function fg(h){if(typeof h==="string")return h;if(h instanceof Uint8Array)return Buffer.from(h).toString();if(h instanceof ArrayBuffer)return Buffer.from(h).toString();if(Array.isArray(h))return Buffer.concat(h.map(($)=>Buffer.from($))).toString();if(h&&typeof h==="object"&&"data"in h&&typeof h.data<"u")return fg(h.data);return String(h)}function GHh(h){if(typeof h==="string")return h;if(h instanceof Uint8Array)return Buffer.from(h).toString("utf8");if(h instanceof ArrayBuffer)return Buffer.from(h).toString("utf8");return""}function Og(h){let $=h,Z=GHh($.reason);return new Q2("hub_connection_closed",$.code||Z?`Hub connection closed (code=${$.code??0}${Z?`, reason=${Z}`:""})`:mL,{closeCode:$.code,closeReason:Z||void 0})}function HHh(h,$){if(h instanceof Q2)return h;if(h instanceof Error)return new Q2("hub_connect_failed",h.message);if(h&&typeof h==="object"&&"error"in h&&h.error instanceof Error)return new Q2("hub_connect_failed",h.error.message);let Z=h&&typeof h==="object"&&"message"in h&&typeof h.message==="string"?h.message.trim():"";if(Z)return new Q2("hub_connect_failed",Z);let Q=h&&typeof h==="object"&&"type"in h&&typeof h.type==="string"?h.type.trim():"";return new Q2("hub_connect_failed",Q?`Failed to connect to hub at ${$.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var gL="*",Ng=8000,FHh="cline-hub-auth.",Tg=new Map,Cg=new Set,_Hh=3000,BHh=3000,DHh=100,mL="Hub connection closed",zHh=250,qHh=5000,Mg=0.5;class Q2 extends Error{code;details;constructor(h,$,Z){super($);this.code=h;this.details=Z;this.name="HubTransportError"}}function LHh(h){return h instanceof Q2}class EK extends Error{command;code;constructor(h,$,Z){super(Z);this.command=h;this.code=$;this.name="HubCommandError"}}function Rg(h,$){return h instanceof EK&&h.code==="hub_command_timeout"&&($===void 0||h.command===$)}function dL(h){let $=h.searchParams.get("authToken")?.trim();if(h.searchParams.delete("authToken"),$)return $;let Z=pL(h.toString());return Z?Tg.get(Z):void 0}function wHh(h){try{let Z=new URL(h).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function pL(h){if(!wHh(h))return;let $=new URL(m8(h));return $.search="",$.hash="",$.toString()}function cL(h){let $=pL(h);return!!$&&Cg.has($)}function v8(h,$){let Z=pL(h);if(Z){if(Cg.add(Z),$?.trim())Tg.set(Z,$)}return h}class X4{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new Q2("hub_connection_closed",mL);sawSocketClose=!1;registered=!1;capabilities;constructor(h){this.options=h;this.clientId=h.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=h.url,this.capabilities=[...h.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(h){if(this.capabilities=h.map(($)=>({...$})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let h=new URL(this.currentUrl),$=this.options.authToken?.trim()||dL(h);h.hash="";let Q=new(UHh())(h.toString(),$?[`${FHh}${$}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((X,Y)=>{let j=!1,W=setTimeout(()=>{if(j)return;j=!0,J=!0,this.lastCloseError=new Q2("hub_connect_timeout",`Timed out connecting to hub after ${Ng}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}Y(this.lastCloseError)},Ng);Q.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(W),X()}),Q.addEventListener("error",(V)=>{if(j)return;j=!0,clearTimeout(W),this.lastCloseError=HHh(V,h),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Y(this.lastCloseError)}),Q.addEventListener("close",(V)=>{if(j)return;if(j=!0,clearTimeout(W),!J)this.lastCloseError=Og(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Y(this.lastCloseError)})}),Q.addEventListener("message",(X)=>{this.handleFrame(JSON.parse(fg(X)))}),Q.addEventListener("close",(X)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=Og(X),this.sawSocketClose=!0;this.registered=!1;for(let Y of this.pendingReplies.values())Y.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let X of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(X));this.reconnectAttempt=0}subscribe(h,$){let Z=$?.sessionId?.trim()||void 0,Q={listener:h,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command(h,$,Z,Q){let J=0,X=h!=="client.register"&&h!=="client.unregister";while(!0)try{return await this.commandOnce(h,$,Z,Q)}catch(Y){if(!X||J>=1||!await this.recoverLocalHubTransport(Y))throw Y;J+=1}}async commandOnce(h,$,Z,Q){await this.connect();let J=jHh("hubreq_"),X=KHh(h,Q?.timeoutMs),Y=new Promise((W,V)=>{let K=X===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;V(new EK(h,"hub_command_timeout",`Hub command ${h} timed out after ${X}ms (hub=${this.currentUrl}, requestId=${J}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},X);this.pendingReplies.set(J,{resolve:(U)=>{if(K)clearTimeout(K);W(U)},reject:(U)=>{if(K)clearTimeout(K);V(U)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:h,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:X,payload:$}})}catch(W){throw this.pendingReplies.delete(J),W}let j=await Y;if(!j.ok){if(j.error?.code===nQ){let W=Z??(typeof $?.sessionId==="string"?$.sessionId:void 0);throw new o6(W,j.error.message)}throw new EK(h,j.error?.code,j.error?.message??`Hub command ${h} failed`)}return j}async recoverLocalHubTransport(h){if(!cL(this.currentUrl)||!LHh(h))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await _J({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let h=Math.min(zHh*2**this.reconnectAttempt,qHh),$=Math.round(h*(1-Mg)+Math.random()*h*Mg);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!cL(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let h=await _J({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(h){this.currentUrl=h,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let h=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!h)return;this.lastCloseError=new Q2("hub_connection_closed",mL),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{h.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(h){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new Q2("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(h))}sendSubscriptionFrame(h,$){let Z=h==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId($)):void 0;this.sendFrame({kind:h,clientId:this.clientId,...$?{sessionId:$}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(h,$){let Z=this.subscriptionKeyForSessionId(h),Q=(this.subscriptionCounts.get(Z)??0)+$;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",h);return}if(this.subscriptionCounts.set(Z,Q),$>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",h)}subscriptionKeyForSessionId(h){return h??gL}subscriptionSessionIdFromKey(h){return h===gL?void 0:h}handleFrame(h){switch(h.kind){case"reply":{let $=h.envelope.requestId;if(!$)return;let Z=this.pendingReplies.get($);if(!Z)return;this.pendingReplies.delete($),Z.resolve(h.envelope);return}case"event":{let $=h.envelope.sequence;if(typeof $==="number"){let Z=h.envelope.sessionId?.trim();for(let Q of[gL,Z]){if(!Q||!this.subscriptionCounts.has(Q))continue;let J=this.lastEventSequenceByKey.get(Q)??0;if($>J)this.lastEventSequenceByKey.set(Q,$)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==h.envelope.sessionId?.trim())continue;Z.listener(h.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function m8(h){let $=new URL(h);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function Z2(h,$){let Z=new X4({url:h,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function uL(h,$){let Z=m8(h),Q=await Q4(Z,{authToken:$?.authToken});if(!Q)return{status:"unreachable",url:Z};if($?.requireCurrentBuild){let J=B$(),X=Q9(Q,J);if(!X.compatible&&!S8(Q))return{status:X.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!WHh(Q).compatible)return{status:"protocol_mismatch",url:Z};if($?.verifyConnection===!0&&!await Z2(Z,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function AHh(h){let $=Date.now()+BHh;while(Date.now()<$){if(!(await Q4(h).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,DHh))}return!1}function OHh(h,$){try{return m8(h)===m8($)}catch{return!1}}function Eg(h){let $=h&&typeof h==="object"&&Array.isArray(h.sessions)?h.sessions:[],Z=0,Q=new Set;for(let J of $){if(!J||typeof J!=="object")continue;let X=J.participants;if(!Array.isArray(X)||X.length===0)continue;Z+=1;for(let Y of X){let j=Y&&typeof Y==="object"?Y.clientId:void 0;if(typeof j==="string"&&j.trim())Q.add(j)}}return{activeSessionCount:Z,participantClientCount:Q.size}}function nth(h){return Eg(h).activeSessionCount>0}async function g8(h,$,Z){let Q=new X4({url:h,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:_Hh});return Eg(J.payload)}finally{await Q.dispose().catch(()=>{return})}}async function Pg(h,$,Z){try{return(await g8(h,$,Z)).activeSessionCount===0}catch{return!1}}async function NHh(h,$){let Z=`${h.discoveryPath}.superseded`,Q=await g0(Z);if(!Q?.url||!Q.authToken)return;let J=await uL(Q.url,{authToken:Q.authToken});if(J.status!=="compatible")return;if(await Pg(J.url,Q.authToken,$))return;return v8(J.url,Q.authToken)}async function aL(h={}){if(h.endpoint?.trim()){let J=await uL(h.endpoint);return J.status==="compatible"?J.url:void 0}let $=lL(),Z=await g0($.discoveryPath);if(!Z?.url)return await NHh($,h);let Q=await uL(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if(Q.status==="compatible")return v8(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await Z4($.discoveryPath).catch(()=>{return});return}async function _J(h={}){let $=await aL(h);if($&&await Z2($,{workspaceRoot:h.workspaceRoot,cwd:h.cwd}))return $;if(h.endpoint?.trim())return;try{return(await FJ(h.workspaceRoot??process.cwd())).url}catch{return}}async function Y9(h,$,Z,Q){let J=new URL(h),X=$?.trim()||dL(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";if(J.pathname="/drain",J.hash="",Z)J.searchParams.set("reason",Z);if(Q?.off)J.searchParams.set("off","1");return(await fetch(J,{method:"POST",headers:X?{authorization:`Bearer ${X}`}:void 0})).ok}async function vL(h,$){let Z=new URL(h),Q=$?.trim()||dL(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function MHh(h=lL()){let $=await g0(h.discoveryPath);if(!$?.url)return!1;try{if(await vL($.url,$.authToken))return!0}catch{}return!1}async function bg(h){if(!cL(h.url))return;let $=lL(),Z=await g0($.discoveryPath);if(!Z?.url||!OHh(Z.url,h.url))return;if(!await Pg(Z.url,Z.authToken,{workspaceRoot:h.workspaceRoot,cwd:h.cwd}))return;if(!await MHh())return;if(!await AHh(Z.url))return;return await Z4($.discoveryPath).catch(()=>{return}),await _J({workspaceRoot:h.workspaceRoot,cwd:h.cwd})}import{resolveProviderRequestHeaders as yHh}from"@cerebriline/llms";import{captureSdkError as nL,createSessionId as vg,HUB_CHECKPOINT_CAPABILITY as kHh,HUB_COMPACTION_CAPABILITY as SHh,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as IHh,HUB_HOOK_CAPABILITY_PREFIX as xHh,HUB_MISTAKE_LIMIT_CAPABILITY as vHh,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as gHh,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as mHh,isGeneratedMedia as cHh,isHubToolExecutorName as uHh}from"@cerebriline/shared";import{createHash as fHh}from"node:crypto";import{formatDisplayUserInput as yg}from"@cerebriline/shared";import{z as z$}from"zod";function THh(h){if(!h||typeof h!=="object"||Array.isArray(h))return!1;let $=h;if($.role!=="user"&&$.role!=="assistant")return!1;return typeof $.content==="string"||Array.isArray($.content)}var CHh=z$.custom(THh),PK=z$.object({version:z$.literal(1),updated_at:z$.string().datetime(),conversation_id:z$.string().min(1).optional(),source_message_count:z$.number().int().nonnegative(),source_prefix_hash:z$.string().min(1).optional(),source_last_message_key:z$.string().min(1).optional(),messages:z$.array(CHh),system_prompt:z$.string().optional()});function iL(h){return JSON.parse(JSON.stringify(h))}function kg(h){if(h.role!=="user")return h;if(typeof h.content==="string")return{...h,content:yg(h.content)};return{...h,content:h.content.map(($)=>$.type==="text"?{...$,text:yg($.text)}:$)}}function Sg(h){if(h.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function RHh(h){let $=kg(h);return Sg($.role),[["role",$.role],["content",$.content],["agent",$.agent??null],["sessionId",$.sessionId??null],["metadata",$.metadata??null],["modelInfo",$.modelInfo??null],["metrics",$.metrics??null]]}function Ig(h){if(!h)return"";let $=kg(h);if(typeof $.id==="string"&&$.id.trim())return`id:${$.id.trim()}`;if(Sg($.role),typeof $.ts==="number"&&Number.isFinite($.ts))return`ts:${$.role}:${$.ts}`;return`content:${$.role}:${JSON.stringify($.content)}`}function xg(h,$=h.length){let Z=fHh("sha256");Z.update(`cline-session-compaction-source-v2
|
|
4503
4503
|
`),Z.update(`${$}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cerebriline/core",
|
|
3
3
|
"description": "Cerebriline Core SDK for Node Runtime",
|
|
4
|
-
"version": "4.100.
|
|
4
|
+
"version": "4.100.244",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/mann1x/cline.git",
|
|
@@ -69,9 +69,9 @@
|
|
|
69
69
|
"ws": "^8.20.0",
|
|
70
70
|
"yaml": "^2.8.2",
|
|
71
71
|
"zod": "^4.3.6",
|
|
72
|
-
"@cerebriline/agents": "4.100.
|
|
73
|
-
"@cerebriline/llms": "4.100.
|
|
74
|
-
"@cerebriline/shared": "4.100.
|
|
72
|
+
"@cerebriline/agents": "4.100.244",
|
|
73
|
+
"@cerebriline/llms": "4.100.244",
|
|
74
|
+
"@cerebriline/shared": "4.100.244"
|
|
75
75
|
},
|
|
76
76
|
"peerDependencies": {
|
|
77
77
|
"posthog-node": "^5.8.0"
|