@toloka-platform/sdk 0.12.1 → 0.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/toloka.js +2 -2
- package/dist/cli/toloka.js.jsc +0 -0
- package/dist/cli/toloka.js.jsc.sha256 +1 -1
- package/dist/cli/toloka.js.sha256 +1 -1
- package/openapi/gen/models/datasetExportReportTokensEstimatorVersion.ts +1 -1
- package/openapi/gen/models/trainingCostEstimateOneOfInputsTrainingReportAnyOfTokensEstimatorVersion.ts +1 -1
- package/openapi/gen/models/trainingCostEstimateOneOfInputsValidationAnyOfReportAnyOfTokensEstimatorVersion.ts +1 -1
- package/openapi/gen/models/trainingCostEstimateOneOfTwosevenInputsTrainingReportAnyOfTokensEstimatorVersion.ts +1 -1
- package/openapi/gen/models/trainingCostEstimateOneOfTwosevenInputsValidationAnyOfReportAnyOfTokensEstimatorVersion.ts +1 -1
- package/openapi/gen/models/trainingRunInputsAnyOfTrainingReportTokensEstimatorVersion.ts +1 -1
- package/openapi/gen/models/trainingRunInputsAnyOfValidationAnyOfReportTokensEstimatorVersion.ts +1 -1
- package/openapi/gen/models/trainingRunQuoteInputsTrainingReportAnyOfTokensEstimatorVersion.ts +1 -1
- package/openapi/gen/models/trainingRunQuoteInputsValidationAnyOfReportAnyOfTokensEstimatorVersion.ts +1 -1
- package/package.json +2 -2
- package/skills/catalog.json +7 -7
- package/skills/toloka-fine-tuning/SKILL.md +2 -1
- package/skills/toloka-gisting/SKILL.md +3 -2
package/dist/cli/toloka.js
CHANGED
|
@@ -36,7 +36,7 @@ Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,(o)=>{l
|
|
|
36
36
|
`);for(let s=n;s<r.length;s++){let a=r[s];if(a.length>1024)continue;let l=Ou.test(a)?a.replace(Ou,"$1"):a;if(!l.match(/\S*Error: /)){for(let g of t){let d=g(l,e);if(d){o.push(d);break}}if(o.length>=Uu)break}}return Ju(o)}}class zu{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let i=kt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return mi(e,"DOMException")}isDOMError(e){return mi(e,"DOMError")}}class zr{match(e){return du(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let i=e.message;if(i.error&&typeof i.error.message=="string")return String(i.error.message);return String(i)}getStack(e){return e.stacktrace||e.stack||void 0}}class Du{constructor(){}match(e){return cu(e)&&e.error!=null}coerce(e,t){let i=t.apply(e.error);if(!i)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return i}}var HR=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Dr{match(e){return typeof e=="string"}coerce(e,t){let[i,n]=this.getInfos(e);return{type:i??"Error",value:n??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",i=e,n=e.match(HR);if(n)t=n[1],i=n[2];return[t,i]}}var _u=["fatal","error","warning","log","info","debug"];function _r(e,t=40){let i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(let n=i.length;n>0;n--){let o=i.slice(0,n).join(", ");if(!(o.length>t)){if(n===i.length)return o;return o.length<=t?o:`${o.slice(0,t)}...`}}return""}class Qr{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let i=this.getErrorPropertyFromObject(e);if(i)return t.apply(i);return{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return en(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let n=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")n+=` with message: '${e.message}'`;return n}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),i=_r(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return kt(e)&&!au(e)&&_u.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(ku(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class Qu{match(e){return en(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${_r(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class Kr{match(e){return Pr(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class Ku{match(e){return mi(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!en(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let i=this.getUnhandledRejectionReason(e);if(Pr(i))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}class Lu{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t===void 0)return;return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){while(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;if(e)this._cache.delete(e)}}}var mo={MESSAGE:"$message",TIMESTAMP:"$timestamp"},kR=new Set([mo.MESSAGE,mo.TIMESTAMP]),Lr={enabled:!0,max_bytes:32768};function cl(e){if(!e)return{...Lr};return{enabled:e.enabled??Lr.enabled,max_bytes:PR(e.max_bytes,Lr.max_bytes)}}function vR(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,o)=>{if(kR.has(o))return t.push(o),n;return n[o]=e[o],n},{}),droppedKeys:t}}class Mu{constructor(e){this._entries=[],this._totalBytes=0,this._config=cl(e)}setConfig(e){this._config=cl(e),this._trimToMaxBytes()}add(e){let t=NR(e);if(!t)return;let i=$u(t.json);if(i>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,this._trimToMaxBytes()}getAttachable(){return this._entries.map((e)=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let e=this._entries.shift();if(e)this._totalBytes-=e.bytes}}}function PR(e,t){if(!lo(e)||e===1/0||e===-1/0)return t;let i=Math.floor(e);if(i<0)return t;return i}function NR(e){let t;try{t=qi(e)}catch{return}try{let i=JSON.parse(t);if(!ao(i))return;let n=i,o=n[mo.MESSAGE],r=n[mo.TIMESTAMP];if(!kt(o)||o.trim().length===0)return;if(!kt(r)&&!lo(r))return;return{step:n,json:t}}catch{return}}function $u(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),i=0;for(let n=0;n<t.length;n++)if(t[n]==="%")i+=1,n+=2;else i+=1;return i}class Jt extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class pi extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var tm=(e,t)=>{for(let i of Object.keys(t))if(i.startsWith("$feature/")||i==="$active_feature_flags")e[i]=t[i]};async function qu(e){if(e instanceof Jt){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function SR(e){return typeof e=="object"&&(e instanceof Jt||im(e))}function im(e){return e instanceof pi}function xR(e){if(e instanceof Jt)return e.status===502||e.status===504;if(!(e instanceof pi))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function on(e){return typeof e=="object"&&e instanceof Jt&&e.status===413}function Co(e){if(e instanceof Jt)return e.status===408||e.status===429||e.status>=500;return im(e)}function em(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Il="default";class Mr{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Jr([new zr,new Qr,new Dr,new Kr],dl())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Qa,this._events=new al,this._isInitialized=!1;let i=typeof e=="string"?e.trim():"",n=typeof t.host=="string"?t.host.trim():"",o=!i;if(this._logger=Au("[PostHog]",this.logMsgIfDebug.bind(this)),o)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=i,this.host=Fu(n||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1000),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3000,retryCheck:Co},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3000,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||o,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!Da()||(t?.disableCompression??!1)}logMsgIfDebug(e){if(this.isDebug)e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(Je.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Je.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Je.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},i={...t,...this.getCommonEventProperties()};if(tm(i,t),e.event==="$feature_flag_called"&&i.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())i=ro(i);return{distinct_id:e.distinct_id,event:e.event,properties:i}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(e,t,i){let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",n,i)}captureStateless(e,t,i,n){this.wrap(()=>{let o=this.buildPayload({distinct_id:e,event:t,properties:i});this.enqueue("capture",o,n)})}async captureStatelessImmediate(e,t,i,n){let o=this.buildPayload({distinct_id:e,event:t,properties:i});await this.sendImmediate("capture",o,n)}aliasStateless(e,t,i,n){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});this.enqueue("alias",o,n)})}async aliasStatelessImmediate(e,t,i,n){let o=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",o,n)}groupIdentifyStateless(e,t,i,n,o,r){this.wrap(()=>{let s=this.buildPayload({distinct_id:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...r||{}}});this.enqueue("capture",s,n)})}async groupIdentifyStatelessImmediate(e,t,i,n,o,r){let s=this.buildPayload({distinct_id:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...r||{}}});await this.sendImmediate("capture",s,n)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((n)=>n.json()).catch((n)=>{this._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(e,t={},i={},n={},o={},r=!1){await this._initPromise;let s=r?"&config=true":"",a=`${this.host}/flags/?v=2${s}`,l={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:n,...o};if(i.$device_id)l.$device_id=i.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)l.evaluation_contexts=this.evaluationContexts;let g={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,g,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:xR},this.featureFlagsRequestTimeoutMs).then((d)=>d.json()).then((d)=>({success:!0,response:za(d)})).catch((d)=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(e){if(e instanceof Jt)return{type:"api_error",statusCode:e.status};if(e instanceof pi){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,i={},n={},o={},r){await this._initPromise;let s=await this.getFeatureFlagDetailStateless(e,t,i,n,o,r);if(s===void 0)return{response:void 0,requestId:void 0};let a=oo(s.response);if(a===void 0)a=!1;return{response:a,requestId:s.requestId}}async getFeatureFlagDetailStateless(e,t,i={},n={},o={},r){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(t,i,n,o,r,[e]);if(s===void 0)return;return{response:s.flags[e],requestId:s.requestId,evaluatedAt:s.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,i={},n={},o={},r){await this._initPromise;let s=await this.getFeatureFlagPayloadsStateless(t,i,n,o,r,[e]);if(!s)return;let a=s[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},i={},n={},o,r){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,o,r)).payloads}async getFeatureFlagsStateless(e,t={},i={},n={},o,r){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,o,r)}async getFeatureFlagsAndPayloadsStateless(e,t={},i={},n={},o,r){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(e,t,i,n,o,r);if(!s)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:s.featureFlags,payloads:s.featureFlagPayloads,requestId:s.requestId}}async getFeatureFlagDetailsStateless(e,t={},i={},n={},o,r){await this._initPromise;let s={geoip_disable:o??this.disableGeoip};if(r)s.flag_keys_to_evaluate=r;let a=await this.getFlags(e,t,i,n,s);if(!a.success)return;let l=a.response;if(l.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(l.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited};return l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(e,t).then((o)=>{if(o.status!==200||!o.json){let r=`Surveys API could not be loaded: ${o.status}`,s=Error(r);this._logger.error(s),this._events.emit("error",Error(r));return}return o.json()}).catch((o)=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;if(n)this._logger.info("Surveys fetched from API: ",JSON.stringify(n));return n??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Je.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Je.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Je.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Il}persistedQueueKeyForRoute(e){return Je.Queue}getActiveQueueRoutes(){return[Il]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);let o=this.persistedQueueKeyForRoute(this.getQueueRouteKey(n)),r=this.getPersistedProperty(o)||[];if(r.length>=this.maxQueueSize)r.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(r.push({message:n}),this.setPersistedProperty(o,r),this._events.emit(e,n),r.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=We(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);try{await this.sendBatch([n],void 0,this.getQueueRouteKey(n))}catch(o){this._events.emit("error",o)}}normalizeMessage(e){let{type:t,library:i,library_version:n,...o}=e,r=em(o.properties)?o.properties:void 0;if(i!==void 0&&r?.$lib===void 0)r={...r||{},$lib:i};if(n!==void 0&&r?.$lib_version===void 0)r={...r||{},$lib_version:n};if(r)o.properties=r;return o.uuid=Er(o.uuid,je),o}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:el(),uuid:Er(t?.uuid,je)};if(t?.disableGeoip??this.disableGeoip){if(!em(i.properties))i.properties={};i.properties.$geoip_disable=!0}if(i.distinctId)i.distinct_id=i.distinctId,delete i.distinctId;return i}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await qu(e)})}async waitForPendingPromises(e,t=[]){let i=t.filter((o)=>!!o),n=0;while(!0){let o=this.promiseQueue.getPromises([...i,...this.flushPromises],e);if(o.length===0)return;if(n>0)this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`);await Promise.all(o.map((r)=>r.catch(()=>{}))),n++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,i=this.promiseQueue.maxId,n=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(i,[t,n])}).then(()=>tl([t])).then(()=>{if(this.pendingFlushPromise===n)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=n,this.flushPromise=n,this.flushPromises.add(n),this.addPendingPromise(n),tl([n]).then(()=>{if(this.flushPromises.delete(n),this.pendingFlushPromise===n)this.pendingFlushPromise=null;if(this.flushPromise===n)this.flushPromise=null}),n}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,i=Il){let n={api_key:this.apiKey,batch:e,sent_at:el()};if(this.historicalMigration)n.historical_migration=!0;let o=qi(n),r=`${this.host}/batch/`,s=this.disableCompression?null:await Ii(o,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...s!==null&&{"Content-Encoding":"gzip"}},body:s||o};await(await this.fetchWithRetry(r,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((n)=>this.getRouteQueue(n).length>0))return;let t=[],i;for(let n of e)try{await this._flushRoute(n,t)}catch(o){if(i===void 0)i=o}if(i!==void 0)throw i;this._events.emit("flush",t)}async _flushRoute(e,t){let i=this.persistedQueueKeyForRoute(e),n=this.getPersistedProperty(i)||[];if(!n.length)return;let o=n.length,r=0;while(n.length>0&&r<o){let s=n.slice(0,this.maxBatchSize),a=s.map((d)=>d.message===void 0?d.message:this.normalizeMessage(d.message)),l=async()=>{let c=(this.getPersistedProperty(i)||[]).slice(s.length);this.setPersistedProperty(i,c),n=c,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},g={retryCheck:(d)=>{if(on(d))return!1;return Co(d)}};try{await this.sendBatch(a,g,e)}catch(d){if(on(d)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(d instanceof pi))await l();throw this._events.emit("error",d),d}await l(),t.push(...a),r+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await Ii(t,this.isDebug),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,o,{retryCheck:(r)=>{if(on(r))return!1;return Co(r)}}),{kind:"ok"}}catch(r){if(on(r))return{kind:"too-large"};if(r instanceof pi)return{kind:"retry-later",error:r};return{kind:"fatal",error:r}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await Ii(t,this.isDebug),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,o,{retryCheck:(r)=>{if(on(r))return!1;return Co(r)}}),{kind:"ok"}}catch(r){if(on(r))return{kind:"too-large"};if(Co(r))return{kind:"retry-later",error:r};return{kind:"fatal",error:r}}}async fetchWithRetry(e,t,i,n){let o=t.body?t.body:"",r=-1;try{r=o instanceof Blob?o.size:Buffer.byteLength(o,wu)}catch{if(o instanceof Blob)r=o.size;else r=new TextEncoder().encode(o).length}return await Hu(async()=>{let s=new AbortController,a=n??this.requestTimeout,l=We(()=>s.abort(),a),g=null;try{g=await this.fetch(e,{signal:s.signal,...t})}catch(c){throw new pi(c)}finally{clearTimeout(l)}if(t.mode!=="no-cors"&&(g.status<200||g.status>=400))throw new Jt(g,r);return g},{...this._retryOptions,...i})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let i=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((s)=>this.getRouteQueue(s).length>0))break;let r=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===r){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(o){if(!SR(o))throw o;await qu(o)}},n;try{return await Promise.race([new Promise((o,r)=>{n=We(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,r("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),i()])}finally{clearTimeout(n)}}async shutdown(e=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var rm=require("fs"),sm=require("readline"),$r=new Ye.ReduceableCache(25),am=new Ye.ReduceableCache(20),ul=7,OR=1000,UR=1e4;async function lm(e){let t={};for(let o=e.length-1;o>=0;o--){let r=e[o],s=r?.filename;if(!r||typeof s!="string"||typeof r.lineno!="number"||DR(s)||_R(r))continue;if(!t[s])t[s]=[];t[s].push(r.lineno)}let i=Object.keys(t);if(i.length==0)return e;let n=[];for(let o of i){if(am.get(o))continue;let r=t[o];if(!r)continue;r.sort((l,g)=>l-g);let s=KR(r);if(s.every((l)=>QR(o,l)))continue;let a=LR($r,o,{});n.push(JR(o,s,a))}if(await Promise.all(n).catch(()=>{}),e&&e.length>0)jR(e,$r);return $r.reduce(),e}function JR(e,t,i){return new Promise((n)=>{let o=rm.createReadStream(e),r=sm.createInterface({input:o});function s(){o.destroy(),n()}let a=0,l=0,g=t[l];if(g===void 0)return void s();let d=g[0],c=g[1];function u(){am.set(e,1),r.close(),r.removeAllListeners(),s()}o.on("error",u),r.on("error",u),r.on("close",s),r.on("line",(C)=>{if(a++,a<d)return;if(i[a]=MR(C,0),a>=c){if(l===t.length-1){r.close(),r.removeAllListeners();return}l++;let p=t[l];if(p===void 0){r.close(),r.removeAllListeners();return}d=p[0],c=p[1]}})})}function jR(e,t){for(let i of e)if(i.filename&&i.context_line===void 0&&typeof i.lineno=="number"){let n=t.get(i.filename);if(n===void 0)continue;zR(i.lineno,i,n)}}function zR(e,t,i){if(t.lineno===void 0||i===void 0)return;t.pre_context=[];for(let o=gm(e);o<e;o++){let r=i[o];if(r===void 0)return void nm(t);t.pre_context.push(r)}if(i[e]===void 0)return void nm(t);t.context_line=i[e];let n=dm(e);t.post_context=[];for(let o=e+1;o<=n;o++){let r=i[o];if(r===void 0)break;t.post_context.push(r)}}function nm(e){delete e.pre_context,delete e.context_line,delete e.post_context}function DR(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function _R(e){if(e.lineno!==void 0&&e.lineno>UR)return!0;if(e.colno!==void 0&&e.colno>OR)return!0;return!1}function QR(e,t){let i=$r.get(e);if(i===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(i[n]===void 0)return!1;return!0}function KR(e){if(!e.length)return[];let t=0,i=e[0];if(typeof i!="number")return[];let n=om(i),o=[];while(!0){if(t===e.length-1){o.push(n);break}let r=e[t+1];if(typeof r!="number")break;if(r<=n[1])n[1]=r+ul;else o.push(n),n=om(r);t++}return o}function om(e){return[gm(e),dm(e)]}function gm(e){return Math.max(1,e-ul)}function dm(e){return e+ul}function LR(e,t,i){let n=e.get(t);if(n===void 0)return e.set(t,i),i;return n}function MR(e,t){let i=e,n=i.length;if(n<=150)return i;if(t>n)t=n;let o=Math.max(t-60,0);if(o<5)o=0;let r=Math.min(o+140,n);if(r>n-5)r=n;if(r===n)o=Math.max(r-140,0);if(i=i.slice(o,r),o>0)i=`...${i}`;if(r<n)i+="...";return i}var rn=require("path");function cm(e=process.cwd()){let t=rn.sep==="\\",i=(o)=>t?o.replace(/\\/g,"/"):o,n=i(e);return async(o)=>{for(let r of o)if(!(!r.filename||r.filename.startsWith("node:")||r.filename.startsWith("data:"))){if(rn.isAbsolute(r.filename))r.filename=i(rn.relative(n,i(r.filename)))}return o}}var Im="5.46.1";var vt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Ai{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!t)return;if(!t.enabled)return!1;return t.variant??!0}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let i=this._flags[t];if(i)e[t]=i}return this._cloneWith(e)}only(e){let t={},i=[];for(let n of e){let o=this._flags[n];if(o)t[n]=o;else i.push(n)}if(i.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${i.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[i,n]of Object.entries(this._flags)){let o=n.enabled===!1?!1:n.variant??!0;if(e[`$feature/${i}`]=o,n.enabled)t.push(i)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Ai({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId==="")return;if(this._isSlice&&!(e in this._flags))return;let t=this._flags[e],i=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,n={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:i,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)n.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)n.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let o=[];if(this._errorsWhileComputing)o.push(vt.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)o.push(vt.QUOTA_LIMITED);if(t===void 0)o.push(vt.FLAG_MISSING);if(o.length>0)n.$feature_flag_error=o.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:n})}}async function um(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let i=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map((o)=>o.toString(16).padStart(2,"0")).join("")}var $R=60000,qR=1152921504606847000,e0=["is_not","is_set"];class sn extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,sn.prototype)}}function Am(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class U extends Error{constructor(e){super(e);Am(this,U)}}class At extends Error{constructor(e){super(e);Am(this,At)}}class ml{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:i,timeout:n,host:o,customHeaders:r,...s}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=o,this.poller=void 0,this.fetch=s.fetch||fetch,this.onError=s.onError,this.customHeaders=r,this.onLoad=s.onLoad,this.onMinimalFlagCalledEvents=s.onMinimalFlagCalledEvents,this.cacheProvider=s.cacheProvider,this.strictLocalEvaluation=s.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},i={},n={},o={}){return{distinctId:e,groups:t,personProperties:i,groupProperties:n,evaluationCache:o}}async getFeatureFlag(e,t,i={},n={},o={}){await this.loadFeatureFlags();let r,s;if(!this.loadedSuccessfullyOnce)return r;if(s=this.featureFlagsByKey[e],s!==void 0){let a=this.createEvaluationContext(t,i,n,o);try{r=(await this.computeFlagAndPayloadLocally(s,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${r}`))}catch(l){if(l instanceof At||l instanceof U)this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${e}: ${l.message}`));else if(l instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${l}`))}}return r}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let i={},n={},o=this.featureFlags.length==0,r=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,s={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(r.map(async(a)=>{try{let{value:l,payload:g}=await this.computeFlagAndPayloadLocally(a,s);if(i[a.key]=l,g)n[a.key]=g}catch(l){if(l instanceof At||l instanceof U)this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${a.key}: ${l.message}`));else if(l instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${l}`));o=!0}})),{response:i,payloads:n,fallbackToFlags:o}}async computeFlagAndPayloadLocally(e,t,i={}){let{matchValue:n,skipLoadCheck:o=!1}=i;if(!o)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let r;r=n!==void 0?n:await this.computeFlagValueLocally(e,t);let s=this.getFeatureFlagPayload(e.key,r);return{value:r,payload:s}}async computeFlagValueLocally(e,t){let{distinctId:i,groups:n,personProperties:o,groupProperties:r}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new U("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let l=this.groupTypeMapping[String(a)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new U("Flag has unknown group type index");if(!(l in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let g=r[l];return await this.matchFeatureFlagProperties(e,n[l],g,t)}{let l=this.getBucketingValueForFlag(e,i,o);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new U(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,l,o,t)}}getBucketingValueForFlag(e,t,i){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let n=i?.$device_id;if(n==null||n==="")return;return n}return t}getFeatureFlagPayload(e,t){let i=null;if(t!==!1&&t!=null){if(typeof t=="boolean")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(i!=null){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}}return null}async evaluateFlagDependency(e,t,i){let{evaluationCache:n}=i,o=e.key;if(!this.featureFlagsByKey)throw new U("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new U(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let r=e.dependency_chain;if(!Array.isArray(r))throw new U(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof r})`);if(r.length===0)throw new U(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let a of r){if(!(a in n)){let g=this.featureFlagsByKey[a];if(g)if(g.active)try{let d=await this.computeFlagValueLocally(g,i);n[a]=d}catch(d){throw new U(`Error evaluating flag dependency '${a}' for flag '${o}': ${d}`)}else n[a]=!1;else throw new U(`Missing flag dependency '${a}' for flag '${o}'`)}if(n[a]==null)throw new U(`Dependency '${a}' could not be evaluated`)}let s=n[o];return this.flagEvaluatesToExpectedValue(e.value,s)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,i,n){let o=e.filters||{},r=o.groups||[],s=o.aggregation_group_type_index,a=o.early_exit??!1,{groups:l,groupProperties:g}=n,d=!1,c;for(let u of r)try{let C=u.aggregation_group_type_index!==void 0?u.aggregation_group_type_index:s,p=i,b=t;if(C!==s){if(C!=null){let m=this.groupTypeMapping[String(C)];if(!m||!(m in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${C} not available`));continue}if(!(m in g)){d=!0;continue}p=g[m],b=l[m]}}let I=await this.isConditionMatch(e,b,u,p,n);if(I==="match"){let m=u.variant,A=o.multivariate?.variants||[];c=m&&A.some((Z)=>Z.key===m)?m:await this.getMatchingVariant(e,b)||!0;break}if(a&&I==="out_of_rollout_bound")return!1}catch(C){if(C instanceof At)throw C;if(C instanceof U)d=!0;else throw C}if(c!==void 0)return c;if(d)throw new U("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,i,n,o){let r=i.rollout_percentage,s=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((i.properties||[]).length>0){for(let a of i.properties){let l=a.type,g=!1;if(l==="cohort"){let d=await hm(a,n,this.cohorts,this.debugMode,(c)=>this.evaluateFlagDependency(c,n,o));g=a.operator==="not_in"?!d:d}else g=l==="flag"?await this.evaluateFlagDependency(a,n,o):bm(a,n,s);if(!g)return"no_match"}if(r==null)return"match"}if(r!=null&&await mm(e.key,t)>r/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let i=await mm(e.key,t,"variant"),n=this.variantLookupTable(e).find((o)=>i>=o.valueMin&&i<o.valueMax);if(n)return n.key}variantLookupTable(e){let t=[],i=0,n=0;return((e.filters||{}).multivariate?.variants||[]).forEach((s)=>{n=i+s.rollout_percentage/100,t.push({valueMin:i,valueMax:n,key:s.key}),i=n}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,i)=>(t[i.key]=i,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter((i)=>i.ensure_experience_continuity);if(t.length>0)console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map((i)=>i.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(t){return this.onError?.(Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(this.loadedSuccessfullyOnce&&!e)return;if(!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((t)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min($R,this.pollingInterval*2**this.backOffCount)}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!e){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new sn(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new sn(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new sn(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let i=await t.json()??{};if(!("flags"in i))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{},minimalFlagCalledEvents:i.minimal_flag_called_events===!0};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(o){this.onError?.(Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(e){if(e instanceof sn)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)i["If-None-Match"]=t;return{method:e,headers:i}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=We(()=>{n.abort()},this.timeout),t.signal=n.signal}try{let n=this.fetch;return n(e,t)}finally{clearTimeout(i)}}async stopPoller(e=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();if(t instanceof Promise)await Promise.race([t,new Promise((i,n)=>setTimeout(()=>n(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function mm(e,t,i=""){let n=await um(`${e}.${t}${i}`);return parseInt(n.slice(0,15),16)/qR}function bm(e,t,i){let{key:n,value:o}=e,r=e.operator||"exact";if(n in t){if(r==="is_not_set")return!1}else{if(r==="is_not_set")return!0;throw new U(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!e0.includes(r)){if(i)i(`Property ${n} cannot have a value of null/undefined with the ${r} operator`);return!1}function a(g,d){if(Array.isArray(g))return g.map((c)=>String(c).toLowerCase()).includes(String(d).toLowerCase());return String(g).toLowerCase()===String(d).toLowerCase()}function l(g,d,c){if(c==="gt")return g>d;if(c==="gte")return g>=d;if(c==="lt")return g<d;if(c==="lte")return g<=d;throw Error(`Invalid operator: ${c}`)}switch(r){case"exact":return a(o,s);case"is_not":return!a(o,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(o).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(o).toLowerCase());case"regex":return Cm(String(o))&&String(s).match(String(o))!==null;case"not_regex":return Cm(String(o))&&String(s).match(String(o))===null;case"gt":case"gte":case"lt":case"lte":{let g=typeof o=="number"?o:parseFloat(String(o)),d;if(d=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(g)&&Number.isFinite(d))return l(d,g,r);return l(String(s),String(o),r)}case"is_date_after":case"is_date_before":{if(typeof o=="boolean")throw new U("Date operations cannot be performed on boolean values");let g=r0(String(o));if(g==null)g=pm(o);if(g==null)throw new U(`Invalid date: ${o}`);let d=pm(s);if(["is_date_before"].includes(r))return d<g;return d>g}case"semver_eq":return Le(Ce(String(s)),Ce(String(o)))===0;case"semver_neq":return Le(Ce(String(s)),Ce(String(o)))!==0;case"semver_gt":return Le(Ce(String(s)),Ce(String(o)))>0;case"semver_gte":return Le(Ce(String(s)),Ce(String(o)))>=0;case"semver_lt":return Le(Ce(String(s)),Ce(String(o)))<0;case"semver_lte":return Le(Ce(String(s)),Ce(String(o)))<=0;case"semver_tilde":{let g=Ce(String(s)),{lower:d,upper:c}=i0(String(o));return Le(g,d)>=0&&Le(g,c)<0}case"semver_caret":{let g=Ce(String(s)),{lower:d,upper:c}=n0(String(o));return Le(g,d)>=0&&Le(g,c)<0}case"semver_wildcard":{let g=Ce(String(s)),{lower:d,upper:c}=o0(String(o));return Le(g,d)>=0&&Le(g,c)<0}default:throw new U(`Unknown operator: ${r}`)}}function t0(e,t){if(!(e in t))throw new At(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function hm(e,t,i,n=!1,o){let r=String(e.value);t0(r,i);let s=i[r];return Zm(s,t,i,n,o)}async function Zm(e,t,i,n=!1,o){if(!e)return!0;let{type:r,values:s}=e;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let l of s)try{let g=await Zm(l,t,i,n,o);if(r==="AND"){if(!g)return!1}else if(g)return!0}catch(g){if(g instanceof At)throw g;if(g instanceof U){if(n)console.debug(`Failed to compute property ${l} locally: ${g}`);a=!0}else throw g}if(a)throw new U("Can't match cohort without a given cohort property value");return r==="AND"}for(let l of s)try{let g;if(l.type==="cohort")g=await hm(l,t,i,n,o);else if(l.type==="flag"){if(!o)throw new U(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await o(l)}else g=bm(l,t);let d=l.negation||!1;if(r==="AND"){if(!g&&!d)return!1;if(g&&d)return!1}else{if(g&&!d)return!0;if(!g&&d)return!0}}catch(g){if(g instanceof At)throw g;if(g instanceof U){if(n)console.debug(`Failed to compute property ${l} locally: ${g}`);a=!0}else throw g}if(a)throw new U("can't match cohort without a given cohort property value");return r==="AND"}function Cm(e){try{return new RegExp(e),!0}catch(t){return!1}}function fm(e,t){if(!/^\d+$/.test(e))throw new U(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new U(`Invalid semver: ${t}`);return parseInt(e,10)}function Ce(e){let i=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!i||i.startsWith("."))throw new U(`Invalid semver: ${e}`);let n=i.split("."),o=(l)=>{if(l===void 0||l==="")return 0;return fm(l,e)},r=o(n[0]),s=o(n[1]),a=o(n[2]);return[r,s,a]}function Le(e,t){for(let i=0;i<3;i++){if(e[i]<t[i])return-1;if(e[i]>t[i])return 1}return 0}function i0(e){let t=Ce(e),i=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:i,upper:n}}function n0(e){let t=Ce(e),[i,n,o]=t,r=[i,n,o],s;return s=i>0?[i+1,0,0]:n>0?[0,n+1,0]:[0,0,o+1],{lower:r,upper:s}}function o0(e){let i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new U(`Invalid wildcard semver: ${e}`);let n=i.split("."),o=(l)=>{try{return fm(l,e)}catch{throw new U(`Invalid wildcard semver: ${e}`)}},r=o(n[0]),s,a;if(n.length===1)s=[r,0,0],a=[r+1,0,0];else{let l=o(n[1]);s=[r,l,0],a=[r,l+1,0]}return{lower:s,upper:a}}function pm(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new U(`${e} is in an invalid date format`)}throw new U(`The date provided ${e} must be a string, number, or date object`)}function r0(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,i=e.match(t),n=new Date(new Date().toISOString());if(!i)return null;{if(!i.groups)return null;let o=parseInt(i.groups.number);if(o>=1e4)return null;let r=i.groups.interval;if(r=="h")n.setUTCHours(n.getUTCHours()-o);else if(r=="d")n.setUTCDate(n.getUTCDate()-o);else if(r=="w")n.setUTCDate(n.getUTCDate()-7*o);else if(r=="m")n.setUTCMonth(n.getUTCMonth()-o);else{if(r!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-o)}return n}}function s0(e,t){let i=!1;return Object.assign((n)=>{let r=global.process.listeners("uncaughtException").filter((s)=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;if(e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!i&&r)i=!0,t(n)},{_posthogErrorHandler:!0})}function Wm(e,t){globalThis.process?.on("uncaughtException",s0(e,t))}function ym(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var a0=2000;class bt{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new _a({...uu(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return ao(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,i,n,o){let r={...o},s=e.buildFromUnknown(t,i);return s.$exception_list=await e.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...r},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())Wm(this.onException.bind(this),this.onFatalError.bind(this)),ym(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!bt.isPreviouslyCapturedError(e)){let i=await bt.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),o=i.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(o))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o});return this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(a0),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class Cl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function l0(e){return e==="v0"||e==="v1"}function Vm(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return l0(e)?e:"v0"}var po="analytics",Ao="ai";function Bm(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class an extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:n}){super(an.buildMessage(e,t,i,n)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=i,this.cause=n}static buildMessage(e,t,i,n){let o=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${i.length} undelivered`;if(n instanceof Error)o+=` (${n.message})`;return o}}function pl(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function g0(e){return typeof e=="string"?e:void 0}var d0=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:pl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:pl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:pl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:g0}],c0=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function I0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u0(e){if(typeof e=="string"){let i=new Date(e);return Number.isNaN(i.getTime())?new Date().toISOString():e}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Rm(e,t,i){if(i!==void 0&&!(t in e))e[t]=i}function m0(e){let i={...I0(e.properties)?e.properties:{}},n={};for(let{property:r,optionKey:s,coerce:a}of d0)if(r in i){let l=a(i[r]);if(l!==void 0)n[s]=l;delete i[r]}let o={};for(let{property:r,field:s}of c0)if(r in i){let a=i[r];if(typeof a=="string")o[s]=a;delete i[r]}return delete i.$lib,delete i.$lib_version,Rm(i,"$set",e.$set),Rm(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:u0(e.timestamp),...o,options:n,properties:i}}function Gm(e,{createdAt:t,historicalMigration:i}){let n={created_at:t,batch:e.map(m0)};if(i)n.historical_migration=!0;return n}var C0="/i/v1/analytics/events",p0=30000,A0=new Set([408,500,502,503,504]);class Al{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??p0,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((i)=>new Promise((n)=>We(n,i))),this.generateRequestId=t.generateRequestId??je,this.compress=t.compress??Ii}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:n}=Gm(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${C0}`,r=[],s=n,a=Math.max(1,this.config.maxAttempts);for(let l=1;l<=a;l++){let g=l===a,d=qi({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:s}),c;try{c=await this.sendOnce(o,d,l,t)}catch(I){if(g)return this.surfaceBatchFailure(t,r,s,I);await this.sleep(this.backoffDelay(l));continue}let{status:u}=c;if(u<200||u>=300){if(!g&&A0.has(u)){let m=this.parseRetryAfter(c);await this.cancelBody(c),await this.sleep(this.backoffDelay(l,m));continue}let I=await this.buildHttpError(c,u);return this.surfaceBatchFailure(t,r,s,I)}let C;try{C=await this.parseResponse(c)}catch{return this.surfaceBatchFailure(t,r,s,Error(`Capture V1 returned an unparseable ${u} response body`))}let p=this.classify(s,C,r);if(p.length===0)return this.surfacePartialDrops(t,r);if(g)return void this.onError(new an({requestId:t,drops:r,retryExhausted:p.map((I)=>I.uuid)}));s=p;let b=this.parseRetryAfter(c);await this.sleep(this.backoffDelay(l,b))}}async sendOnce(e,t,i,n){let o=this.buildHeaders(i,n),r=t;if(this.config.compressionEnabled){let l=await this.compress(t,this.config.isDebug);if(l!==null)r=l,o["Content-Encoding"]="gzip"}let s=new AbortController,a=We(()=>s.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:o,body:r,signal:s.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let i=`${this.config.libraryId}/${this.config.libraryVersion}`,n={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":i,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)n["User-Agent"]=this.config.userAgent;return n}classify(e,t,i){let n=t.results??{},o=[];for(let r of e){let s=n[r.uuid];if(s){if(s.result==="drop")i.push({uuid:r.uuid,details:s.details??void 0});else if(s.result==="retry")o.push(r)}}return o}backoffDelay(e,t){let i=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return i;return Math.max(i,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let i=t.trim();if(/^\d+$/.test(i)){let r=parseInt(i,10);return Number.isFinite(r)&&r>0?1000*r:void 0}let n=Date.parse(i);if(Number.isNaN(n))return;let o=n-this.now();return o>0?o:void 0}async parseResponse(e){let t=await e.text(),i=JSON.parse(t);if(typeof i!="object"||i===null||Array.isArray(i))throw Error("unexpected response shape");let n=i.results;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw Error("unexpected results shape");return{results:n??{}}}async buildHttpError(e,t){let i="";try{i=(await e.text()).slice(0,512)}catch{}let n=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${n}`)}surfaceBatchFailure(e,t,i,n){this.onError(new an({requestId:e,drops:t,retryExhausted:i.map((o)=>o.uuid),cause:n}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new an({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var b0=100,wm=30000,h0=50000,Z0=50,f0=500,W0="https://us.i.posthog.com",Fm=new Set;function qr(e,t){if(Fm.has(e))return;Fm.add(e),console.warn(`[PostHog] ${t}`)}function y0(e){return typeof e=="string"?e.trim():""}function V0(e){return(typeof e=="string"?e.trim():"")||void 0}function B0(e){return(typeof e=="string"?e.trim():"")||W0}function R0(e){return(Array.isArray(e)?e:[e]).filter((i)=>typeof i=="string"&&i.trim().length>0)}function G0(e){if(!e)return{};let t={};for(let[n,o]of Object.entries(e))t[`$feature/${n}`]=o;let i=Object.keys(e).filter((n)=>e[n]!==!1).sort();if(i.length>0)t.$active_feature_flags=i;return t}class bl extends Mr{constructor(e,t={}){let i=y0(e),n={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:B0(t.host),personalApiKey:V0(t.secretKey??t.personalApiKey)};if(super(i,n),this._memoryStorage=new Cl,this._minimalFlagCalledEvents=!1,this.options=n,this.captureMode=Vm(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof n.featureFlagsPollingInterval=="number"?Math.max(n.featureFlagsPollingInterval,b0):wm,typeof n.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(n.waitUntilDebounceMs,0);if(typeof n.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(n.waitUntilMaxWaitMs,0);if(!this.disabled&&n.personalApiKey){if(n.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');if(n.enableLocalEvaluation!==!1)this.featureFlagsPoller=new ml({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:n.personalApiKey,projectApiKey:i,timeout:n.requestTimeout??1e4,host:this.host,fetch:n.fetch,onError:(r)=>{this._events.emit("error",r)},onLoad:(r)=>{this._events.emit("localEvaluationFlagsLoaded",r)},onMinimalFlagCalledEvents:(r)=>{this._minimalFlagCalledEvents=r},customHeaders:this.getCustomHeaders(),cacheProvider:n.flagDefinitionCacheProvider,strictLocalEvaluation:n.strictLocalEvaluation})}this.errorTracking=new bt(this,n,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=n.maxCacheSize||h0}enqueue(e,t,i){super.enqueue(e,t,i),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let r,s=new Promise((a)=>{r=a});try{e(s)}catch{return}this._waitUntilCycle={resolve:r,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,i=this.options.waitUntilMaxWaitMs??f0,n=t>=i;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(n)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Z0;this._waitUntilCycle.timer=We(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;if(e)clearTimeout(e.timer),this._waitUntilCycle=void 0;return e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&Bm(e)?Ao:po}persistedQueueKeyForRoute(e){return e===Ao?Je.AiQueue:Je.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[po,Ao]:[po]}async sendBatch(e,t,i=po){if(this.captureMode!=="v1"||i===Ao)return super.sendBatch(e,t,i);let n=e.filter((o)=>o!==void 0);await this.getV1Sender().sendV1Batch(n)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Al({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3000,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:(e)=>this._events.emit("error",e)});return this._v1Sender}getLibraryVersion(){return Im}get metrics(){if(!this._metrics)this._metrics=new Xr(this,Tr(this.options.metrics),this._logger);return this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,i){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(i)}_sendPreparedEvent(e,t,i,n){return this.addPendingPromise(this._prepareEventMessage(t,n).then(({distinctId:o,event:r,properties:s,options:a})=>{let l={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},g={distinctId:o,event:r,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,g,l):this.enqueue(e,g,l)}).catch((o)=>{if(o)console.error(o)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:o,$anon_distinct_id:r,...s}=t,g={$set:n||s,$set_once:o||{},$anon_distinct_id:r??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:g,disableGeoip:i},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:o,$anon_distinct_id:r,...s}=t,g={$set:n||s,$set_once:o||{},$anon_distinct_id:r??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:g,disableGeoip:i},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:i={}}){if(Object.keys(t).length===0&&Object.keys(i).length===0)return;let n={};if(Object.keys(t).length>0)n.$set=t;if(Object.keys(i).length>0)n.$set_once=i;this.capture({distinctId:e,event:"$set",properties:n})}unsetPersonProperties({distinctId:e,properties:t}){let i=R0(t);if(i.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:i}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=wm){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let i=setTimeout(()=>{n(),t(!1)},e),n=this._events.on("localEvaluationFlagsLoaded",(o)=>{clearTimeout(i),n(),t(o>0)})})}_resolveDistinctId(e,t){if(typeof e=="string")return{distinctId:e,options:t};return{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,i={},n){if(this.disabled)return void this._logger.warn("The client is disabled");let o=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let V=this._flagOverrides[e];if(V===void 0)return;let H=this._payloadOverrides?.[e];return{key:e,enabled:V!==!1,variant:typeof V=="string"?V:void 0,payload:H}}let{groups:r,disableGeoip:s}=i,{onlyEvaluateLocally:a,personProperties:l,groupProperties:g}=i,d=this.addLocalPersonAndGroupProperties(t,r,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(t,r,this.personPropertiesForLocalEvaluation(t,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let u,C=!1,p,b,I,m,A,Z,f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let V=this.featureFlagsPoller?.featureFlagsByKey[e];if(V)try{let H=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(V,c,{matchValue:n});if(H){C=!0;let S=H.value;m=V.id,Z="Evaluated locally",f=V.has_experiment,u={key:e,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:H.payload??void 0}}}catch(H){if(H instanceof At||H instanceof U)this._logger?.info(`${H.name} when computing flag locally: ${e}: ${H.message}`);else throw H}}if(!C&&!a){let V=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,l,g,s,[e]);if(V===void 0)I=vt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=V.minimalFlagCalledEvents===!0,p=V.requestId,b=V.evaluatedAt;let H=[];if(V.errorsWhileComputingFlags)H.push(vt.ERRORS_WHILE_COMPUTING);if(V.quotaLimited?.includes("feature_flags"))H.push(vt.QUOTA_LIMITED);let S=V.flags[e];if(S===void 0)H.push(vt.FLAG_MISSING);else{m=S.metadata?.id,A=S.metadata?.version,Z=S.reason?.description??S.reason?.code,f=S.metadata?.has_experiment;let k;if(S.metadata?.payload!==void 0)try{k=JSON.parse(S.metadata.payload)}catch{k=S.metadata.payload}u={key:e,enabled:S.enabled,variant:S.variant,payload:k}}if(H.length>0)I=H.join(",")}}if(o){let V=u===void 0?void 0:u.enabled===!1?!1:u.variant??!0,H={$feature_flag:e,$feature_flag_response:V,$feature_flag_id:m,$feature_flag_version:A,$feature_flag_reason:Z,locally_evaluated:C,[`$feature/${e}`]:V,$feature_flag_request_id:p,$feature_flag_evaluated_at:C?Date.now():b};if(f!==void 0)H.$feature_flag_has_experiment=f;if(C&&this.featureFlagsPoller){let S=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(S!==void 0)H.$feature_flag_definitions_loaded_at=S}if(I)H.$feature_flag_error=I;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:V,groups:r,disableGeoip:s,properties:H})}if(u!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)u={...u,payload:this._payloadOverrides[e]};return u}async getFeatureFlag(e,t,i){qr("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return n.variant??!0}async getFeatureFlagPayload(e,t,i,n){if(qr("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let o=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:!1},i);if(o===void 0)return;return o.payload??null}async getFeatureFlagResult(e,t,i){let{distinctId:n,options:o}=this._resolveDistinctId(t,i);if(!n)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,n,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let i=await t.json();if(typeof i=="string")try{return JSON.parse(i)}catch(n){}return i}async isFeatureEnabled(e,t,i){qr("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return!!(n.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(i,n)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:r,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:l,groupProperties:g}=n||{},d=this.addLocalPersonAndGroupProperties(i,o,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(i,o,this.personPropertiesForLocalEvaluation(i,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,s),C={},p={},b=!0;if(u)C=u.response,p=u.payloads,b=u.fallbackToFlags;if(b&&!a){let I=await super.getFeatureFlagsAndPayloadsStateless(c.distinctId,c.groups,l,g,r,s);C={...C,...I.flags||{}},p={...p,...I.payloads||{}}}if(this._flagOverrides!==void 0)C={...C,...this._flagOverrides};if(this._payloadOverrides!==void 0)p={...p,...this._payloadOverrides};return{featureFlags:C,featureFlagPayloads:p}}async evaluateFlags(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Ai({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Ai({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,flags:{}});let{groups:o,disableGeoip:r,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:l,groupProperties:g}=n||{},d=this.addLocalPersonAndGroupProperties(i,o,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(i,o,this.personPropertiesForLocalEvaluation(i,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let u={},C,p,b=!1,I=!1,m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,s),A=new Set;if(m)for(let[f,y]of Object.entries(m.response)){let V=this.featureFlagsPoller?.featureFlagsByKey[f];u[f]={key:f,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:m.payloads[f],id:V?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:V?.has_experiment},A.add(f)}if((m?m.fallbackToFlags:!0)&&!a){let f=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,l,g,r,s);if(f){this._minimalFlagCalledEvents=f.minimalFlagCalledEvents===!0,C=f.requestId,p=f.evaluatedAt,b=Boolean(f.errorsWhileComputingFlags),I=Array.isArray(f.quotaLimited)&&f.quotaLimited.includes("feature_flags");for(let[y,V]of Object.entries(f.flags)){if(A.has(y))continue;let H;if(V.metadata?.payload!==void 0)try{H=JSON.parse(V.metadata.payload)}catch{H=V.metadata.payload}u[y]={key:y,enabled:V.enabled,variant:V.variant,payload:H,id:V.metadata?.id,version:V.metadata?.version,reason:V.reason?.description??V.reason?.code,locallyEvaluated:!1,hasExperiment:V.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[f,y]of Object.entries(this._flagOverrides)){if(y===void 0){delete u[f];continue}let V=u[f];u[f]={key:f,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:V?.payload,id:V?.id,version:V?.version,reason:V?.reason,locallyEvaluated:V?.locallyEvaluated??!1,hasExperiment:V?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[f,y]of Object.entries(this._payloadOverrides)){let V=u[f];if(V)u[f]={...V,payload:y}}return new Ai({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,groups:o,disableGeoip:r,flags:u,requestId:C,evaluatedAt:p,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:i,response:n,groups:o,disableGeoip:r,properties:s}=e,a=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([g],[d])=>g<d?-1:g>d?1:0))}`:"",l=`${i}_${n}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(l);else this.distinctIdHasSentFlagCalls[t]=new Set([l]);this.capture({distinctId:t,event:"$feature_flag_called",properties:s,groups:o,disableGeoip:r})}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(i)=>Object.fromEntries(i.map((n)=>[n,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let i=t.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in t){let i=t.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(e,t,i){if(!this.context)return t();return this.context.run(e,t,i)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),i=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((n)=>We(n,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},i?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;n=We(()=>{o.abort()},this.options.requestTimeout),i.signal=o.signal}try{return await this.fetch(t,i)}catch(o){this._events.emit("error",o);return}finally{if(n)clearTimeout(n)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[o,r]of Object.entries(e))if(Iu(r)&&t&&o in t){let s={};for(let[a,l]of Object.entries(r))s[String(a)]=String(l);n[String(o)]=s}else i[String(o)]=String(r);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(e,t,i,n){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=n?.personProperties||{},r=n?.groupProperties||{},s=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let l={};for(let[g,d]of Object.entries(t||{}))l[g]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:o,groupProperties:r,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[g,d]of Object.entries(t||{}))l[g]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:o,groupProperties:r,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}return(await super.getFeatureFlagsStateless(e,t,o,r,i)).flags}addLocalPersonAndGroupProperties(e,t,i,n){let o={...i||{}},r={};if(t)for(let s of Object.keys(t))r[s]={$group_key:t[s],...n?.[s]||{}};return{allPersonProperties:o,allGroupProperties:r}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,i,n){return{distinctId:e,groups:t||{},personProperties:i||{},groupProperties:n||{},evaluationCache:{}}}captureException(e,t,i,n,o){if(!bt.isPreviouslyCapturedError(e)){let r=Error("PostHog syntheticException");this.addPendingPromise(bt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:r},t,i).then((s)=>this._capturePreparedEvent({...s,uuid:n,flags:o},!1)))}}async captureExceptionImmediate(e,t,i,n){if(!bt.isPreviouslyCapturedError(e)){let o=Error("PostHog syntheticException");return this.addPendingPromise(bt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,i).then((r)=>this.captureImmediate({...r,flags:n})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:i,event:n,properties:o,groups:r,flags:s,sendFeatureFlags:a,timestamp:l,disableGeoip:g,uuid:d}=e,c=this.context?.get(),u=t.includeContextProperties??!0,C=i||c?.distinctId,p=u?{...this.props,...c?.properties||{},...o||{}}:{...o||{}};if(!C)C=je(),p.$process_person_profile=!1;if(u&&c?.sessionId&&!p.$session_id)p.$session_id=c.sessionId;let b=this._shouldSendMinimalFlagCalledEvent(n,p)?ro(p):p,I=this._runBeforeSend({distinctId:C,event:n,properties:b,groups:r,flags:s,sendFeatureFlags:a,timestamp:l,disableGeoip:g,uuid:d});if(!I)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return s._getEventProperties()}if(a){qr("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let A=typeof a=="object"?a:void 0,Z=await this.getFeatureFlagsForEvent(I.distinctId,r,g,A);return G0(Z)}return{}}).catch(()=>({})).then((A)=>{let Z=I.groups||r;return{...A,...I.properties||{},...Z!==void 0&&Object.keys(Z).length>0?{$groups:Z}:{}}});if(I.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"){if(ru(m.$raw_user_agent,this.options.custom_blocked_useragents||[]))I.event="$bot_pageview",m.$browser_type="bot"}return{distinctId:I.distinctId,event:I.event,properties:m,options:{timestamp:I.timestamp,disableGeoip:I.disableGeoip,uuid:I.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let i=Array.isArray(t)?t:[t],n=e;for(let o of i){if(n=o(n),!n)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let r=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(r)}}return n}}var Hm=require("async_hooks");class hl{constructor(){this.storage=new Hm.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,i){return this.storage.run(this.resolve(e,i),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let i=this.get()||{};return{distinctId:e.distinctId??i.distinctId,sessionId:e.sessionId??i.sessionId,properties:{...i.properties||{},...e.properties||{}}}}}function w0(e,{organization:t,projectId:i,prefix:n,severityAllowList:o=["error"],sendExceptionsToPostHog:r=!0}={}){return(s)=>{if(!(o==="*"||o.includes(s.level)))return s;if(!s.tags)s.tags={};let l=s.tags[km.POSTHOG_ID_TAG];if(l===void 0)return s;let g=e.options.host??"https://us.i.posthog.com",d=new URL(`/project/${e.apiKey}/person/${l}`,g).toString();s.tags["PostHog Person URL"]=d;let c=s.exception?.values||[],u=c.map((p)=>({...p,stacktrace:p.stacktrace?{...p.stacktrace,type:"raw",frames:(p.stacktrace.frames||[]).map((b)=>({...b,platform:"node:javascript"}))}:void 0})),C={$exception_message:c[0]?.value||s.message,$exception_type:c[0]?.type,$exception_level:s.level,$exception_list:u,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:c[0]?.value||s.message,$sentry_exception_type:c[0]?.type,$sentry_tags:s.tags};if(t&&i)C.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+s.event_id;if(r)e.capture({event:"$exception",distinctId:l,properties:C});return s}}class km{static#i=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,i,n,o){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(r,s){let a=s()?.getClient()?.getDsn()?.projectId;r(w0(e,{organization:t,projectId:a,prefix:i,severityAllowList:n,sendExceptionsToPostHog:o??!0}))}}}class Zl extends bl{getLibraryId(){return"posthog-node"}initializeContext(){return new hl}createErrorPropertiesBuilder(){return new Ye.ErrorPropertiesBuilder([new Ye.EventCoercer,new Ye.ErrorCoercer,new Ye.ObjectCoercer,new Ye.StringCoercer,new Ye.PrimitiveCoercer],Ye.createStackParser("node:javascript",Ye.nodeStackLineParser),[iu(),lm,cm()])}}class M extends Error{code;status;body;requestId;constructor(e,t,i,n,o){super(e);this.name="PotatoApiError",this.code=t,this.status=i,this.body=n,this.requestId=o}static fromResponse(e,t,i){let n=i===void 0?"":` (request id: ${i})`;return new M(`Potato API request failed with status ${e}${n}`,"http",e,t,i)}static waitTimeout(e){return new M(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class bi extends Error{code="invalid_pipeline_graph";issues;constructor(e,t){super(e);this.name="PipelineGraphValidationError",this.issues=t}static fromIssues(e){let t=e.map(({path:i,reason:n})=>`- ${i}: ${n}`).join(`
|
|
37
37
|
`);return new bi(`Pipeline graph validation failed
|
|
38
38
|
${t}`,e)}}var Fe=require("fs/promises"),Sm=require("os"),hi=require("path");class F extends Error{hint;constructor(e,t){super(e,t.cause===void 0?void 0:{cause:t.cause});this.name="TolokaCliError",this.hint=t.hint}}function h(e,t,i){if(!e)throw new F(t,i)}var vm=(e)=>("disabled"in e)?void 0:`Hint: ${e.description}`,v={description:"This looks like a defect in the CLI or the platform. Write a report as the toloka-report-issue skill describes, then send it with toloka report <report.md>."},Pt={description:"Retry the command; if it keeps failing, write a report as the toloka-report-issue skill describes and send it with toloka report <report.md>."},pe={description:"Reinstall @toloka-platform/sdk to restore the bundled files."};class bo extends F{constructor(e,t){super(e,t);this.name="CredentialsError"}}var xm=(e)=>e.HOME??Sm.homedir(),F0=(e)=>e.XDG_CONFIG_HOME??hi.join(xm(e),".config"),Me=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??hi.join(F0(e),"toloka","credentials.json"),Ym=(e=process.env)=>hi.join(xm(e),".toloka","credentials.json"),ts=(e=process.env)=>hi.dirname(Me(e)),Pm=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},ht=(e)=>{let t=Pm(e.trim());try{let i=new URL(t);return i.hash="",i.search="",Pm(i.toString())}catch{return t}},es=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,H0=(e)=>{if(typeof e!=="object"||e===null)return;let t=Reflect.get(e,"id");if(typeof t!=="string"||t.length===0)return;let i=Reflect.get(e,"name");if(i!==void 0&&typeof i!=="string")return;return i===void 0?{id:t}:{id:t,name:i}},k0=(e)=>{if(e===void 0||typeof e!=="object"||e===null||Array.isArray(e))return;let t=Object.create(null);for(let[i,n]of Object.entries(e)){if(i.length===0)return;let o=H0(n);if(o===void 0)return;Object.defineProperty(t,i,{value:o,writable:!0,enumerable:!0,configurable:!0})}return t},v0=(e,t)=>{let i=k0(e);if(i===void 0)return;if(typeof t==="string"){if(t.length===0||!Object.hasOwn(i,t))return;return{current:t,projects:i}}if(t!==void 0)return;return Object.keys(i).length===0?{}:{projects:i}},P0=(e)=>{let t=es(e,"baseUrl"),i=es(e,"apiKey");if(typeof t!=="string"||t.length===0)return;if(i!==void 0&&(typeof i!=="string"||i.length===0))return;let n=i===void 0?{baseUrl:t}:{baseUrl:t,apiKey:i},o=es(e,"current"),r=es(e,"projects");if(o===void 0&&r===void 0)return n;let s=v0(r,o);if(s===void 0)return;return{...n,...s}};async function ho(e){let t;try{t=await Fe.readFile(e,"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return"missing";return"invalid"}try{let i=P0(JSON.parse(t));return i===void 0?"invalid":{credentials:i}}catch{return"invalid"}}async function fl(e=process.env){let t=Me(e),i=await ho(t);if(i!=="missing"){if(i==="invalid")throw new bo(`Invalid credentials file at ${t}. Run toloka logout, then toloka login.`,{hint:{disabled:!0}});return{credentials:i.credentials,path:t,legacy:!1}}if(e.TOLOKA_CREDENTIALS_FILE!==void 0)return;let n=Ym(e),o=await ho(n);if(o==="missing")return;if(o==="invalid")throw new bo(`Invalid credentials file at ${n}. Run toloka logout, then toloka login.`,{hint:{disabled:!0}});return{credentials:o.credentials,path:n,legacy:!0}}async function ln(e,t){try{return{found:await fl(e)}}catch(i){if(!(i instanceof bo)||t===void 0)throw i;return{found:void 0,warning:i.message}}}async function Em(e=process.env){return(await fl(e))?.credentials}async function jt(e=process.env){let t=await fl(e);if(t!==void 0)return t;throw new bo(`No stored credentials found at ${Me(e)}. Run toloka login.`,{hint:{disabled:!0}})}var N0=(e)=>{let t=e.projects,i=t!==void 0&&Object.keys(t).length>0;return{baseUrl:e.baseUrl,...e.apiKey===void 0?{}:{apiKey:e.apiKey},...e.current===void 0?{}:{current:e.current},...i?{projects:t}:{}}},Nm=async(e)=>{try{let t=await Fe.lstat(e);h(!t.isSymbolicLink(),`Refusing to write through symbolic link ${e}.`,{hint:{description:"Replace the symbolic link with a regular file or directory, then retry."}})}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}};async function Nt(e){let t=hi.dirname(e);await Nm(t),await Nm(e),await Fe.mkdir(t,{recursive:!0,mode:448}),await Fe.chmod(t,448)}async function Zo(e,t=process.env){let i=Me(t);return await Nt(i),await Fe.writeFile(i,`${JSON.stringify(N0(e),null,2)}
|
|
39
|
-
`,{mode:384}),await Fe.chmod(i,384),i}var S0=async(e)=>{try{return await Fe.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},Wl=(e=process.env)=>[Me(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[Ym(e)]:[]];async function Tm(e=process.env){let t=[];for(let i of Wl(e)){if(!await S0(i))continue;await Fe.rm(i,{force:!0}),t.push(i)}return t}var x0=16,Xm=(e)=>e.length>x0?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var $e=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},gn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var yl={name:"@toloka-platform/sdk",version:"0.12.
|
|
39
|
+
`,{mode:384}),await Fe.chmod(i,384),i}var S0=async(e)=>{try{return await Fe.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},Wl=(e=process.env)=>[Me(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[Ym(e)]:[]];async function Tm(e=process.env){let t=[];for(let i of Wl(e)){if(!await S0(i))continue;await Fe.rm(i,{force:!0}),t.push(i)}return t}var x0=16,Xm=(e)=>e.length>x0?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var $e=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},gn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var yl={name:"@toloka-platform/sdk",version:"0.12.2",private:!1,description:"Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change between minor versions before 1.0.",license:"Apache-2.0",bin:{toloka:"bin/toloka.js"},files:["README.md","bin","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./testing":"./src/testing/index.ts","./checks":"./src/checks/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"latest"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js","generate:check":"bun ./scripts/check-generated-client.ts",prepack:"bun run build","sync-skill-catalog":"bun ./scripts/sync-skill-catalog.ts","sync-task-ui-declarations":"bun ./scripts/sync-task-ui-declarations.ts",test:"vitest run","test:browser":"vitest run --config vitest.browser.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1","@typescript/vfs":"1.6.2",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","jsonpath-rfc9535":"1.3.0","oxc-parser":"0.138.0","posthog-node":"5.46.1","typescript-api":"npm:typescript@6.0.3"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",playwright:"1.56.1",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},peerDependencies:{playwright:">=1.56.1 <2",vitest:">=4.1.0 <5"},peerDependenciesMeta:{playwright:{optional:!0},vitest:{optional:!0}},engines:{bun:">=1.4.0"},tolokaBuild:{commit:"72b9ea77f616c7f9c3c564c550eac42f703929b2"}};var ye=yl.name,se=yl.version,Vl=(e)=>{let t=/^(\d+)\.(\d+)\.(\d+)(?:-preview\.(\d+))?$/u.exec(e);if(t===null)return;let[,i,n,o,r]=t;return[Number(i),Number(n),Number(o),r===void 0?Number.POSITIVE_INFINITY:Number(r)]},Om=(e)=>{let t=Vl(e);if(t===void 0)return;return t[3]===Number.POSITIVE_INFINITY?"latest":"preview"},Bl=(e,t)=>{let i=Vl(e),n=Vl(t);if(i===void 0||n===void 0)return;let o=Math.max(i.length,n.length);for(let r=0;r<o;r+=1){let s=i[r]??0,a=n[r]??0;if(s<a)return-1;if(s>a)return 1}return 0};var fo=(e)=>{let t=typeof e.body==="string"?e.body:e.body===void 0?void 0:JSON.stringify(e.body);return t===void 0||t.length===0?void 0:t},E0=(e)=>{if(e.code==="wait_timeout")return"Hint: The job is still running. Check it later with its status command; commands that accept --timeout can wait longer.";if(e.status===401||e.status===403)return"Hint: Run toloka whoami to see which key and platform are in use; toloka login stores a new key.";if(e.status===404)return"Hint: Check the id against toloka project current and the matching list command; ids belong to one project on one platform.";if(e.status===429)return"Hint: The platform is rate limiting this key; wait a moment and retry.";if(e.status===503&&e.body==="Tunnel unavailable; the request was not sent")return"Hint: The sandbox lost its connection to the platform (usually a platform restart) and it was not restored within 90 seconds; the request was not sent. Retry in a minute.";if(e.status!==void 0&&e.status>=500)return"Hint: The platform failed to handle the request. Retry; if it keeps failing, write a report as the toloka-report-issue skill describes and send it with toloka report <report.md>.";return},Um=(e)=>e.filter((t)=>t!==void 0&&t.length>0).join(`
|
|
40
40
|
`),dn=(e)=>{if(e instanceof M)return e;if(e instanceof AggregateError)for(let t of e.errors){let i=dn(t);if(i!==void 0)return i}return e instanceof Error?dn(e.cause):void 0},zt=(e)=>{if(e instanceof F){let t=dn(e.cause),i=t===void 0?[]:t.message===e.message?[fo(t)]:[t.message,fo(t)];return Um([e.message,...i,vm(e.hint)])}if(e instanceof M)return Um([e.message,fo(e),E0(e)]);return e instanceof Error?e.message:String(e)};var T0="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",X0="https://eu.posthog.com",O0={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0};function U0(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(gn(t))return!1;if($e(t))return!0;if($e(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if($e(e.CI??process.env.CI))return!1;if($e(process.env.VITEST))return!1;return!0}var J0={project:{list:!0,add:!0,switch:!0,current:!0,remove:!0,create:!0},pipeline:{list:!0,run:!0,status:!0,runs:!0,cost:!0,cancel:!0,results:!0},dataset:{list:!0,create:!0,fields:!0,load:!0,upload:!0},"delivery-order":{list:!0},audience:{specialization:{list:!0}},training:{list:!0,get:!0,create:!0,update:!0,cost:!0,run:!0,runs:!0,status:!0,resume:!0,cancel:!0,metrics:!0,logs:!0},"base-model":{list:!0,get:!0},"generation-model":{list:!0},model:{list:!0,get:!0,versions:!0,create:!0,archive:!0,version:{download:!0}},secret:{set:!0},skill:{list:!0,search:!0,install:!0},config:{get:!0,set:!0}},j0={apply:!0,check:!0,"auth-status":!0,config:!0,help:!0,import:!0,init:!0,login:!0,logout:!0,plan:!0,status:!0,validate:!0,report:!0,version:!0,whoami:!0},jm=(e)=>{let t=e[0];if(t===void 0)return"help";let i=J0[t];if(i===void 0)return j0[t]===!0?t:"unknown";let n=e[1],o=n===void 0?void 0:i[n];if(o===void 0)return t;if(o===!0)return`${t} ${n}`;let r=e[2];return r!==void 0&&o[r]===!0?`${t} ${n} ${r}`:`${t} ${n}`};function ns(e){if(e.includes("-v")||e.includes("--version"))return"version";let t=[];for(let i=0;i<e.length;i+=1){let n=e[i];if(n===void 0)continue;if(n==="--help"||n==="-h")break;if(n.startsWith("-")){if(O0[n]===!0)i+=1;continue}t.push(n)}return jm(t)}function z0(e){if(e===void 0)return{error_code:"command_failed"};let t=dn(e);if(t!==void 0)return{error_code:t.code};if(e instanceof bi)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var D0=(e)=>{let t=dn(e);return t===void 0?{}:{status_code:t.status,request_id:t.requestId}},_0=(e)=>is.join(is.dirname(Me(e)),"anonymous-id"),Q0=async(e)=>{let t=_0(e);await Nt(t);try{let n=(await Zi.readFile(t,"utf8")).trim();if(n.length>0)return await Zi.chmod(t,384),n}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ENOENT"))throw n}let i=Jm.randomUUID();return await Zi.writeFile(t,`${i}
|
|
41
41
|
`,{mode:384}),await Zi.chmod(t,384),i},K0=()=>({shouldIdentify:!1,issueReportingEnabled:!1,identifyCurrentUser(){},captureCommand(){},async submitIssueReport(){h(!1,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.",{hint:{disabled:!0}})},async shutdown(){}});function zm(e){let{environment:t}=e;if(e.client===void 0&&!U0(t))return K0();let{client:i,distinctId:n}=e,o,r=[],s=(d)=>{r.push(d)};i?.on?.("error",s);let a=async()=>{if(i!==void 0&&n!==void 0)return;if(i===void 0){let d=new Zl(T0,{host:X0,flushAt:1,flushInterval:0});d.on("error",s),i=d}n??=await Q0(t)},l=()=>({sdk_version:se,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),g=a().catch(()=>{});return{issueReportingEnabled:!0,shouldIdentify:!0,identifyCurrentUser(d){g=g.then(()=>{if(i===void 0||n===void 0)return;if(o===d.id)return;if(o=d.id,n!==d.id)i.alias({distinctId:d.id,alias:n});n=d.id}).catch(()=>{})},captureCommand(d){g=g.then(()=>{if(i===void 0||n===void 0)return;let c=l(),u=jm(d.command.split(" "));if(d.outcome==="failed"){let C=z0(d.error),p=D0(d.error);if(d.error!==void 0){let b=new F(`CLI command failed: ${C.error_code}`,{hint:{disabled:!0}});b.name="PotatoCliError",i.captureException(b,n,{...c,command:u,duration_ms:d.durationMs,exit_code:d.exitCode,$process_person_profile:!1,$geoip_disable:!0,...C,...p})}i.capture({distinctId:n,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...c,command:u,duration_ms:d.durationMs,exit_code:d.exitCode,...C,...p}});return}i.capture({distinctId:n,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...c,command:u,duration_ms:d.durationMs,exit_code:d.exitCode,outcome:d.outcome}})}).catch(()=>{})},submitIssueReport(d){let c=g.then(async()=>{h(i&&n,"PostHog issue reporting could not be initialized.",{hint:{description:"Set TOLOKA_TELEMETRY=1 and check that this machine can reach PostHog, then retry."}}),r.length=0,i.capture({distinctId:n,event:"sdk_cli_issue_report_submitted",disableGeoip:!0,properties:{...l(),report_id:d.reportId,report_text:d.reportText,report_length_bytes:new TextEncoder().encode(d.reportText).length,authored_by:d.authoredBy,platform:d.platform,$process_person_profile:!1}}),await i.flush();let u=r[0];if(r.length=0,u!==void 0)throw u});return g=c.catch(()=>{}),c},async shutdown(){try{await g,await i?.shutdown(2000)}catch{}}}}var Sn=require("crypto"),ea=require("child_process"),rr=require("events"),Tt=require("fs"),D=require("fs/promises"),ge=require("path"),ta=require("stream"),ch=require("stream/promises");var Vo=require("fs"),Wi=require("path");var fi=()=>Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0,Wo=(e,t=fi())=>t?{...e,BUN_BE_BUN:"1"}:e;var Dm=Wi.join("bin","toloka.js"),_m=(e)=>{try{return Vo.realpathSync(e)}catch{return e}},yo=(e)=>{let t=Wi.join(e,Dm);if(Vo.existsSync(t))return t;let i=Wi.dirname(e);return i===e?void 0:yo(i)},Qm=(e=process.argv[1])=>(e===void 0?void 0:yo(Wi.dirname(_m(e))))??yo(process.cwd()),L0=(e=process.argv[1])=>{let t=e===void 0?void 0:_m(e);if(t!==void 0&&Vo.existsSync(t)&&yo(Wi.dirname(t))!==void 0)return t;let i=yo(process.cwd());return h(i!==void 0,`Cannot locate the toloka CLI entry point. An installed @toloka-platform/sdk ships ${Dm} in a directory above its runtime entry, but none exists above ${e??"the unset process.argv[1]"} or above ${process.cwd()}. Reinstall @toloka-platform/sdk.`,{hint:{disabled:!0}}),i},os=(e,t,i={})=>{let n=i.executable??process.execPath;if(!(i.native??fi()))return{executable:i.executable??(Reflect.get(process.versions,"bun")?process.execPath:"bun"),args:[L0(i.runtimeEntry),...e],environment:t};let o={...t};return delete o.BUN_BE_BUN,{executable:n,args:[...e],environment:o}};var In=require("fs/promises"),Km=require("path");var cn="auto-update",Lm={autoUpdate:!0};class rs extends F{constructor(e,t){super(e,t);this.name="SettingsError"}}var Mm=(e=process.env)=>Km.join(ts(e),"settings.json"),M0=(e)=>{let t=typeof e==="object"&&e!==null?Reflect.get(e,"autoUpdate"):void 0;if(typeof t!=="boolean")return Lm;return{autoUpdate:t}};async function Bo(e=process.env){try{return M0(JSON.parse(await In.readFile(Mm(e),"utf8")))}catch{return Lm}}async function $0(e,t=process.env){let i=Mm(t);return await Nt(i),await In.writeFile(i,`${JSON.stringify({autoUpdate:e.autoUpdate},null,2)}
|
|
42
42
|
`,{mode:384}),await In.chmod(i,384),i}var q0=(e)=>{if($e(e))return!0;if(gn(e))return!1;throw new rs(`Expected a boolean (true or false), got ${JSON.stringify(e)}.`,{hint:{description:"Run toloka config set auto-update true or false."}})},eG=(e)=>`${cn}=${e.autoUpdate}`,Rl=(e,t)=>{if(t===void 0||t.length===0)return{output:eG(e)};if(t!==cn)throw new rs(`Unknown setting "${t}". Known settings: ${cn}.`,{hint:{disabled:!0}});return{output:String(e.autoUpdate)}};async function $m(e,t,i){if(t!==cn)throw new rs(`Unknown setting "${t}". Known settings: ${cn}.`,{hint:{disabled:!0}});let n={autoUpdate:q0(i)};return await $0(n,e),{settings:n,output:`Set ${cn} to ${n.autoUpdate}.`}}var nh=require("fs"),oh=require("child_process"),rh=require("module"),sh=require("events"),oi=require("fs/promises"),Ld=require("os"),ni=require("path");var tC=require("oxc-parser");var qm=require("oxc-parser"),Gl=(e,t,i)=>{let n=qm.parseSync(e,t,{lang:i,preserveParens:!1});return n.errors.some((o)=>o.severity==="Error")?null:n.program},eC=(e)=>{let t=e?.value;if(!t)return null;if(t.type==="Literal")return typeof t.value==="string"?t.value:null;if(t.type==="JSXExpressionContainer"){let i=t.expression;if(i.type==="Literal"&&typeof i.value==="string")return i.value;if(i.type==="TemplateLiteral"&&i.expressions.length===0)return i.quasis[0]?.value.cooked??null}return null};var wl=(e)=>{let t=iG(e.postprocess);if(!t||t.size===0)return[];let i=tG(e.code);if(!i||i.size===0)return[];return[...i].filter(([n])=>t.has(n)).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>{let r=o===n?`path="${o}"`:`path="${o}" \u2014 a dotted path binds its top-level key "${n}"`;return{severity:"error",text:`Postprocess returns the key "${n}", but a Field component is bound to it (${r}). Every submission of this interface fails at runtime with: Postprocess cannot write key '${n}' because a component is bound to it. Fix: bind the Field to a raw key (e.g. path="raw_${n}") and derive "${n}" in postprocess, or remove "${n}" from the postprocess return.`}})},tG=(e)=>{let t=Gl("code.tsx",`(
|
|
@@ -406,7 +406,7 @@ ${i}${n}`},UV=async(e,t,i)=>{let n=await e.trainings.getRunMetrics({trainingRunI
|
|
|
406
406
|
`),EO=(e)=>Object.values(e).map((t)=>[`## ${t.name}`,t.description,`When to use: ${t.whenToUse}`,..._I("Capabilities",t.capabilities),..._I("Limitations",t.limitations),..._I("Best practices",t.bestPractices),"Props:",t.propsType,...t.valueType===void 0?[]:["Value:",t.valueType],...t.example===void 0?[]:["Example:",t.example.jsxTemplate,"Example output:",t.example.output]].join(`
|
|
407
407
|
`)).join(`
|
|
408
408
|
|
|
409
|
-
`),KV=async({sourceRoot:e,names:t,json:i,io:n,describe:o})=>{let r=await o({resolveFrom:e,...t.length===0?{}:{names:[...t]}});if(i){n.stdout(JSON.stringify(r,void 0,2));return}n.stdout(t.length===0?YO(r):EO(r))};var LV=(e,t)=>{let{context:i,globals:n}=t;e.command("ui").description("inspect the Task UI components the launcher renders").command("components").argument("[names...]","component names such as Field.RadioGroup; omit to list every component").option("--json","print the component contracts as JSON",!1).description("list Task UI components, or print the props, value shape, and example of the named ones").action(async(r,s)=>{let a=await ce(n(),i.io);await KV({sourceRoot:a,names:r,json:s.json,io:i.io,describe:i.taskUiComponents??QV})})};var MV=require("fs"),$V=require("os"),Se=require("path");var TO=`${Se.sep}install${Se.sep}global${Se.sep}`,Oa=(e)=>{try{return MV.realpathSync(e)}catch{return e}},XO=(e,t,i,n)=>{if(Oa(e).includes(TO))return"global-registry";if(Oa(n)===t)return"linked";if(Se.dirname(Se.resolve(e))===Se.resolve(i))return"linked";return"project-local"},qV=(e=process.argv[1],t={})=>{if(t.native??fi())return{version:se,commit:"
|
|
409
|
+
`),KV=async({sourceRoot:e,names:t,json:i,io:n,describe:o})=>{let r=await o({resolveFrom:e,...t.length===0?{}:{names:[...t]}});if(i){n.stdout(JSON.stringify(r,void 0,2));return}n.stdout(t.length===0?YO(r):EO(r))};var LV=(e,t)=>{let{context:i,globals:n}=t;e.command("ui").description("inspect the Task UI components the launcher renders").command("components").argument("[names...]","component names such as Field.RadioGroup; omit to list every component").option("--json","print the component contracts as JSON",!1).description("list Task UI components, or print the props, value shape, and example of the named ones").action(async(r,s)=>{let a=await ce(n(),i.io);await KV({sourceRoot:a,names:r,json:s.json,io:i.io,describe:i.taskUiComponents??QV})})};var MV=require("fs"),$V=require("os"),Se=require("path");var TO=`${Se.sep}install${Se.sep}global${Se.sep}`,Oa=(e)=>{try{return MV.realpathSync(e)}catch{return e}},XO=(e,t,i,n)=>{if(Oa(e).includes(TO))return"global-registry";if(Oa(n)===t)return"linked";if(Se.dirname(Se.resolve(e))===Se.resolve(i))return"linked";return"project-local"},qV=(e=process.argv[1],t={})=>{if(t.native??fi())return{version:se,commit:"72b9ea77f616",channel:"native",path:Oa(t.executablePath??process.execPath)};h(e,"CLI entry path is unavailable",{hint:v});let i=t.globalBinDirectory??Se.resolve(process.env.BUN_INSTALL??Se.join($V.homedir(),".bun"),"bin"),n=t.globalPackageDirectory??Se.resolve(i,"..","install","global","node_modules","@toloka-platform","sdk"),o=Se.resolve(Se.dirname(Oa(e)),".."),r=XO(e,o,i,n);return{version:se,commit:"72b9ea77f616",channel:r,...r==="linked"?{path:o}:{}}};var eB=(e,t)=>{e.command("version").option("--json","print version and build provenance as JSON",!1).description("print the current CLI version").action((i)=>t.context.io.stdout(i.json?JSON.stringify(qV()):se))};var iB=require("readline/promises");var tB=()=>new F("Standard input closed before an API key was entered.",{hint:{description:"Run toloka login in an interactive terminal, or pipe the key with toloka login --api-key-stdin."}}),OO=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},UO=async(e)=>{process.stdout.write(e);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let{promise:i,resolve:n,reject:o}=Promise.withResolvers(),r="",s=()=>{process.stdin.off("data",d),process.stdin.off("end",l),process.stdin.off("error",g),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{s(),process.stdout.write(`
|
|
410
410
|
`)},l=()=>{a(),o(tB())},g=(c)=>{a(),o(c)},d=(c)=>{for(let u of c){if(u==="\r"||u===`
|
|
411
411
|
`){a(),n(r);return}if(u==="\x03"||u==="\x04"){a(),o(u==="\x03"?new F("Canceled.",{hint:{disabled:!0}}):tB());return}if(u==="\x7F"||u==="\b"){if(r.length>0)r=r.slice(0,-1),process.stdout.write("\b \b");continue}r+=u,process.stdout.write("*")}};process.stdin.on("data",d),process.stdin.once("end",l),process.stdin.once("error",g);try{return await i}finally{s()}},JO=async(e,t={})=>{if(t.mask===!0)return UO(e);let i=iB.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await i.question(e)}finally{i.close()}},jO=(e,t)=>Na({message:e,choices:t}),QI=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:OO,style:mf(process.env,process.stdout.isTTY),...process.stdin.isTTY?{prompt:JO,choose:jO,select:ky}:{}});function zO(e){let t=new Mi("toloka"),i={value:0},n=!1;t.description("Build and operate Toloka pipeline projects from TypeScript source. The public API may change between minor versions before 1.0.").version(se,"-v, --version","output the current version").option("--source-root <directory>","project root; discovered from the working directory when omitted").option("--api-key <key>","API key for this command only").option("--base-url <url>","platform base URL for this command only").option("--project-id <id>","target project; overrides toloka.json").addHelpText("after",`
|
|
412
412
|
${qZ}`).configureOutput({writeOut:(s)=>e.io.stdout(s.replace(/\n$/u,"")),writeErr:(s)=>e.io.stderr(s.replace(/\n$/u,""))}).exitOverride();let o=()=>t.opts(),r={context:e,exitCode:i,globals:o};return t.hook("postAction",async(s,a)=>{if(n)return;let l=[];for(let c=a;c!==null;c=c.parent)l.push(c.name());if(l.includes("init")||l.includes("help")||l.includes("report")||l.includes("url")||l.includes("version")||l.includes("config"))return;let g=await ce(o(),e.io),d=await bV(g).catch(()=>{return});if(d===void 0)return;n=!0,e.io.stderr(d)}),eB(t,r),vf(t,r),kf(t,r),jy(t,r),BW(t,r),gf(t,r),yW(t,r),fV(t,r),Qy(t,r),xW(t,r),jV(t,r),fW(t,r),Jy(t,r),WV(t,r),_y(t,r),dV(t,r),LV(t,r),{program:t,exitCode:i}}var DO=(e,t)=>{for(let i=0;i<t.length;i+=1){let n=t[i];if(n===void 0)return;if(n==="--")return t[i+1];if(!n.startsWith("-"))return n;let o=e.options.find((r)=>r.short===n||r.long===n);if(o!==void 0&&(o.required||o.optional)&&!n.includes("="))i+=1}return},_O=(e,t)=>{let i=DO(e,t);if(i===void 0||i==="help")return;return e.commands.some((o)=>o.name()===i||o.aliases().includes(i))?void 0:i},QO=async(e,t,i,n)=>{let o=_O(e,i);if(o!==void 0)return n.stderr(`error: unknown command '${o}'
|
package/dist/cli/toloka.js.jsc
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
8ed8ac9a70b9d78e84e61a5ab6f59647b65043707f6fd5a09e394e648151df5f toloka.js.jsc
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
b5ed5a56f22841b7d917e9f4f7e974cb1a7d3c9fe4a0e58a1df5f8967a4be250 toloka.js
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type DatasetExportReportTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type DatasetExportReportTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type TrainingCostEstimateOneOfInputsTrainingReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type TrainingCostEstimateOneOfInputsTrainingReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type TrainingCostEstimateOneOfInputsValidationAnyOfReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type TrainingCostEstimateOneOfInputsValidationAnyOfReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type TrainingCostEstimateOneOfTwosevenInputsTrainingReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type TrainingCostEstimateOneOfTwosevenInputsTrainingReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type TrainingCostEstimateOneOfTwosevenInputsValidationAnyOfReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type TrainingCostEstimateOneOfTwosevenInputsValidationAnyOfReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type TrainingRunInputsAnyOfTrainingReportTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type TrainingRunInputsAnyOfTrainingReportTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
package/openapi/gen/models/trainingRunInputsAnyOfValidationAnyOfReportTokensEstimatorVersion.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type TrainingRunInputsAnyOfValidationAnyOfReportTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type TrainingRunInputsAnyOfValidationAnyOfReportTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
package/openapi/gen/models/trainingRunQuoteInputsTrainingReportAnyOfTokensEstimatorVersion.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type TrainingRunQuoteInputsTrainingReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type TrainingRunQuoteInputsTrainingReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
package/openapi/gen/models/trainingRunQuoteInputsValidationAnyOfReportAnyOfTokensEstimatorVersion.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export type TrainingRunQuoteInputsValidationAnyOfReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | null;
|
|
2
|
+
export type TrainingRunQuoteInputsValidationAnyOfReportAnyOfTokensEstimatorVersion = 'utf16-code-units-div-4-v1' | 'script-weighted-v1' | null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@toloka-platform/sdk",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change between minor versions before 1.0.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -77,6 +77,6 @@
|
|
|
77
77
|
"bun": ">=1.4.0"
|
|
78
78
|
},
|
|
79
79
|
"tolokaBuild": {
|
|
80
|
-
"commit": "
|
|
80
|
+
"commit": "72b9ea77f616c7f9c3c564c550eac42f703929b2"
|
|
81
81
|
}
|
|
82
82
|
}
|
package/skills/catalog.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"testing",
|
|
12
12
|
"checks"
|
|
13
13
|
],
|
|
14
|
-
"version": "0.12.
|
|
14
|
+
"version": "0.12.2",
|
|
15
15
|
"digest": "7e6b79b9b85fbfc86cf98f33ebd30fdb4617707d22f7c24440bee2fedecb5f71",
|
|
16
16
|
"files": [
|
|
17
17
|
"SKILL.md",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"bug",
|
|
34
34
|
"report"
|
|
35
35
|
],
|
|
36
|
-
"version": "0.12.
|
|
36
|
+
"version": "0.12.2",
|
|
37
37
|
"digest": "70f0bd2c80b32f87896aeb27c363b8a2d37f40e22424f57fe1aad142e125ad67",
|
|
38
38
|
"files": [
|
|
39
39
|
"SKILL.md",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"getting-started",
|
|
51
51
|
"agent"
|
|
52
52
|
],
|
|
53
|
-
"version": "0.12.
|
|
53
|
+
"version": "0.12.2",
|
|
54
54
|
"digest": "2278adeb46a792356579395fcf73c42322cb23bcd0c61e20856ccabdad6762d1",
|
|
55
55
|
"files": [
|
|
56
56
|
"SKILL.md"
|
|
@@ -67,8 +67,8 @@
|
|
|
67
67
|
"sft",
|
|
68
68
|
"models"
|
|
69
69
|
],
|
|
70
|
-
"version": "0.12.
|
|
71
|
-
"digest": "
|
|
70
|
+
"version": "0.12.2",
|
|
71
|
+
"digest": "3ce10dee5d3c283d8b5fdea15134a58fc738c7af2c1bb19eb5a0bf70ea0bca13",
|
|
72
72
|
"files": [
|
|
73
73
|
"SKILL.md"
|
|
74
74
|
]
|
|
@@ -84,8 +84,8 @@
|
|
|
84
84
|
"prompt",
|
|
85
85
|
"models"
|
|
86
86
|
],
|
|
87
|
-
"version": "0.12.
|
|
88
|
-
"digest": "
|
|
87
|
+
"version": "0.12.2",
|
|
88
|
+
"digest": "be8bce8d9cf7241ccb60d2b2a9b7cc07d7755a76e8ff8ec1b0847c49efbb3469",
|
|
89
89
|
"files": [
|
|
90
90
|
"SKILL.md"
|
|
91
91
|
]
|
|
@@ -13,7 +13,7 @@ For first-time setup details, read `https://platform.toloka.ai/agents/fine-tunin
|
|
|
13
13
|
|
|
14
14
|
## Domain model
|
|
15
15
|
|
|
16
|
-
- **SFT** adapts model weights from representative chat examples. Each training row must follow the platform chat contract and end with the assistant response the model should learn to produce.
|
|
16
|
+
- **SFT** adapts model weights from representative chat examples. Each training row must follow the platform chat contract and end with the assistant response the model should learn to produce. Rows with tool calls also need `tools` declaring every function they call. Each call's `arguments` must be a string holding a JSON object (it is not checked against the function's `parameters`), call ids must be unique within a turn, and the `tool` replies must answer every call before the next turn. Cost estimation rejects rows that break these rules and names the first few in its error.
|
|
17
17
|
- A **Training** is an editable project-owned draft. A **Training Run** is one immutable, billable execution of a frozen draft and the rows of its slice.
|
|
18
18
|
- A run can start from a catalog **Base Model** or an exact existing **Model Version**. An explicit Model Version is the source; do not also select a Base Model.
|
|
19
19
|
- A completed run publishes a durable Model Version. It does not prove deployment or inference readiness.
|
|
@@ -163,6 +163,7 @@ Control and billing rules:
|
|
|
163
163
|
- `payment_window_expired` is final: the run is `failed`, cannot resume, and was not charged, even though `billingStatus` remains `payment_required`. A replacement run needs funds and new cost approval.
|
|
164
164
|
- Cancel only on explicit request, before output checks begin. Before training starts, cancellation is free. During training, it stops the GPU job and charges for GPU seconds used, with no Model Version. A startup cancellation may remain `stopping` until the job stops; wait rather than retrying cancel.
|
|
165
165
|
- `provider_failed` and `provider_timeout` are platform failures: no charge, full hold returned. Reported GPU usage remains visible.
|
|
166
|
+
- A `failed` or `canceled` run frees its estimate: the same estimate file can start one new run at the same `maximumCharge` until the estimate expires. Retry only an error with `retryable: true` (network, storage, or GPU capacity), and only after the user agrees.
|
|
166
167
|
|
|
167
168
|
Do not duplicate a slow run. Progress `queued` or `pending` means it is waiting for GPUs; training starts automatically. Training may also exceed the estimated duration. The charge stays capped at the approved `maximumCharge`; successful runs still publish a Model Version.
|
|
168
169
|
|
|
@@ -78,7 +78,7 @@ To train on a subset or reuse rows across Trainings, freeze a slice once every u
|
|
|
78
78
|
toloka dataset slice create <dataset-name> --name "<slice-name>" --json
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
-
Check that the examples demonstrate the desired behavior under the prompt: dynamic input in user messages, target output in the final assistant message, representative edge cases, and no prompt or answer leakage across validation.
|
|
81
|
+
Check that the examples demonstrate the desired behavior under the prompt: dynamic input in user messages, target output in the final assistant message, representative edge cases, and no prompt or answer leakage across validation. Rows with tool calls also need `tools` declaring every function they call. Each call's `arguments` must be a string holding a JSON object (it is not checked against the function's `parameters`), call ids must be unique within a turn, and the `tool` replies must answer every call before the next turn. Cost estimation rejects rows that break these rules and names the first few in its error.
|
|
82
82
|
|
|
83
83
|
### 3. Preserve the prompt and choose the source
|
|
84
84
|
|
|
@@ -170,6 +170,7 @@ Control and billing rules:
|
|
|
170
170
|
- `payment_window_expired` is final: the run is `failed`, cannot resume, and was not charged, even though `billingStatus` remains `payment_required`. A replacement run needs funds and new cost approval.
|
|
171
171
|
- Cancel only on explicit request, before output checks begin. Before training starts, cancellation is free. During training, it stops the GPU job and charges for GPU seconds used, with no Model Version. A startup cancellation may remain `stopping` until the job stops; wait rather than retrying cancel.
|
|
172
172
|
- `provider_failed` and `provider_timeout` are platform failures: no charge, full hold returned. Reported GPU usage remains visible.
|
|
173
|
+
- A `failed` or `canceled` run frees its estimate: the same estimate file can start one new run at the same `maximumCharge` until the estimate expires. Retry only an error with `retryable: true` (network, storage, or GPU capacity), and only after the user agrees.
|
|
173
174
|
|
|
174
175
|
Do not duplicate a slow run. Progress `queued` or `pending` means it is waiting for GPUs; training starts automatically. Training may also exceed the estimated duration. The charge stays capped at the approved `maximumCharge`; successful runs still publish a Model Version.
|
|
175
176
|
|
|
@@ -182,4 +183,4 @@ toloka model versions <model-id> --json
|
|
|
182
183
|
toloka model version download <model-version-id> --out <absolute-output-directory>
|
|
183
184
|
```
|
|
184
185
|
|
|
185
|
-
The downloaded folder contains full model weights (`config.json` and `model-*.safetensors`) and tokenizer files, including supported text sidecars such as `merges.txt` and `chat_template.jinja`. Keep the files together. The learned prompt is represented by `<|
|
|
186
|
+
The downloaded folder contains full model weights (`config.json` and `model-*.safetensors`) and tokenizer files, including supported text sidecars such as `merges.txt` and `chat_template.jinja`. Keep the files together. The learned prompt is represented by the special tokens `<|gist_0|>`, `<|gist_1|>`, and so on. A request must match training: the gist tokens first as plain text, then the conversation without the final assistant turn rendered by the tokenizer's chat template with `add_generation_prompt=True` and `enable_thinking=False`, without the original prompt. Send that string to a completions endpoint, because a chat endpoint wraps it in message markers; a system message holding only the gist tokens is the closest chat-only fallback and must be checked on validation rows. Verify serving separately with a compatible runtime; a successful download alone does not establish inference readiness.
|