@cerebriline/core 4.100.249 → 4.100.250

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.
@@ -1,4 +1,4 @@
1
- import{createRequire as t0}from"node:module";var a0=t0(import.meta.url);import{homedir as l1}from"node:os";import{claimHubDaemonProcess as c1}from"@cerebriline/shared";import{setHomeDirIfUnset as i1}from"@cerebriline/shared/storage";import{createSessionId as O1,ensureLoopbackProxyBypass as k0,isHubProtocolCompatible as B1,resolveClineBuildEnv as A1,resolveHubCommandTimeoutMs as f1}from"@cerebriline/shared";import U1 from"ws";var x={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@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 $0="session_not_found";class u extends Error{sessionId;code="session_not_found";constructor(J,j){super(j??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as k2}from"node:child_process";import{closeSync as y2,mkdirSync as b2,openSync as h2,readFileSync as m2,unlinkSync as v2}from"node:fs";import{basename as u2,dirname as p2,join as l2}from"node:path";import{fileURLToPath as c2}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as i2,isBunEmbeddedModulePath as n2,isHubDaemonProcess as s2,resolveClineBuildEnv as S0,withResolvedClineBuildEnv as d2}from"@cerebriline/shared";import{createHash as r0,randomBytes as e0}from"node:crypto";import{mkdir as l,open as X0,readFile as W0,rename as J2,rm as I,writeFile as j2}from"node:fs/promises";import{dirname as G0,join as c}from"node:path";import{ensureLoopbackProxyBypass as Q2,isHubProtocolCompatible as Z2}from"@cerebriline/shared";import{resolveClineDataDir as D,resolveClineDir as Q6}from"@cerebriline/shared/storage";var $2="CLINE_HUB_DISCOVERY_PATH",X2="CLINE_HUB_BUILD_ID",z2="CLINE_HUB_BUILD_EPOCH_MS",V2=30000,Y2=15000,z0=100;function N2(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function W2(J){return r0("sha256").update(J).digest("hex").slice(0,12)}function G2(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(j){return j instanceof Error&&"code"in j?String(j.code)==="EPERM":!1}}function V0(J){return new Promise((j)=>setTimeout(j,J))}function K2(J){return`${J}.lock`}async function q2(J){try{let j=JSON.parse(await W0(c(J,"owner.json"),"utf8"));if(typeof j.pid!=="number"||typeof j.acquiredAt!=="string")return;return{pid:j.pid,acquiredAt:j.acquiredAt}}catch{return}}async function p(J){await I(J,{recursive:!0,force:!0}).catch(()=>{return})}function C(){let J=process.env[X2]?.trim();if(J)return J;return"sdk-v1-5e5cbbd449b2ed4fe502fdfcac849230ad16119851bcdf43d5731fc082612031".trim()||`source-${String(x.version)}`}function F2(){let J=Number(process.env[z2]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1791835710163)?1791835710163:void 0}function w(J,j=C()){let Q=Z2(J);if(!Q.compatible)return Q;let Z=J.buildId?.trim();if(!Z)return{compatible:!1,reason:"missing_build"};if(Z!==j)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function Y0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function N0(J){let j=J?.trim().split(/[-+]/,1)[0];if(!j)return;let Q=j.split(".").map((Z)=>Number(Z));if(Q.length===0||Q.some((Z)=>!Number.isInteger(Z)||Z<0))return;return Q}function L2(J,j){for(let Q=0;Q<Math.max(J.length,j.length);Q++){let Z=J[Q]??0,$=j[Q]??0;if(Z!==$)return Z<$?-1:1}return 0}function K0(J,j){let Q=J.buildId?.trim(),Z=j.buildId?.trim();if(Q&&Z&&Q===Z)return 0;let $=Y0(J.buildEpochMs),X=Y0(j.buildEpochMs);if($!==void 0&&X!==void 0&&$!==X)return $<X?-1:1;let z=N0(J.coreVersion),N=N0(j.coreVersion);if(z&&N){let Y=L2(z,N);if(Y!==0)return Y}if(Q&&Z&&Q!==Z)return Q<Z?-1:1;return 0}function q0(){return{buildId:C(),buildEpochMs:F2(),coreVersion:String(x.version)}}function P(J,j){let Q=j?.self??q0(),Z=w(J,Q.buildId??"");if(Z.compatible)return!0;if(Z.reason!=="build_mismatch"&&Z.reason!=="missing_build")return!1;return K0(Q,J)<=0}function F0(J=process.argv[1]?.trim()||process.cwd()){let j=`hub-${W2(J)}`,Q=process.env[$2]?.trim()||c(D(),"locks","hub","owners",`${N2(j)}.json`);return{ownerId:j,discoveryPath:Q}}async function B(J){try{let j=JSON.parse(await W0(J,"utf8"));if(typeof j.hubId!=="string"||typeof j.protocolVersion!=="string"||typeof j.authToken!=="string"||typeof j.host!=="string"||typeof j.port!=="number"||typeof j.url!=="string"||typeof j.startedAt!=="string"||typeof j.updatedAt!=="string")return;return{hubId:j.hubId,protocolVersion:j.protocolVersion,minClientProtocolVersion:typeof j.minClientProtocolVersion==="string"?j.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof j.maxClientProtocolVersion==="string"?j.maxClientProtocolVersion:void 0,capabilities:Array.isArray(j.capabilities)?j.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof j.coreVersion==="string"?j.coreVersion:void 0,buildId:typeof j.buildId==="string"?j.buildId:void 0,buildEpochMs:typeof j.buildEpochMs==="number"?j.buildEpochMs:void 0,authToken:j.authToken,host:j.host,port:j.port,url:j.url,pid:typeof j.pid==="number"?j.pid:void 0,startedAt:j.startedAt,updatedAt:j.updatedAt}}catch{return}}async function L0(J,j,Q){await i(J,async()=>{let Z=G0(J);await l(Z,{recursive:!0});let $=`${J}.${process.pid}.${e0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(j,null,2)}
1
+ import{createRequire as t0}from"node:module";var a0=t0(import.meta.url);import{homedir as l1}from"node:os";import{claimHubDaemonProcess as c1}from"@cerebriline/shared";import{setHomeDirIfUnset as i1}from"@cerebriline/shared/storage";import{createSessionId as O1,ensureLoopbackProxyBypass as k0,isHubProtocolCompatible as B1,resolveClineBuildEnv as A1,resolveHubCommandTimeoutMs as f1}from"@cerebriline/shared";import U1 from"ws";var x={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@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 $0="session_not_found";class u extends Error{sessionId;code="session_not_found";constructor(J,j){super(j??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as k2}from"node:child_process";import{closeSync as y2,mkdirSync as b2,openSync as h2,readFileSync as m2,unlinkSync as v2}from"node:fs";import{basename as u2,dirname as p2,join as l2}from"node:path";import{fileURLToPath as c2}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as i2,isBunEmbeddedModulePath as n2,isHubDaemonProcess as s2,resolveClineBuildEnv as S0,withResolvedClineBuildEnv as d2}from"@cerebriline/shared";import{createHash as r0,randomBytes as e0}from"node:crypto";import{mkdir as l,open as X0,readFile as W0,rename as J2,rm as I,writeFile as j2}from"node:fs/promises";import{dirname as G0,join as c}from"node:path";import{ensureLoopbackProxyBypass as Q2,isHubProtocolCompatible as Z2}from"@cerebriline/shared";import{resolveClineDataDir as D,resolveClineDir as Q6}from"@cerebriline/shared/storage";var $2="CLINE_HUB_DISCOVERY_PATH",X2="CLINE_HUB_BUILD_ID",z2="CLINE_HUB_BUILD_EPOCH_MS",V2=30000,Y2=15000,z0=100;function N2(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function W2(J){return r0("sha256").update(J).digest("hex").slice(0,12)}function G2(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(j){return j instanceof Error&&"code"in j?String(j.code)==="EPERM":!1}}function V0(J){return new Promise((j)=>setTimeout(j,J))}function K2(J){return`${J}.lock`}async function q2(J){try{let j=JSON.parse(await W0(c(J,"owner.json"),"utf8"));if(typeof j.pid!=="number"||typeof j.acquiredAt!=="string")return;return{pid:j.pid,acquiredAt:j.acquiredAt}}catch{return}}async function p(J){await I(J,{recursive:!0,force:!0}).catch(()=>{return})}function C(){let J=process.env[X2]?.trim();if(J)return J;return"sdk-v1-60a66114367f2ef4b034ec68043e8c751e15bcf46da4f62bffd40c3b75ccf1fc".trim()||`source-${String(x.version)}`}function F2(){let J=Number(process.env[z2]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1791878691346)?1791878691346:void 0}function w(J,j=C()){let Q=Z2(J);if(!Q.compatible)return Q;let Z=J.buildId?.trim();if(!Z)return{compatible:!1,reason:"missing_build"};if(Z!==j)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function Y0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function N0(J){let j=J?.trim().split(/[-+]/,1)[0];if(!j)return;let Q=j.split(".").map((Z)=>Number(Z));if(Q.length===0||Q.some((Z)=>!Number.isInteger(Z)||Z<0))return;return Q}function L2(J,j){for(let Q=0;Q<Math.max(J.length,j.length);Q++){let Z=J[Q]??0,$=j[Q]??0;if(Z!==$)return Z<$?-1:1}return 0}function K0(J,j){let Q=J.buildId?.trim(),Z=j.buildId?.trim();if(Q&&Z&&Q===Z)return 0;let $=Y0(J.buildEpochMs),X=Y0(j.buildEpochMs);if($!==void 0&&X!==void 0&&$!==X)return $<X?-1:1;let z=N0(J.coreVersion),N=N0(j.coreVersion);if(z&&N){let Y=L2(z,N);if(Y!==0)return Y}if(Q&&Z&&Q!==Z)return Q<Z?-1:1;return 0}function q0(){return{buildId:C(),buildEpochMs:F2(),coreVersion:String(x.version)}}function P(J,j){let Q=j?.self??q0(),Z=w(J,Q.buildId??"");if(Z.compatible)return!0;if(Z.reason!=="build_mismatch"&&Z.reason!=="missing_build")return!1;return K0(Q,J)<=0}function F0(J=process.argv[1]?.trim()||process.cwd()){let j=`hub-${W2(J)}`,Q=process.env[$2]?.trim()||c(D(),"locks","hub","owners",`${N2(j)}.json`);return{ownerId:j,discoveryPath:Q}}async function B(J){try{let j=JSON.parse(await W0(J,"utf8"));if(typeof j.hubId!=="string"||typeof j.protocolVersion!=="string"||typeof j.authToken!=="string"||typeof j.host!=="string"||typeof j.port!=="number"||typeof j.url!=="string"||typeof j.startedAt!=="string"||typeof j.updatedAt!=="string")return;return{hubId:j.hubId,protocolVersion:j.protocolVersion,minClientProtocolVersion:typeof j.minClientProtocolVersion==="string"?j.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof j.maxClientProtocolVersion==="string"?j.maxClientProtocolVersion:void 0,capabilities:Array.isArray(j.capabilities)?j.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof j.coreVersion==="string"?j.coreVersion:void 0,buildId:typeof j.buildId==="string"?j.buildId:void 0,buildEpochMs:typeof j.buildEpochMs==="number"?j.buildEpochMs:void 0,authToken:j.authToken,host:j.host,port:j.port,url:j.url,pid:typeof j.pid==="number"?j.pid:void 0,startedAt:j.startedAt,updatedAt:j.updatedAt}}catch{return}}async function L0(J,j,Q){await i(J,async()=>{let Z=G0(J);await l(Z,{recursive:!0});let $=`${J}.${process.pid}.${e0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(j,null,2)}
2
2
  `,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,Q?.beforePublish?.(),await J2($,J);let z;try{z=await X0(Z,"r"),await z.sync()}catch{}finally{await z?.close().catch(()=>{return})}}catch(z){throw await X?.close().catch(()=>{return}),await I($,{force:!0}).catch(()=>{return}),z}})}async function _(J){await i(J,async()=>{await I(J,{force:!0}).catch(()=>{return})})}async function O0(J,j){return await i(J,async()=>{if((await B(J))?.hubId!==j)return!1;return await I(J,{force:!0}),!0})}async function B0(J,j,Q){let Z=K2(J);await l(G0(Z),{recursive:!0});let $=Date.now()+Y2;while(!0){try{await l(Z,{recursive:!1})}catch(X){if((X instanceof Error&&"code"in X?String(X.code):"")!=="EEXIST")throw X;let N=await q2(Z);if(!N){if(Date.now()>=$){await p(Z);continue}await V0(z0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!G2(N.pid)||Y>V2){await p(Z);continue}if(Date.now()>=$)throw Error(`Timed out waiting for hub ${j} lock ${Z}`);await V0(z0);continue}try{return await j2(c(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
3
  `,"utf8"),await Q()}finally{await p(Z)}}}function i(J,j){return B0(`${J}.mutation`,"discovery mutation",j)}function A0(J,j){return B0(J,"startup",j)}async function T(J,j){Q2();try{let Q=await fetch(j?.authToken?O2(J):U0(J),{headers:j?.authToken?{authorization:`Bearer ${j.authToken}`}:void 0,signal:j?.signal});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter(($)=>typeof $==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,buildEpochMs:typeof Z.buildEpochMs==="number"?Z.buildEpochMs:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function f0(J,j,Q="/hub"){return new URL(`ws://${J}:${j}${Q}`).toString()}function U0(J){let j=new URL(J);return j.protocol=j.protocol==="wss:"?"https:":"http:",j.pathname="/health",j.search="",j.toString()}function O2(J){let j=new URL(U0(J));return j.pathname="/status",j.toString()}import{CLINE_HUB_DEV_PORT as B2,CLINE_HUB_PORT as A2,resolveClineBuildEnv as f2}from"@cerebriline/shared";var U2="CLINE_HUB_HOST",M2="CLINE_HUB_PORT",x2="CLINE_HUB_PATHNAME",C2="127.0.0.1",_2=A2,D2="/hub";function M0(J){return f2(J)==="development"?B2:_2}function R2(J={}){return(J.env??process.env)[U2]?.trim()||C2}function E2(J={}){let Q=(J.env??process.env)[M2]?.trim();if(!Q)return M0(J);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return M0(J);return Z}function S2(J={}){return(J.env??process.env)[x2]?.trim()||D2}function x0(J={},j={}){return{host:J.host??R2(j),port:J.port??E2(j),pathname:J.pathname??S2(j)}}import{join as w2}from"node:path";import{execFile as g2}from"node:child_process";import{promisify as I2}from"node:util";import{processWorkspaceInfo as W6}from"@cerebriline/shared";import K6 from"simple-git";var q6=I2(g2);var P2="shared:cline",T2="CLINE_HUB_DISCOVERY_PATH",H2="hub-production";function R(J=P2){return F0(`${J}@${C()}`)}function H(){return{ownerId:H2,discoveryPath:process.env[T2]?.trim()||w2(D(),"locks","hub","production.json")}}var C0=15000,t2=200,_0=3000,a2=100,o2=[100,250,500,1000,2000],r2="--cline-hub-daemon",e2=3,J1=60000,D0=new Map;function j1(J,j=Date.now()){let Q=D0.get(J);if(!Q||j-Q.windowStartedAt>J1)return D0.set(J,{count:1,windowStartedAt:j}),!0;return Q.count+=1,Q.count<=e2}function Q1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function Z1(){try{let J=l2(D(),"logs","hub-daemon.log");return b2(p2(J),{recursive:!0}),{fd:h2(J,"a"),logPath:J}}catch{return}}function $1(){return S0()==="production"?H():R()}function E(J){return P(J)}function X1(J){try{let j=JSON.parse(m2(`${J}.superseded`,"utf8"));return{url:typeof j.url==="string"?j.url:void 0,authToken:typeof j.authToken==="string"?j.authToken:void 0,pid:typeof j.pid==="number"?j.pid:void 0}}catch{return}}function n(J){try{v2(`${J}.superseded`)}catch{}}function R0(J,j,Q){if(!j||j.url!==Q)return J;return{...J,authToken:J.authToken??j.authToken,pid:J.pid??j.pid}}async function S(J,j){try{return await T(J,{authToken:j})}catch{return}}async function E0(J,j){let Q=Date.now()+j;while(Date.now()<Q){if(!(await S(J))?.url)return!0;await new Promise(($)=>setTimeout($,a2))}return!1}async function d(J,j){if(!j1(J.url))return!1;await g(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Q=await E0(J.url,_0);if(!Q&&J.pid&&z1(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Q=await E0(J.url,_0)}if(Q)await _(j).catch(()=>{return});return Q}function z1(J){try{return process.kill(J,0),!0}catch(j){return j?.code==="EPERM"}}async function V1(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function s(J,j){if(E(J))return"reusable";let Q=await g(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await V1(J)){if(Q)await g(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let Z=await d(J,j);if(!Z&&Q)await g(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return Z?"retired":"failed"}async function Y1(J){if(S0()!=="production")return;let j=R();if(j.discoveryPath===J.discoveryPath)return;let Q=await B(j.discoveryPath);if(Q?.url)await d(Q,j.discoveryPath);else await _(j.discoveryPath).catch(()=>{return})}function N1(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return c2(new URL(`./entry.${J}`,import.meta.url))}function W1(J,j){if(n2(J))return[r2];return[...j&&J.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],J]}function G1(J,j){let Q=N1(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let $=u2(Z).toLowerCase().includes("bun"),X=W1(Q,$);return{launcher:Z,args:[...X,"--cwd",J,...Q1(j),...j.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...d2(process.env),CLINE_NO_INTERACTIVE:"1",[i2]:"1"}}}function K1(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Q="message"in J?J.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function q1(J,j={}){if(s2())return;let Q=G1(J,j),Z=Z1();try{k2(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)y2(Z.fd)}}async function F1(J,j={}){for(let Q=0;;Q++)try{q1(J,j);return}catch(Z){let $=o2[Q];if(!K1(Z)||$===void 0)throw Z;await new Promise((X)=>setTimeout(X,$))}}async function L1(J,j,Q={}){let Z=Q.host!==void 0||Q.port!==void 0||Q.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),$=x0(Q),X=f0($.host,$.port,$.pathname),z=(G)=>{if(!Z)y(G.url,G.authToken);else g0(G.url,G.authToken);return G};await Y1(J).catch(()=>{return});let N=await B(J.discoveryPath),Y=N?.url?void 0:X1(J.discoveryPath),W=!1;if(N?.url){let G=N.authToken;if(!G)W=!0,await d(N,J.discoveryPath);else{let K=await S(N.url,G);if(K?.url&&E(K)&&await A(K.url,{authToken:G}))return n(J.discoveryPath),z({url:K.url,authToken:G});if(K?.url){if(await s({...K,authToken:G},J.discoveryPath)==="deferred_busy"&&await A(K.url,{authToken:G}))return z({url:K.url,authToken:G})}else await _(J.discoveryPath).catch(()=>{return})}}let V=await S(X);if(V?.url){let G=R0(V,N??Y,X);if(E(V)){let L=[V.authToken,N?.authToken,Y?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0);for(let M of L){if(!await A(V.url,{authToken:M}))continue;let d0={hubId:V.hubId??`repaired-${V.port}`,protocolVersion:V.protocolVersion,minClientProtocolVersion:V.minClientProtocolVersion,maxClientProtocolVersion:V.maxClientProtocolVersion,capabilities:V.capabilities,coreVersion:V.coreVersion,buildId:V.buildId,authToken:M,host:V.host,port:V.port,url:V.url,pid:V.pid??N?.pid??Y?.pid,startedAt:V.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await L0(J.discoveryPath,d0)}catch{}return n(J.discoveryPath),z({url:V.url,authToken:M})}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.${W?" 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 K=await s(G,J.discoveryPath);if(K==="deferred_busy"){for(let L of[G.authToken,N?.authToken].filter((U)=>typeof U==="string"&&U.trim().length>0))if(await A(V.url,{authToken:L}))return z({url:V.url,authToken:L});if(Q.allowPortFallback!==!0&&$.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(K==="failed"&&Q.allowPortFallback!==!0&&$.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 O=Q.allowPortFallback===!0&&$.port!==0?{...$,port:0}:$;await F1(j,{...O,manageConnectors:Q.manageConnectors});let f=Date.now()+C0;while(Date.now()<f){let G=await B(J.discoveryPath);if(G?.url&&G.authToken){let L=await S(G.url,G.authToken);if(L?.url&&E(L)&&await A(L.url,{authToken:G.authToken}))return n(J.discoveryPath),z({url:L.url,authToken:G.authToken})}let K=await S(X);if(K?.url&&!E(K)){let L=R0(K,G??Y,X),U=await s(L,J.discoveryPath);if(U==="deferred_busy"&&G?.authToken&&await A(K.url,{authToken:G.authToken}))return z({url:K.url,authToken:G.authToken});if(U==="failed"&&Q.allowPortFallback!==!0&&$.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((L)=>setTimeout(L,t2))}throw Error(`Timed out after ${C0}ms waiting for detached hub startup.`)}async function k(J,j={}){let Q=$1();return await A0(Q.discoveryPath,async()=>L1(Q,J,j))}function M1(){return A1()==="production"?H():R()}function x1(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function y0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((j)=>Buffer.from(j))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return y0(J.data);return String(J)}function C1(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function I0(J){let j=J,Q=C1(j.reason);return new q("hub_connection_closed",j.code||Q?`Hub connection closed (code=${j.code??0}${Q?`, reason=${Q}`:""})`:o,{closeCode:j.code,closeReason:Q||void 0})}function w0(J,j){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Q=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Q)return new q("hub_connect_failed",Q);let Z=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",Z?`Failed to connect to hub at ${j.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${j.toString()}.`)}var a="*",h=8000,_1="cline-hub-auth.",J0=new Map,b0=new Set,D1=3000;var o="Hub connection closed",R1=250,E1=5000,P0=0.5;class q extends Error{code;details;constructor(J,j,Q){super(j);this.code=J;this.details=Q;this.name="HubTransportError"}}function S1(J){return J instanceof q}class r extends Error{command;code;constructor(J,j,Q){super(Q);this.command=J;this.code=j;this.name="HubCommandError"}}function j0(J,j={}){let Q=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Q)return Q;if(j.skipRegistry)return;let Z=m(J.toString());return Z?J0.get(Z):void 0}function g1(J){try{let Q=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function m(J){if(!g1(J))return;let j=new URL(h0(J));return j.search="",j.hash="",j.toString()}function T0(J){let j=m(J);return!!j&&b0.has(j)}function y(J,j){let Q=m(J);if(Q){if(b0.add(Q),j?.trim())J0.set(Q,j)}return J}function g0(J,j){let Q=m(J);if(Q&&j?.trim())J0.set(Q,j)}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",o);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.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(J){if(this.capabilities=J.map((j)=>({...j})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),j=this.options.authToken?.trim()||j0(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",j&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Q=++this.connectGeneration,Z=this.openSocket(J,j,Q),$;this.connectPromise=Z.then(async(z)=>{if($=z,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(x.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Q!==this.connectGeneration||this.closedByClient){try{z.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let X=this.connectPromise;try{await X}catch(z){if(this.connectPromise===X)this.connectPromise=void 0;if($&&this.socket===$){this.lastCloseError=w0(z,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{$.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw z}}async openSocket(J,j,Q){let Z=this.options.resolveConnectionHeaders,$;if(Z){let Y;try{$=await Promise.race([Promise.resolve().then(()=>Z()),new Promise((W,V)=>{Y=setTimeout(()=>{V(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(W){let V=W instanceof q?W:new q("hub_connect_failed",W instanceof Error?W.message:String(W));if(Q===this.connectGeneration)this.lastCloseError=V;throw V}finally{clearTimeout(Y)}}if(Q!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if($&&Object.keys($).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Q===this.connectGeneration)this.lastCloseError=Y;throw Y}let X=$?new U1(J.toString(),{headers:{...$}}):new(x1())(J.toString(),j?[`${_1}${j}`]:void 0);this.socket=X;let z=!1,N=new Promise((Y,W)=>{let V=!1,F=setTimeout(()=>{if(V)return;V=!0,z=!0;let O=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===X)this.lastCloseError=O,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{X.close()}catch{}W(O)},h);X.addEventListener("open",()=>{if(V)return;V=!0,clearTimeout(F),Y()}),X.addEventListener("error",(O)=>{if(V)return;V=!0,clearTimeout(F);let f=w0(O,J);if(this.socket===X)this.lastCloseError=f,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;W(f)}),X.addEventListener("close",(O)=>{if(V)return;V=!0,clearTimeout(F);let f=z?this.lastCloseError:I0(O);if(this.socket===X){if(!z)this.lastCloseError=f,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}W(f)})});return X.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(y0(Y)))}),X.addEventListener("close",(Y)=>{if(this.socket!==X)return;if(!z)this.lastCloseError=I0(Y),this.sawSocketClose=!0;this.registered=!1;for(let W of this.pendingReplies.values())W.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,X}subscribe(J,j){let Q=j?.sessionId?.trim()||void 0,Z={listener:J,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command(J,j,Q,Z){let $=0,X=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,j,Q,Z)}catch(z){if(!X||$>=1||!await this.recoverLocalHubTransport(z))throw z;$+=1}}async commandOnce(J,j,Q,Z,$=!0){if($)await this.connect();Z?.beforeDispatch?.();let X=O1("hubreq_");Z?.onDispatch?.(X);let z=f1(J,Z?.timeoutMs),N=new Promise((W,V)=>{let F=z===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(X))return;V(new r(J,"hub_command_timeout",`Hub command ${J} timed out after ${z}ms (hub=${this.currentUrl}, requestId=${X}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},z);this.pendingReplies.set(X,{resolve:(O)=>{if(F)clearTimeout(F);W(O)},reject:(O)=>{if(F)clearTimeout(F);V(O)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:X,clientId:this.clientId,sessionId:Q,timeoutMs:z,payload:j}})}catch(W){throw this.pendingReplies.delete(X),W}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let W=Q??(typeof j?.sessionId==="string"?j.sessionId:void 0);throw new u(W,Y.error.message)}throw new r(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!T0(this.currentUrl)||!S1(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let j=await H0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!j)return!1;return this.currentUrl=j,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 J=Math.min(R1*2**this.reconnectAttempt,E1),j=Math.round(J*(1-P0)+Math.random()*J*P0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},j)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!T0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await H0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",o);for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.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(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,j){let Q=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(j)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...j?{sessionId:j}:{},...Q!==void 0?{sinceSequence:Q}:{}})}adjustSubscriptionCount(J,j){let Q=this.subscriptionKeyForSessionId(J),Z=(this.subscriptionCounts.get(Q)??0)+j;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(j<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Q,Z),j>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??a}subscriptionSessionIdFromKey(J){return J===a?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let j=J.envelope.requestId;if(!j)return;let Q=this.pendingReplies.get(j);if(!Q)return;this.pendingReplies.delete(j),Q.resolve(J.envelope);return}case"event":{let j=J.envelope.sequence;if(typeof j==="number"){let Q=J.envelope.sessionId?.trim();for(let Z of[a,Q]){if(!Z||!this.subscriptionCounts.has(Z))continue;let $=this.lastEventSequenceByKey.get(Z)??0;if(j>$)this.lastEventSequenceByKey.set(Z,j)}}for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J.envelope.sessionId?.trim())continue;Q.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function h0(J){let j=new URL(J);if(j.protocol==="http:")j.protocol="ws:";else if(j.protocol==="https:")j.protocol="wss:";return j.toString()}async function A(J,j){let Q=new Q0({url:J,authToken:j?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:j?.workspaceRoot,cwd:j?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function e(J,j){let Q=h0(J),Z=await T(Q,{authToken:j?.authToken});if(!Z)return{status:"unreachable",url:Q};if(j?.requireCurrentBuild){let $=C(),X=w(Z,$);if(!X.compatible&&!P(Z))return{status:X.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Q}}else if(!B1(Z).compatible)return{status:"protocol_mismatch",url:Q};if(j?.verifyConnection===!0&&!await A(Q,{workspaceRoot:j.workspaceRoot,cwd:j.cwd,authToken:j.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}function I1(J){let j=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Q=0,Z=new Set;for(let $ of j){if(!$||typeof $!=="object")continue;let X=$.participants;if(!Array.isArray(X)||X.length===0)continue;Q+=1;for(let z of X){let N=z&&typeof z==="object"?z.clientId:void 0;if(typeof N==="string"&&N.trim())Z.add(N)}}return{activeSessionCount:Q,participantClientCount:Z.size}}async function t(J,j,Q){let Z=new Q0({url:J,authToken:j,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let $=await Z.command("session.list",{limit:500},void 0,{timeoutMs:D1});return I1($.payload)}finally{await Z.dispose().catch(()=>{return})}}async function w1(J,j,Q){try{return(await t(J,j,Q)).activeSessionCount===0}catch{return!1}}async function P1(J,j){let Q=`${J.discoveryPath}.superseded`,Z=await B(Q);if(!Z?.url||!Z.authToken)return;let $=await e(Z.url,{authToken:Z.authToken});if($.status!=="compatible")return;if(await w1($.url,Z.authToken,j))return;return y($.url,Z.authToken)}async function T1(J={}){if(J.endpoint?.trim()){let $=await e(J.endpoint);return $.status==="compatible"?$.url:void 0}let j=M1(),Q=await B(j.discoveryPath);if(!Q?.url)return await P1(j,J);let Z=await e(Q.url,{authToken:Q.authToken,requireCurrentBuild:!0});if(Z.status==="compatible")return y(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await _(j.discoveryPath).catch(()=>{return});return}async function H0(J={}){let j=await T1(J);if(j&&await A(j,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return j;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch(Q){J.onStartupError?.(Q);return}}async function g(J,j,Q,Z){k0();let $=new URL(J),X=j?.trim()||j0($);if($.protocol==="ws:")$.protocol="http:";else if($.protocol==="wss:")$.protocol="https:";if($.pathname="/drain",$.hash="",Q)$.searchParams.set("reason",Q);if(Z?.off)$.searchParams.set("off","1");return(await fetch($,{method:"POST",headers:X?{authorization:`Bearer ${X}`}:void 0})).ok}async function b(J,j){k0();let Q=new URL(J),Z=j?.trim()||j0(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}import{spawn as H1}from"node:child_process";import{userInfo as k1}from"node:os";import{basename as y1,delimiter as v}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",v0="__CLINE_SIDECAR_PATH_END__",u0=5000,b1=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${v0}"'`,m0="CLINE_SIDECAR_SKIP_SHELL_PATH";function p0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function h1(J,j){try{let Q=k1().shell?.trim();if(Q)return Q}catch{}return j.SHELL?.trim()||p0(J)}function m1(J,j){let Q=y1(J);if(Q==="csh"||Q==="tcsh")return{args:["-c",j],argv0:`-${Q}`};return{args:["-i","-l","-c",j]}}function v1(J){let j=J.indexOf(Z0);if(j===-1)return;let Q=J.indexOf(v0,j);if(Q===-1)return;let Z=J.slice(j+Z0.length,Q).trim();return Z.length>0?Z:void 0}function u1(J,j){let Q=[...J.split(v),...j.split(v)].map((Z)=>Z.trim()).filter((Z)=>Z.length>0);return Array.from(new Set(Q)).join(v)}function p1(J,j=u0){return new Promise((Q)=>{let Z=m1(J,b1),$=H1(J,Z.args,{argv0:Z.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),X="",z=0,N=()=>{try{if($.pid)process.kill(-$.pid,"SIGKILL")}catch{$.kill("SIGKILL")}},Y=!1,W=(F)=>{if(Y)return;Y=!0,clearTimeout(V),$.stdout?.destroy(),N(),Q(F)},V=setTimeout(()=>{try{if($.pid)process.kill(-$.pid,"SIGKILL")}catch{$.kill("SIGKILL")}W(void 0)},j);$.stdout?.on("data",(F)=>{if(Y)return;if(z+=F.length,z>65536){W(void 0);return}X+=F.toString("utf8")}),$.on("error",()=>W(void 0)),$.on("close",()=>W(v1(X)))})}async function l0(J){let j=J?.platform??process.platform,Q=J?.env??process.env;if(j==="win32")return{status:"skipped",reason:"windows"};if(Q[m0]?.trim())return{status:"skipped",reason:m0};let Z=J?.userShell??h1(j,Q),$=J?.fallbackShell??p0(j),X=J?.timeoutMs??u0,z=Z===$?[[Z,X]]:[[Z,X],[$,X/2]];for(let[N,Y]of z){let W=await p1(N,Y);if(!W)continue;let V=u1(W,Q.PATH??"");return Q.PATH=V,{status:"applied",pathEntries:V.split(v).length,shell:N}}return{status:"failed",shell:Z}}var c0={readHubDiscovery:B,clearHubDiscoveryIfOwned:O0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:c1,loadHubDaemon:()=>import("@cerebriline/core/hub/daemon-entry"),ensureLoginShellPath:l0,setHomeDirIfUnset:i1,homeDir:l1,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function i0(J,j){let Q=J.indexOf(j);return(Q>=0?J[Q+1]:void 0)?.trim()||void 0}function n0(J,j){let Q=i0(J,"--discovery-path");if(!Q)throw Error("--discovery-path is required for remote Hub management");return j.env.CLINE_HUB_DISCOVERY_PATH=Q,Q}async function n1(J=process.argv,j=c0){j.setHomeDirIfUnset(j.homeDir()),await j.ensureLoginShellPath();let Q=i0(J,"--cwd")??j.cwd();n0(J,j);let Z=await j.ensureDetachedHubServer(Q,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});j.writeOutput(`${JSON.stringify({...Z,cwd:Q,platform:process.platform,arch:process.arch})}
4
4
  `)}async function s0(J=process.argv,j=c0){if(J.includes("--remote-hub-stop")){let Q=n0(J,j),Z=await j.readHubDiscovery(Q);if(Z&&typeof Z.pid==="number"&&Number.isInteger(Z.pid)&&Z.pid>0)try{j.probeProcess(Z.pid)}catch($){if($?.code==="ESRCH")return await j.clearHubDiscoveryIfOwned(Q,Z.hubId),!0}if(Z&&!await j.requestHubShutdown(Z.url,Z.authToken))throw Error("Remote Hub shutdown failed");return!0}if(J.includes("--remote-hub-ensure"))return await n1(J,j),!0;if(j.claimHubDaemonProcess())return await j.loadHubDaemon(),!0;return!1}(async()=>{if(!await s0())throw Error("A remote helper command is required")})().catch((J)=>{process.stderr.write(`${J instanceof Error?J.message:String(J)}
@@ -1,4 +1,4 @@
1
- import{createRequire as d0}from"node:module";var t0=d0(import.meta.url);import{homedir as p1}from"node:os";import{claimHubDaemonProcess as l1}from"@cerebriline/shared";import{setHomeDirIfUnset as c1}from"@cerebriline/shared/storage";import{createSessionId as L1,ensureLoopbackProxyBypass as k0,isHubProtocolCompatible as O1,resolveClineBuildEnv as B1,resolveHubCommandTimeoutMs as A1}from"@cerebriline/shared";import f1 from"ws";var x={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@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 $0="session_not_found";class u extends Error{sessionId;code="session_not_found";constructor(J,j){super(j??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as H2}from"node:child_process";import{closeSync as k2,mkdirSync as y2,openSync as b2,readFileSync as h2,unlinkSync as m2}from"node:fs";import{basename as v2,dirname as u2,join as p2}from"node:path";import{fileURLToPath as l2}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as c2,isBunEmbeddedModulePath as i2,isHubDaemonProcess as n2,resolveClineBuildEnv as S0,withResolvedClineBuildEnv as s2}from"@cerebriline/shared";import{createHash as o0,randomBytes as r0}from"node:crypto";import{mkdir as l,open as X0,readFile as W0,rename as e0,rm as I,writeFile as J2}from"node:fs/promises";import{dirname as G0,join as c}from"node:path";import{ensureLoopbackProxyBypass as j2,isHubProtocolCompatible as Q2}from"@cerebriline/shared";import{resolveClineDataDir as D,resolveClineDir as j6}from"@cerebriline/shared/storage";var Z2="CLINE_HUB_DISCOVERY_PATH",$2="CLINE_HUB_BUILD_ID",X2="CLINE_HUB_BUILD_EPOCH_MS",z2=30000,V2=15000,z0=100;function Y2(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function N2(J){return o0("sha256").update(J).digest("hex").slice(0,12)}function W2(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(j){return j instanceof Error&&"code"in j?String(j.code)==="EPERM":!1}}function V0(J){return new Promise((j)=>setTimeout(j,J))}function G2(J){return`${J}.lock`}async function K2(J){try{let j=JSON.parse(await W0(c(J,"owner.json"),"utf8"));if(typeof j.pid!=="number"||typeof j.acquiredAt!=="string")return;return{pid:j.pid,acquiredAt:j.acquiredAt}}catch{return}}async function p(J){await I(J,{recursive:!0,force:!0}).catch(()=>{return})}function C(){let J=process.env[$2]?.trim();if(J)return J;return"sdk-v1-5e5cbbd449b2ed4fe502fdfcac849230ad16119851bcdf43d5731fc082612031".trim()||`source-${String(x.version)}`}function q2(){let J=Number(process.env[X2]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1791835710163)?1791835710163:void 0}function w(J,j=C()){let Q=Q2(J);if(!Q.compatible)return Q;let Z=J.buildId?.trim();if(!Z)return{compatible:!1,reason:"missing_build"};if(Z!==j)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function Y0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function N0(J){let j=J?.trim().split(/[-+]/,1)[0];if(!j)return;let Q=j.split(".").map((Z)=>Number(Z));if(Q.length===0||Q.some((Z)=>!Number.isInteger(Z)||Z<0))return;return Q}function F2(J,j){for(let Q=0;Q<Math.max(J.length,j.length);Q++){let Z=J[Q]??0,$=j[Q]??0;if(Z!==$)return Z<$?-1:1}return 0}function K0(J,j){let Q=J.buildId?.trim(),Z=j.buildId?.trim();if(Q&&Z&&Q===Z)return 0;let $=Y0(J.buildEpochMs),X=Y0(j.buildEpochMs);if($!==void 0&&X!==void 0&&$!==X)return $<X?-1:1;let z=N0(J.coreVersion),N=N0(j.coreVersion);if(z&&N){let Y=F2(z,N);if(Y!==0)return Y}if(Q&&Z&&Q!==Z)return Q<Z?-1:1;return 0}function q0(){return{buildId:C(),buildEpochMs:q2(),coreVersion:String(x.version)}}function P(J,j){let Q=j?.self??q0(),Z=w(J,Q.buildId??"");if(Z.compatible)return!0;if(Z.reason!=="build_mismatch"&&Z.reason!=="missing_build")return!1;return K0(Q,J)<=0}function F0(J=process.argv[1]?.trim()||process.cwd()){let j=`hub-${N2(J)}`,Q=process.env[Z2]?.trim()||c(D(),"locks","hub","owners",`${Y2(j)}.json`);return{ownerId:j,discoveryPath:Q}}async function B(J){try{let j=JSON.parse(await W0(J,"utf8"));if(typeof j.hubId!=="string"||typeof j.protocolVersion!=="string"||typeof j.authToken!=="string"||typeof j.host!=="string"||typeof j.port!=="number"||typeof j.url!=="string"||typeof j.startedAt!=="string"||typeof j.updatedAt!=="string")return;return{hubId:j.hubId,protocolVersion:j.protocolVersion,minClientProtocolVersion:typeof j.minClientProtocolVersion==="string"?j.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof j.maxClientProtocolVersion==="string"?j.maxClientProtocolVersion:void 0,capabilities:Array.isArray(j.capabilities)?j.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof j.coreVersion==="string"?j.coreVersion:void 0,buildId:typeof j.buildId==="string"?j.buildId:void 0,buildEpochMs:typeof j.buildEpochMs==="number"?j.buildEpochMs:void 0,authToken:j.authToken,host:j.host,port:j.port,url:j.url,pid:typeof j.pid==="number"?j.pid:void 0,startedAt:j.startedAt,updatedAt:j.updatedAt}}catch{return}}async function L0(J,j,Q){await i(J,async()=>{let Z=G0(J);await l(Z,{recursive:!0});let $=`${J}.${process.pid}.${r0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(j,null,2)}
1
+ import{createRequire as d0}from"node:module";var t0=d0(import.meta.url);import{homedir as p1}from"node:os";import{claimHubDaemonProcess as l1}from"@cerebriline/shared";import{setHomeDirIfUnset as c1}from"@cerebriline/shared/storage";import{createSessionId as L1,ensureLoopbackProxyBypass as k0,isHubProtocolCompatible as O1,resolveClineBuildEnv as B1,resolveHubCommandTimeoutMs as A1}from"@cerebriline/shared";import f1 from"ws";var x={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@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 $0="session_not_found";class u extends Error{sessionId;code="session_not_found";constructor(J,j){super(j??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as H2}from"node:child_process";import{closeSync as k2,mkdirSync as y2,openSync as b2,readFileSync as h2,unlinkSync as m2}from"node:fs";import{basename as v2,dirname as u2,join as p2}from"node:path";import{fileURLToPath as l2}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as c2,isBunEmbeddedModulePath as i2,isHubDaemonProcess as n2,resolveClineBuildEnv as S0,withResolvedClineBuildEnv as s2}from"@cerebriline/shared";import{createHash as o0,randomBytes as r0}from"node:crypto";import{mkdir as l,open as X0,readFile as W0,rename as e0,rm as I,writeFile as J2}from"node:fs/promises";import{dirname as G0,join as c}from"node:path";import{ensureLoopbackProxyBypass as j2,isHubProtocolCompatible as Q2}from"@cerebriline/shared";import{resolveClineDataDir as D,resolveClineDir as j6}from"@cerebriline/shared/storage";var Z2="CLINE_HUB_DISCOVERY_PATH",$2="CLINE_HUB_BUILD_ID",X2="CLINE_HUB_BUILD_EPOCH_MS",z2=30000,V2=15000,z0=100;function Y2(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function N2(J){return o0("sha256").update(J).digest("hex").slice(0,12)}function W2(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(j){return j instanceof Error&&"code"in j?String(j.code)==="EPERM":!1}}function V0(J){return new Promise((j)=>setTimeout(j,J))}function G2(J){return`${J}.lock`}async function K2(J){try{let j=JSON.parse(await W0(c(J,"owner.json"),"utf8"));if(typeof j.pid!=="number"||typeof j.acquiredAt!=="string")return;return{pid:j.pid,acquiredAt:j.acquiredAt}}catch{return}}async function p(J){await I(J,{recursive:!0,force:!0}).catch(()=>{return})}function C(){let J=process.env[$2]?.trim();if(J)return J;return"sdk-v1-60a66114367f2ef4b034ec68043e8c751e15bcf46da4f62bffd40c3b75ccf1fc".trim()||`source-${String(x.version)}`}function q2(){let J=Number(process.env[X2]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1791878691346)?1791878691346:void 0}function w(J,j=C()){let Q=Q2(J);if(!Q.compatible)return Q;let Z=J.buildId?.trim();if(!Z)return{compatible:!1,reason:"missing_build"};if(Z!==j)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function Y0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function N0(J){let j=J?.trim().split(/[-+]/,1)[0];if(!j)return;let Q=j.split(".").map((Z)=>Number(Z));if(Q.length===0||Q.some((Z)=>!Number.isInteger(Z)||Z<0))return;return Q}function F2(J,j){for(let Q=0;Q<Math.max(J.length,j.length);Q++){let Z=J[Q]??0,$=j[Q]??0;if(Z!==$)return Z<$?-1:1}return 0}function K0(J,j){let Q=J.buildId?.trim(),Z=j.buildId?.trim();if(Q&&Z&&Q===Z)return 0;let $=Y0(J.buildEpochMs),X=Y0(j.buildEpochMs);if($!==void 0&&X!==void 0&&$!==X)return $<X?-1:1;let z=N0(J.coreVersion),N=N0(j.coreVersion);if(z&&N){let Y=F2(z,N);if(Y!==0)return Y}if(Q&&Z&&Q!==Z)return Q<Z?-1:1;return 0}function q0(){return{buildId:C(),buildEpochMs:q2(),coreVersion:String(x.version)}}function P(J,j){let Q=j?.self??q0(),Z=w(J,Q.buildId??"");if(Z.compatible)return!0;if(Z.reason!=="build_mismatch"&&Z.reason!=="missing_build")return!1;return K0(Q,J)<=0}function F0(J=process.argv[1]?.trim()||process.cwd()){let j=`hub-${N2(J)}`,Q=process.env[Z2]?.trim()||c(D(),"locks","hub","owners",`${Y2(j)}.json`);return{ownerId:j,discoveryPath:Q}}async function B(J){try{let j=JSON.parse(await W0(J,"utf8"));if(typeof j.hubId!=="string"||typeof j.protocolVersion!=="string"||typeof j.authToken!=="string"||typeof j.host!=="string"||typeof j.port!=="number"||typeof j.url!=="string"||typeof j.startedAt!=="string"||typeof j.updatedAt!=="string")return;return{hubId:j.hubId,protocolVersion:j.protocolVersion,minClientProtocolVersion:typeof j.minClientProtocolVersion==="string"?j.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof j.maxClientProtocolVersion==="string"?j.maxClientProtocolVersion:void 0,capabilities:Array.isArray(j.capabilities)?j.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof j.coreVersion==="string"?j.coreVersion:void 0,buildId:typeof j.buildId==="string"?j.buildId:void 0,buildEpochMs:typeof j.buildEpochMs==="number"?j.buildEpochMs:void 0,authToken:j.authToken,host:j.host,port:j.port,url:j.url,pid:typeof j.pid==="number"?j.pid:void 0,startedAt:j.startedAt,updatedAt:j.updatedAt}}catch{return}}async function L0(J,j,Q){await i(J,async()=>{let Z=G0(J);await l(Z,{recursive:!0});let $=`${J}.${process.pid}.${r0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(j,null,2)}
2
2
  `,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,Q?.beforePublish?.(),await e0($,J);let z;try{z=await X0(Z,"r"),await z.sync()}catch{}finally{await z?.close().catch(()=>{return})}}catch(z){throw await X?.close().catch(()=>{return}),await I($,{force:!0}).catch(()=>{return}),z}})}async function _(J){await i(J,async()=>{await I(J,{force:!0}).catch(()=>{return})})}async function O0(J,j){return await i(J,async()=>{if((await B(J))?.hubId!==j)return!1;return await I(J,{force:!0}),!0})}async function B0(J,j,Q){let Z=G2(J);await l(G0(Z),{recursive:!0});let $=Date.now()+V2;while(!0){try{await l(Z,{recursive:!1})}catch(X){if((X instanceof Error&&"code"in X?String(X.code):"")!=="EEXIST")throw X;let N=await K2(Z);if(!N){if(Date.now()>=$){await p(Z);continue}await V0(z0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!W2(N.pid)||Y>z2){await p(Z);continue}if(Date.now()>=$)throw Error(`Timed out waiting for hub ${j} lock ${Z}`);await V0(z0);continue}try{return await J2(c(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
3
  `,"utf8"),await Q()}finally{await p(Z)}}}function i(J,j){return B0(`${J}.mutation`,"discovery mutation",j)}function A0(J,j){return B0(J,"startup",j)}async function T(J,j){j2();try{let Q=await fetch(j?.authToken?L2(J):U0(J),{headers:j?.authToken?{authorization:`Bearer ${j.authToken}`}:void 0,signal:j?.signal});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter(($)=>typeof $==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,buildEpochMs:typeof Z.buildEpochMs==="number"?Z.buildEpochMs:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function f0(J,j,Q="/hub"){return new URL(`ws://${J}:${j}${Q}`).toString()}function U0(J){let j=new URL(J);return j.protocol=j.protocol==="wss:"?"https:":"http:",j.pathname="/health",j.search="",j.toString()}function L2(J){let j=new URL(U0(J));return j.pathname="/status",j.toString()}import{CLINE_HUB_DEV_PORT as O2,CLINE_HUB_PORT as B2,resolveClineBuildEnv as A2}from"@cerebriline/shared";var f2="CLINE_HUB_HOST",U2="CLINE_HUB_PORT",M2="CLINE_HUB_PATHNAME",x2="127.0.0.1",C2=B2,_2="/hub";function M0(J){return A2(J)==="development"?O2:C2}function D2(J={}){return(J.env??process.env)[f2]?.trim()||x2}function R2(J={}){let Q=(J.env??process.env)[U2]?.trim();if(!Q)return M0(J);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return M0(J);return Z}function E2(J={}){return(J.env??process.env)[M2]?.trim()||_2}function x0(J={},j={}){return{host:J.host??D2(j),port:J.port??R2(j),pathname:J.pathname??E2(j)}}import{join as I2}from"node:path";import{execFile as S2}from"node:child_process";import{promisify as g2}from"node:util";import{processWorkspaceInfo as N6}from"@cerebriline/shared";import G6 from"simple-git";var K6=g2(S2);var w2="shared:cline",P2="CLINE_HUB_DISCOVERY_PATH",T2="hub-production";function R(J=w2){return F0(`${J}@${C()}`)}function H(){return{ownerId:T2,discoveryPath:process.env[P2]?.trim()||I2(D(),"locks","hub","production.json")}}var C0=15000,d2=200,_0=3000,t2=100,a2=[100,250,500,1000,2000],o2="--cline-hub-daemon",r2=3,e2=60000,D0=new Map;function J1(J,j=Date.now()){let Q=D0.get(J);if(!Q||j-Q.windowStartedAt>e2)return D0.set(J,{count:1,windowStartedAt:j}),!0;return Q.count+=1,Q.count<=r2}function j1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function Q1(){try{let J=p2(D(),"logs","hub-daemon.log");return y2(u2(J),{recursive:!0}),{fd:b2(J,"a"),logPath:J}}catch{return}}function Z1(){return S0()==="production"?H():R()}function E(J){return P(J)}function $1(J){try{let j=JSON.parse(h2(`${J}.superseded`,"utf8"));return{url:typeof j.url==="string"?j.url:void 0,authToken:typeof j.authToken==="string"?j.authToken:void 0,pid:typeof j.pid==="number"?j.pid:void 0}}catch{return}}function n(J){try{m2(`${J}.superseded`)}catch{}}function R0(J,j,Q){if(!j||j.url!==Q)return J;return{...J,authToken:J.authToken??j.authToken,pid:J.pid??j.pid}}async function S(J,j){try{return await T(J,{authToken:j})}catch{return}}async function E0(J,j){let Q=Date.now()+j;while(Date.now()<Q){if(!(await S(J))?.url)return!0;await new Promise(($)=>setTimeout($,t2))}return!1}async function d(J,j){if(!J1(J.url))return!1;await g(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Q=await E0(J.url,_0);if(!Q&&J.pid&&X1(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Q=await E0(J.url,_0)}if(Q)await _(j).catch(()=>{return});return Q}function X1(J){try{return process.kill(J,0),!0}catch(j){return j?.code==="EPERM"}}async function z1(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function s(J,j){if(E(J))return"reusable";let Q=await g(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await z1(J)){if(Q)await g(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let Z=await d(J,j);if(!Z&&Q)await g(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return Z?"retired":"failed"}async function V1(J){if(S0()!=="production")return;let j=R();if(j.discoveryPath===J.discoveryPath)return;let Q=await B(j.discoveryPath);if(Q?.url)await d(Q,j.discoveryPath);else await _(j.discoveryPath).catch(()=>{return})}function Y1(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return l2(new URL(`./entry.${J}`,import.meta.url))}function N1(J,j){if(i2(J))return[o2];return[...j&&J.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],J]}function W1(J,j){let Q=Y1(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let $=v2(Z).toLowerCase().includes("bun"),X=N1(Q,$);return{launcher:Z,args:[...X,"--cwd",J,...j1(j),...j.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...s2(process.env),CLINE_NO_INTERACTIVE:"1",[c2]:"1"}}}function G1(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Q="message"in J?J.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function K1(J,j={}){if(n2())return;let Q=W1(J,j),Z=Q1();try{H2(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)k2(Z.fd)}}async function q1(J,j={}){for(let Q=0;;Q++)try{K1(J,j);return}catch(Z){let $=a2[Q];if(!G1(Z)||$===void 0)throw Z;await new Promise((X)=>setTimeout(X,$))}}async function F1(J,j,Q={}){let Z=Q.host!==void 0||Q.port!==void 0||Q.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),$=x0(Q),X=f0($.host,$.port,$.pathname),z=(G)=>{if(!Z)y(G.url,G.authToken);else g0(G.url,G.authToken);return G};await V1(J).catch(()=>{return});let N=await B(J.discoveryPath),Y=N?.url?void 0:$1(J.discoveryPath),W=!1;if(N?.url){let G=N.authToken;if(!G)W=!0,await d(N,J.discoveryPath);else{let K=await S(N.url,G);if(K?.url&&E(K)&&await A(K.url,{authToken:G}))return n(J.discoveryPath),z({url:K.url,authToken:G});if(K?.url){if(await s({...K,authToken:G},J.discoveryPath)==="deferred_busy"&&await A(K.url,{authToken:G}))return z({url:K.url,authToken:G})}else await _(J.discoveryPath).catch(()=>{return})}}let V=await S(X);if(V?.url){let G=R0(V,N??Y,X);if(E(V)){let L=[V.authToken,N?.authToken,Y?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0);for(let M of L){if(!await A(V.url,{authToken:M}))continue;let s0={hubId:V.hubId??`repaired-${V.port}`,protocolVersion:V.protocolVersion,minClientProtocolVersion:V.minClientProtocolVersion,maxClientProtocolVersion:V.maxClientProtocolVersion,capabilities:V.capabilities,coreVersion:V.coreVersion,buildId:V.buildId,authToken:M,host:V.host,port:V.port,url:V.url,pid:V.pid??N?.pid??Y?.pid,startedAt:V.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await L0(J.discoveryPath,s0)}catch{}return n(J.discoveryPath),z({url:V.url,authToken:M})}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.${W?" 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 K=await s(G,J.discoveryPath);if(K==="deferred_busy"){for(let L of[G.authToken,N?.authToken].filter((U)=>typeof U==="string"&&U.trim().length>0))if(await A(V.url,{authToken:L}))return z({url:V.url,authToken:L});if(Q.allowPortFallback!==!0&&$.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(K==="failed"&&Q.allowPortFallback!==!0&&$.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 O=Q.allowPortFallback===!0&&$.port!==0?{...$,port:0}:$;await q1(j,{...O,manageConnectors:Q.manageConnectors});let f=Date.now()+C0;while(Date.now()<f){let G=await B(J.discoveryPath);if(G?.url&&G.authToken){let L=await S(G.url,G.authToken);if(L?.url&&E(L)&&await A(L.url,{authToken:G.authToken}))return n(J.discoveryPath),z({url:L.url,authToken:G.authToken})}let K=await S(X);if(K?.url&&!E(K)){let L=R0(K,G??Y,X),U=await s(L,J.discoveryPath);if(U==="deferred_busy"&&G?.authToken&&await A(K.url,{authToken:G.authToken}))return z({url:K.url,authToken:G.authToken});if(U==="failed"&&Q.allowPortFallback!==!0&&$.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((L)=>setTimeout(L,d2))}throw Error(`Timed out after ${C0}ms waiting for detached hub startup.`)}async function k(J,j={}){let Q=Z1();return await A0(Q.discoveryPath,async()=>F1(Q,J,j))}function U1(){return B1()==="production"?H():R()}function M1(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function y0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((j)=>Buffer.from(j))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return y0(J.data);return String(J)}function x1(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function I0(J){let j=J,Q=x1(j.reason);return new q("hub_connection_closed",j.code||Q?`Hub connection closed (code=${j.code??0}${Q?`, reason=${Q}`:""})`:o,{closeCode:j.code,closeReason:Q||void 0})}function w0(J,j){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Q=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Q)return new q("hub_connect_failed",Q);let Z=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",Z?`Failed to connect to hub at ${j.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${j.toString()}.`)}var a="*",h=8000,C1="cline-hub-auth.",J0=new Map,b0=new Set,_1=3000;var o="Hub connection closed",D1=250,R1=5000,P0=0.5;class q extends Error{code;details;constructor(J,j,Q){super(j);this.code=J;this.details=Q;this.name="HubTransportError"}}function E1(J){return J instanceof q}class r extends Error{command;code;constructor(J,j,Q){super(Q);this.command=J;this.code=j;this.name="HubCommandError"}}function j0(J,j={}){let Q=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Q)return Q;if(j.skipRegistry)return;let Z=m(J.toString());return Z?J0.get(Z):void 0}function S1(J){try{let Q=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function m(J){if(!S1(J))return;let j=new URL(h0(J));return j.search="",j.hash="",j.toString()}function T0(J){let j=m(J);return!!j&&b0.has(j)}function y(J,j){let Q=m(J);if(Q){if(b0.add(Q),j?.trim())J0.set(Q,j)}return J}function g0(J,j){let Q=m(J);if(Q&&j?.trim())J0.set(Q,j)}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",o);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.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(J){if(this.capabilities=J.map((j)=>({...j})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),j=this.options.authToken?.trim()||j0(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",j&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Q=++this.connectGeneration,Z=this.openSocket(J,j,Q),$;this.connectPromise=Z.then(async(z)=>{if($=z,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(x.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Q!==this.connectGeneration||this.closedByClient){try{z.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let X=this.connectPromise;try{await X}catch(z){if(this.connectPromise===X)this.connectPromise=void 0;if($&&this.socket===$){this.lastCloseError=w0(z,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{$.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw z}}async openSocket(J,j,Q){let Z=this.options.resolveConnectionHeaders,$;if(Z){let Y;try{$=await Promise.race([Promise.resolve().then(()=>Z()),new Promise((W,V)=>{Y=setTimeout(()=>{V(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(W){let V=W instanceof q?W:new q("hub_connect_failed",W instanceof Error?W.message:String(W));if(Q===this.connectGeneration)this.lastCloseError=V;throw V}finally{clearTimeout(Y)}}if(Q!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if($&&Object.keys($).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Q===this.connectGeneration)this.lastCloseError=Y;throw Y}let X=$?new f1(J.toString(),{headers:{...$}}):new(M1())(J.toString(),j?[`${C1}${j}`]:void 0);this.socket=X;let z=!1,N=new Promise((Y,W)=>{let V=!1,F=setTimeout(()=>{if(V)return;V=!0,z=!0;let O=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===X)this.lastCloseError=O,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{X.close()}catch{}W(O)},h);X.addEventListener("open",()=>{if(V)return;V=!0,clearTimeout(F),Y()}),X.addEventListener("error",(O)=>{if(V)return;V=!0,clearTimeout(F);let f=w0(O,J);if(this.socket===X)this.lastCloseError=f,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;W(f)}),X.addEventListener("close",(O)=>{if(V)return;V=!0,clearTimeout(F);let f=z?this.lastCloseError:I0(O);if(this.socket===X){if(!z)this.lastCloseError=f,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}W(f)})});return X.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(y0(Y)))}),X.addEventListener("close",(Y)=>{if(this.socket!==X)return;if(!z)this.lastCloseError=I0(Y),this.sawSocketClose=!0;this.registered=!1;for(let W of this.pendingReplies.values())W.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,X}subscribe(J,j){let Q=j?.sessionId?.trim()||void 0,Z={listener:J,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command(J,j,Q,Z){let $=0,X=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,j,Q,Z)}catch(z){if(!X||$>=1||!await this.recoverLocalHubTransport(z))throw z;$+=1}}async commandOnce(J,j,Q,Z,$=!0){if($)await this.connect();Z?.beforeDispatch?.();let X=L1("hubreq_");Z?.onDispatch?.(X);let z=A1(J,Z?.timeoutMs),N=new Promise((W,V)=>{let F=z===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(X))return;V(new r(J,"hub_command_timeout",`Hub command ${J} timed out after ${z}ms (hub=${this.currentUrl}, requestId=${X}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},z);this.pendingReplies.set(X,{resolve:(O)=>{if(F)clearTimeout(F);W(O)},reject:(O)=>{if(F)clearTimeout(F);V(O)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:X,clientId:this.clientId,sessionId:Q,timeoutMs:z,payload:j}})}catch(W){throw this.pendingReplies.delete(X),W}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let W=Q??(typeof j?.sessionId==="string"?j.sessionId:void 0);throw new u(W,Y.error.message)}throw new r(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!T0(this.currentUrl)||!E1(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let j=await H0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!j)return!1;return this.currentUrl=j,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 J=Math.min(D1*2**this.reconnectAttempt,R1),j=Math.round(J*(1-P0)+Math.random()*J*P0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},j)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!T0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await H0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",o);for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.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(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,j){let Q=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(j)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...j?{sessionId:j}:{},...Q!==void 0?{sinceSequence:Q}:{}})}adjustSubscriptionCount(J,j){let Q=this.subscriptionKeyForSessionId(J),Z=(this.subscriptionCounts.get(Q)??0)+j;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(j<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Q,Z),j>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??a}subscriptionSessionIdFromKey(J){return J===a?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let j=J.envelope.requestId;if(!j)return;let Q=this.pendingReplies.get(j);if(!Q)return;this.pendingReplies.delete(j),Q.resolve(J.envelope);return}case"event":{let j=J.envelope.sequence;if(typeof j==="number"){let Q=J.envelope.sessionId?.trim();for(let Z of[a,Q]){if(!Z||!this.subscriptionCounts.has(Z))continue;let $=this.lastEventSequenceByKey.get(Z)??0;if(j>$)this.lastEventSequenceByKey.set(Z,j)}}for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J.envelope.sessionId?.trim())continue;Q.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function h0(J){let j=new URL(J);if(j.protocol==="http:")j.protocol="ws:";else if(j.protocol==="https:")j.protocol="wss:";return j.toString()}async function A(J,j){let Q=new Q0({url:J,authToken:j?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:j?.workspaceRoot,cwd:j?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function e(J,j){let Q=h0(J),Z=await T(Q,{authToken:j?.authToken});if(!Z)return{status:"unreachable",url:Q};if(j?.requireCurrentBuild){let $=C(),X=w(Z,$);if(!X.compatible&&!P(Z))return{status:X.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Q}}else if(!O1(Z).compatible)return{status:"protocol_mismatch",url:Q};if(j?.verifyConnection===!0&&!await A(Q,{workspaceRoot:j.workspaceRoot,cwd:j.cwd,authToken:j.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}function g1(J){let j=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Q=0,Z=new Set;for(let $ of j){if(!$||typeof $!=="object")continue;let X=$.participants;if(!Array.isArray(X)||X.length===0)continue;Q+=1;for(let z of X){let N=z&&typeof z==="object"?z.clientId:void 0;if(typeof N==="string"&&N.trim())Z.add(N)}}return{activeSessionCount:Q,participantClientCount:Z.size}}async function t(J,j,Q){let Z=new Q0({url:J,authToken:j,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let $=await Z.command("session.list",{limit:500},void 0,{timeoutMs:_1});return g1($.payload)}finally{await Z.dispose().catch(()=>{return})}}async function I1(J,j,Q){try{return(await t(J,j,Q)).activeSessionCount===0}catch{return!1}}async function w1(J,j){let Q=`${J.discoveryPath}.superseded`,Z=await B(Q);if(!Z?.url||!Z.authToken)return;let $=await e(Z.url,{authToken:Z.authToken});if($.status!=="compatible")return;if(await I1($.url,Z.authToken,j))return;return y($.url,Z.authToken)}async function P1(J={}){if(J.endpoint?.trim()){let $=await e(J.endpoint);return $.status==="compatible"?$.url:void 0}let j=U1(),Q=await B(j.discoveryPath);if(!Q?.url)return await w1(j,J);let Z=await e(Q.url,{authToken:Q.authToken,requireCurrentBuild:!0});if(Z.status==="compatible")return y(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await _(j.discoveryPath).catch(()=>{return});return}async function H0(J={}){let j=await P1(J);if(j&&await A(j,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return j;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch(Q){J.onStartupError?.(Q);return}}async function g(J,j,Q,Z){k0();let $=new URL(J),X=j?.trim()||j0($);if($.protocol==="ws:")$.protocol="http:";else if($.protocol==="wss:")$.protocol="https:";if($.pathname="/drain",$.hash="",Q)$.searchParams.set("reason",Q);if(Z?.off)$.searchParams.set("off","1");return(await fetch($,{method:"POST",headers:X?{authorization:`Bearer ${X}`}:void 0})).ok}async function b(J,j){k0();let Q=new URL(J),Z=j?.trim()||j0(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}import{spawn as T1}from"node:child_process";import{userInfo as H1}from"node:os";import{basename as k1,delimiter as v}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",v0="__CLINE_SIDECAR_PATH_END__",u0=5000,y1=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${v0}"'`,m0="CLINE_SIDECAR_SKIP_SHELL_PATH";function p0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function b1(J,j){try{let Q=H1().shell?.trim();if(Q)return Q}catch{}return j.SHELL?.trim()||p0(J)}function h1(J,j){let Q=k1(J);if(Q==="csh"||Q==="tcsh")return{args:["-c",j],argv0:`-${Q}`};return{args:["-i","-l","-c",j]}}function m1(J){let j=J.indexOf(Z0);if(j===-1)return;let Q=J.indexOf(v0,j);if(Q===-1)return;let Z=J.slice(j+Z0.length,Q).trim();return Z.length>0?Z:void 0}function v1(J,j){let Q=[...J.split(v),...j.split(v)].map((Z)=>Z.trim()).filter((Z)=>Z.length>0);return Array.from(new Set(Q)).join(v)}function u1(J,j=u0){return new Promise((Q)=>{let Z=h1(J,y1),$=T1(J,Z.args,{argv0:Z.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),X="",z=0,N=()=>{try{if($.pid)process.kill(-$.pid,"SIGKILL")}catch{$.kill("SIGKILL")}},Y=!1,W=(F)=>{if(Y)return;Y=!0,clearTimeout(V),$.stdout?.destroy(),N(),Q(F)},V=setTimeout(()=>{try{if($.pid)process.kill(-$.pid,"SIGKILL")}catch{$.kill("SIGKILL")}W(void 0)},j);$.stdout?.on("data",(F)=>{if(Y)return;if(z+=F.length,z>65536){W(void 0);return}X+=F.toString("utf8")}),$.on("error",()=>W(void 0)),$.on("close",()=>W(m1(X)))})}async function l0(J){let j=J?.platform??process.platform,Q=J?.env??process.env;if(j==="win32")return{status:"skipped",reason:"windows"};if(Q[m0]?.trim())return{status:"skipped",reason:m0};let Z=J?.userShell??b1(j,Q),$=J?.fallbackShell??p0(j),X=J?.timeoutMs??u0,z=Z===$?[[Z,X]]:[[Z,X],[$,X/2]];for(let[N,Y]of z){let W=await u1(N,Y);if(!W)continue;let V=v1(W,Q.PATH??"");return Q.PATH=V,{status:"applied",pathEntries:V.split(v).length,shell:N}}return{status:"failed",shell:Z}}var c0={readHubDiscovery:B,clearHubDiscoveryIfOwned:O0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:l1,loadHubDaemon:()=>import("@cerebriline/core/hub/daemon-entry"),ensureLoginShellPath:l0,setHomeDirIfUnset:c1,homeDir:p1,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function i0(J,j){let Q=J.indexOf(j);return(Q>=0?J[Q+1]:void 0)?.trim()||void 0}function n0(J,j){let Q=i0(J,"--discovery-path");if(!Q)throw Error("--discovery-path is required for remote Hub management");return j.env.CLINE_HUB_DISCOVERY_PATH=Q,Q}async function i1(J=process.argv,j=c0){j.setHomeDirIfUnset(j.homeDir()),await j.ensureLoginShellPath();let Q=i0(J,"--cwd")??j.cwd();n0(J,j);let Z=await j.ensureDetachedHubServer(Q,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});j.writeOutput(`${JSON.stringify({...Z,cwd:Q,platform:process.platform,arch:process.arch})}
4
4
  `)}async function d6(J=process.argv,j=c0){if(J.includes("--remote-hub-stop")){let Q=n0(J,j),Z=await j.readHubDiscovery(Q);if(Z&&typeof Z.pid==="number"&&Number.isInteger(Z.pid)&&Z.pid>0)try{j.probeProcess(Z.pid)}catch($){if($?.code==="ESRCH")return await j.clearHubDiscoveryIfOwned(Q,Z.hubId),!0}if(Z&&!await j.requestHubShutdown(Z.url,Z.authToken))throw Error("Remote Hub shutdown failed");return!0}if(J.includes("--remote-hub-ensure"))return await i1(J,j),!0;if(j.claimHubDaemonProcess())return await j.loadHubDaemon(),!0;return!1}export{i1 as runRemoteHubEnsure,d6 as runRemoteHelperEntrypoint};
@@ -5,6 +5,7 @@ import type { ConfiguredAgentDelegationResult, ConfiguredAgentSummary } from "..
5
5
  import type { HookEventPayload } from "../../hooks";
6
6
  import type { CheckpointEntry } from "../../hooks/checkpoint-hooks";
7
7
  import type { ProviderSettings } from "../../services/llms/provider-settings";
8
+ import type { ResolvedSessionConfig } from "../../services/resolved-session-config";
8
9
  import type { SessionCompactionState } from "../../session/models/session-compaction";
9
10
  import type { SessionManifest } from "../../session/models/session-manifest";
10
11
  import type { SessionSource } from "../../types/common";
@@ -100,6 +101,11 @@ export interface StartSessionResult {
100
101
  manifestPath: string;
101
102
  messagesPath: string;
102
103
  result?: AgentResult;
104
+ /**
105
+ * What the session was built with. Present for a session that runs in
106
+ * this process; a hub or remote runtime does not send it back.
107
+ */
108
+ resolvedConfig?: ResolvedSessionConfig;
103
109
  }
104
110
  export interface SendSessionInput {
105
111
  sessionId: string;
@@ -8,6 +8,7 @@ import type { RuntimeBuilderInput } from "../runtime/orchestration/session-runti
8
8
  import type { SessionHistoryOriginMetadata } from "../session/history-origin";
9
9
  import type { CoreSessionConfig } from "../types/config";
10
10
  import { type ProviderConfig } from "../types/provider-settings";
11
+ import { type ResolvedSessionConfig } from "./resolved-session-config";
11
12
  import type { ProviderSettingsManager } from "./storage/provider-settings-manager";
12
13
  import type { GitWorkspaceState } from "./workspace/workspace-manifest";
13
14
  export interface PrepareLocalRuntimeBootstrapOptions {
@@ -55,6 +56,8 @@ export interface LocalRuntimeBootstrap {
55
56
  effectiveInput: ResolvedStartSessionInput;
56
57
  config: CoreSessionConfig;
57
58
  providerConfig: ProviderConfig;
59
+ /** What the session was built with, as a report. */
60
+ resolvedConfig: ResolvedSessionConfig;
58
61
  workspaceMetadata: string;
59
62
  /** Structured git + path metadata generated alongside workspaceMetadata. */
60
63
  workspaceInfo: WorkspaceInfo;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * What a session was actually built with, for a host that has to prove it.
3
+ *
4
+ * A session's settings come from several places: what the host passed, a
5
+ * provider profile stored in the data directory, the model catalog and the
6
+ * defaults. A harness that passes a sampler and a context window has had no
7
+ * way to learn whether those are what the session ended up with: a stored
8
+ * profile is merged underneath, and a run can inherit a number from the one
9
+ * before it. This is the answer, as data, before the first request is sent.
10
+ *
11
+ * It is a report and holds nothing live: no functions, and no secrets. A key,
12
+ * a token or a header's value is replaced by the word that it was there.
13
+ */
14
+ import type { ProviderConfig } from "../types/provider-settings";
15
+ export interface ResolvedSessionConfig {
16
+ sessionId: string;
17
+ providerId: string;
18
+ modelId: string;
19
+ baseUrl?: string;
20
+ /** The window the session sizes itself against, and sends where a server takes one. */
21
+ contextWindow?: number;
22
+ /** The cap on one reply. */
23
+ maxOutputTokens?: number;
24
+ thinking: {
25
+ enabled?: boolean;
26
+ effort?: string;
27
+ budgetTokens?: number;
28
+ };
29
+ /** The sampler the session sends. Absent: the model's own. */
30
+ sampling?: Record<string, unknown>;
31
+ /** The provider configuration, with secrets and live objects removed. */
32
+ provider: Record<string, unknown>;
33
+ /** The session's own settings, the same way. */
34
+ session: Record<string, unknown>;
35
+ /** The system prompt as the model will be given it. */
36
+ systemPrompt?: string;
37
+ sources: {
38
+ /**
39
+ * `merged`: a stored profile for this provider was found and laid under
40
+ * what the host passed. `ignored`: the host asked for it to be left out.
41
+ * `absent`: there was none.
42
+ */
43
+ storedProviderSettings: "merged" | "ignored" | "absent";
44
+ /**
45
+ * The provider fields whose value came from the stored profile: the host
46
+ * did not set them and the session has them. Empty when nothing was
47
+ * inherited, which is what an isolated run should see.
48
+ */
49
+ inheritedFromStoredProfile: string[];
50
+ dataDir: string;
51
+ providerSettingsPath: string;
52
+ globalSettingsPath: string;
53
+ /** Whether a global settings file exists. Core reads it for more than providers. */
54
+ globalSettingsPresent: boolean;
55
+ };
56
+ }
57
+ /** A copy that can be written as JSON and shown to anyone. */
58
+ export declare function toReportValue(value: unknown, key?: string, depth?: number): unknown;
59
+ /**
60
+ * The provider fields that differ between the configuration built with the
61
+ * stored profile and the one built without it: what the profile contributed.
62
+ */
63
+ export declare function fieldsInheritedFromStoredProfile(withStored: ProviderConfig, withoutStored: ProviderConfig): string[];
@@ -9,6 +9,7 @@ import type { AgentProfileConnection, AgentProviderConnection, TeamEvent } from
9
9
  import type { CheckApprover } from "../runtime/atomic/proposal";
10
10
  import type { EscalationApproval } from "../runtime/escalation/escalation-session";
11
11
  import type { StruggleThresholds } from "../runtime/safety/struggle-detector";
12
+ import type { ResolvedSessionConfig } from "../services/resolved-session-config";
12
13
  import type { ProviderConfig } from "./provider-settings";
13
14
  export type CoreAgentMode = AgentMode;
14
15
  export interface CoreModelConfig {
@@ -734,6 +735,42 @@ export interface CoreSessionConfig extends CoreModelConfig, CoreRuntimeFeatures,
734
735
  * transcript/tool/hook context.
735
736
  */
736
737
  sessionId?: string;
738
+ /**
739
+ * The context window this session runs in, in tokens.
740
+ *
741
+ * It is what the session sizes compaction and its output budget against,
742
+ * and what is sent as `num_ctx` to a server that takes one. Without it the
743
+ * window is the stored profile's, then the one the model declares, then the
744
+ * catalog's. A host that has to control the window had no field for it:
745
+ * the CLI wrote it into the model catalog entry it passed along.
746
+ */
747
+ contextWindow?: number;
748
+ /**
749
+ * What to do with the provider profile stored in the data directory.
750
+ *
751
+ * `merge` (the default) lays it under what this configuration says, so a
752
+ * key, a base URL, a sampler or an output budget saved earlier applies to
753
+ * this session too. `ignore` builds the session from this configuration
754
+ * alone: what is not passed here is absent. A harness wants `ignore`, or
755
+ * one run inherits the numbers of another.
756
+ *
757
+ * Provider settings only. The global settings file (which built-in skills
758
+ * are on, which plugins are off) is still read; `onConfigResolved` reports
759
+ * where it is and whether it exists.
760
+ */
761
+ storedProviderSettings?: "merge" | "ignore";
762
+ /**
763
+ * Called once the session's configuration is final, before its first
764
+ * request is sent. See `ResolvedSessionConfig`.
765
+ *
766
+ * Awaited. Throwing from it stops the session from starting, which is how
767
+ * a host refuses to run on a configuration that is not the one it asked
768
+ * for.
769
+ *
770
+ * Called for a session that runs in this process. A hub or remote runtime
771
+ * builds the session elsewhere and a function does not travel there.
772
+ */
773
+ onConfigResolved?: (resolved: ResolvedSessionConfig) => void | Promise<void>;
737
774
  /**
738
775
  * Turn images into text with a second model, so the session's model never
739
776
  * sees one. See `AgentConfig.describeImages`.
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.249",
4
+ "version": "4.100.250",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/mann1x/cline.git",
@@ -81,9 +81,9 @@
81
81
  "ws": "^8.20.0",
82
82
  "yaml": "^2.8.2",
83
83
  "zod": "^4.3.6",
84
- "@cerebriline/agents": "4.100.249",
85
- "@cerebriline/llms": "4.100.249",
86
- "@cerebriline/shared": "4.100.249"
84
+ "@cerebriline/agents": "4.100.250",
85
+ "@cerebriline/llms": "4.100.250",
86
+ "@cerebriline/shared": "4.100.250"
87
87
  },
88
88
  "peerDependencies": {
89
89
  "posthog-node": "^5.8.0"