@toloka-platform/sdk 0.7.1 → 0.8.0
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 +3 -3
- 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/docs/cli.md +1 -1
- package/package.json +2 -2
- package/skills/catalog.json +7 -7
- package/skills/toloka-build/references/workflow-and-cli.md +1 -1
- package/skills/toloka-gisting/SKILL.md +1 -1
- package/src/cli/commands/training.ts +2 -2
- package/src/pipeline-graph-v1.contract.json +0 -17
package/dist/cli/toloka.js
CHANGED
|
@@ -36,7 +36,7 @@ Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,(r)=>{l
|
|
|
36
36
|
`);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let g=Cu.test(a)?a.replace(Cu,"$1"):a;if(!g.match(/\S*Error: /)){for(let l of t){let d=l(g,e);if(d){r.push(d);break}}if(r.length>=mu)break}}return pu(r)}}class bu{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let i=wt(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 di(e,"DOMException")}isDOMError(e){return di(e,"DOMError")}}class Yo{match(e){return Sc(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 Zu{constructor(){}match(e){return Xc(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 yB=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class So{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(yB);if(n)t=n[1],i=n[2];return[t,i]}}var hu=["fatal","error","warning","log","info","debug"];function Xo(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 r=i.slice(0,n).join(", ");if(!(r.length>t)){if(n===i.length)return r;return r.length<=t?r:`${r.slice(0,t)}...`}}return""}class Eo{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 Di(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=Xo(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return wt(e)&&!Nc(e)&&hu.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(ru(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class fu{match(e){return Di(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Xo(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class To{match(e){return Vo(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class Wu{match(e){return di(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Di(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(Vo(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 yu{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 or={MESSAGE:"$message",TIMESTAMP:"$timestamp"},VB=new Set([or.MESSAGE,or.TIMESTAMP]),Jo={enabled:!0,max_bytes:32768};function Ma(e){if(!e)return{...Jo};return{enabled:e.enabled??Jo.enabled,max_bytes:RB(e.max_bytes,Jo.max_bytes)}}function BB(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,r)=>{if(VB.has(r))return t.push(r),n;return n[r]=e[r],n},{}),droppedKeys:t}}class Vu{constructor(e){this._entries=[],this._totalBytes=0,this._config=Ma(e)}setConfig(e){this._config=Ma(e),this._trimToMaxBytes()}add(e){let t=GB(e);if(!t)return;let i=Bu(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 RB(e,t){if(!er(e)||e===1/0||e===-1/0)return t;let i=Math.floor(e);if(i<0)return t;return i}function GB(e){let t;try{t=ji(e)}catch{return}try{let i=JSON.parse(t);if(!qn(i))return;let n=i,r=n[or.MESSAGE],o=n[or.TIMESTAMP];if(!wt(r)||r.trim().length===0)return;if(!wt(o)&&!er(o))return;return{step:n,json:t}}catch{return}}function Bu(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 Et 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 ci extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var wu=(e,t)=>{for(let i of Object.keys(t))if(i.startsWith("$feature/")||i==="$active_feature_flags")e[i]=t[i]};async function Ru(e){if(e instanceof Et){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 wB(e){return typeof e=="object"&&(e instanceof Et||Fu(e))}function Fu(e){return e instanceof ci}function FB(e){if(e instanceof Et)return e.status===502||e.status===504;if(!(e instanceof ci))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Ki(e){return typeof e=="object"&&e instanceof Et&&e.status===413}function sr(e){if(e instanceof Et)return e.status===408||e.status===429||e.status>=500;return Fu(e)}function Gu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var $a="default";class Uo{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new No([new Yo,new Eo,new So,new To],La())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Na,this._events=new _a,this._isInitialized=!1;let i=typeof e=="string"?e.trim():"",n=typeof t.host=="string"?t.host.trim():"",r=!i;if(this._logger=zc("[PostHog]",this.logMsgIfDebug.bind(this)),r)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=i,this.host=iu(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:sr},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)||r,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=!ka()||(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(Ue.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ue.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ue.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(wu(i,t),e.event==="$feature_flag_called"&&i.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())i=Mn(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 r=this.buildPayload({distinct_id:e,event:t,properties:i});this.enqueue("capture",r,n)})}async captureStatelessImmediate(e,t,i,n){let r=this.buildPayload({distinct_id:e,event:t,properties:i});await this.sendImmediate("capture",r,n)}aliasStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});this.enqueue("alias",r,n)})}async aliasStatelessImmediate(e,t,i,n){let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",r,n)}groupIdentifyStateless(e,t,i,n,r,o){this.wrap(()=>{let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});this.enqueue("capture",s,n)})}async groupIdentifyStatelessImmediate(e,t,i,n,r,o){let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});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={},r={},o=!1){await this._initPromise;let s=o?"&config=true":"",a=`${this.host}/flags/?v=2${s}`,g={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:n,...r};if(i.$device_id)g.$device_id=i.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)g.evaluation_contexts=this.evaluationContexts;let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(g)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:FB},this.featureFlagsRequestTimeoutMs).then((d)=>d.json()).then((d)=>({success:!0,response:va(d)})).catch((d)=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(e){if(e instanceof Et)return{type:"api_error",statusCode:e.status};if(e instanceof ci){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={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailStateless(e,t,i,n,r,o);if(s===void 0)return{response:void 0,requestId:void 0};let a=Ln(s.response);if(a===void 0)a=!1;return{response:a,requestId:s.requestId}}async getFeatureFlagDetailStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(t,i,n,r,o,[e]);if(s===void 0)return;return{response:s.flags[e],requestId:s.requestId,evaluatedAt:s.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagPayloadsStateless(t,i,n,r,o,[e]);if(!s)return;let a=s[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},i={},n={},r,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)).payloads}async getFeatureFlagsStateless(e,t={},i={},n={},r,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(e,t,i,n,r,o);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={},r,o){await this._initPromise;let s={geoip_disable:r??this.disableGeoip};if(o)s.flag_keys_to_evaluate=o;let a=await this.getFlags(e,t,i,n,s);if(!a.success)return;let g=a.response;if(g.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(g.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:g?.requestId,quotaLimited:g.quotaLimited};return g}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((r)=>{if(r.status!==200||!r.json){let o=`Surveys API could not be loaded: ${r.status}`,s=Error(o);this._logger.error(s),this._events.emit("error",Error(o));return}return r.json()}).catch((r)=>{this._logger.error("Surveys API could not be loaded",r),this._events.emit("error",r)}))?.surveys;if(n)this._logger.info("Surveys fetched from API: ",JSON.stringify(n));return n??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Ue.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Ue.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Ue.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return $a}persistedQueueKeyForRoute(e){return Ue.Queue}getActiveQueueRoutes(){return[$a]}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 r=this.persistedQueueKeyForRoute(this.getQueueRouteKey(n)),o=this.getPersistedProperty(r)||[];if(o.length>=this.maxQueueSize)o.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(o.push({message:n}),this.setPersistedProperty(r,o),this._events.emit(e,n),o.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=he(()=>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(r){this._events.emit("error",r)}}normalizeMessage(e){let{type:t,library:i,library_version:n,...r}=e,o=Gu(r.properties)?r.properties:void 0;if(i!==void 0&&o?.$lib===void 0)o={...o||{},$lib:i};if(n!==void 0&&o?.$lib_version===void 0)o={...o||{},$lib_version:n};if(o)r.properties=o;return r.uuid=Fo(r.uuid,Oe),r}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:Ta(),uuid:Fo(t?.uuid,Oe)};if(t?.disableGeoip??this.disableGeoip){if(!Gu(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 Ru(e)})}async waitForPendingPromises(e,t=[]){let i=t.filter((r)=>!!r),n=0;while(!0){let r=this.promiseQueue.getPromises([...i,...this.flushPromises],e);if(r.length===0)return;if(n>0)this._logger.debug(`flush() re-checking ${r.length} pending promise(s) before flushing`);await Promise.all(r.map((o)=>o.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(()=>Ja([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),Ja([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=$a){let n={api_key:this.apiKey,batch:e,sent_at:Ta()};if(this.historicalMigration)n.historical_migration=!0;let r=ji(n),o=`${this.host}/batch/`,s=this.disableCompression?null:await gi(r,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...s!==null&&{"Content-Encoding":"gzip"}},body:s||r};await(await this.fetchWithRetry(o,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(r){if(i===void 0)i=r}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 r=n.length,o=0;while(n.length>0&&o<r){let s=n.slice(0,this.maxBatchSize),a=s.map((d)=>d.message===void 0?d.message:this.normalizeMessage(d.message)),g=async()=>{let I=(this.getPersistedProperty(i)||[]).slice(s.length);this.setPersistedProperty(i,I),n=I,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:(d)=>{if(Ki(d))return!1;return sr(d)}};try{await this.sendBatch(a,l,e)}catch(d){if(Ki(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 ci))await g();throw this._events.emit("error",d),d}await g(),t.push(...a),o+=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 gi(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(Ki(o))return!1;return sr(o)}}),{kind:"ok"}}catch(o){if(Ki(o))return{kind:"too-large"};if(o instanceof ci)return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}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 gi(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(Ki(o))return!1;return sr(o)}}),{kind:"ok"}}catch(o){if(Ki(o))return{kind:"too-large"};if(sr(o))return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async fetchWithRetry(e,t,i,n){let r=t.body?t.body:"",o=-1;try{o=r instanceof Blob?r.size:Buffer.byteLength(r,tu)}catch{if(r instanceof Blob)o=r.size;else o=new TextEncoder().encode(r).length}return await nu(async()=>{let s=new AbortController,a=n??this.requestTimeout,g=he(()=>s.abort(),a),l=null;try{l=await this.fetch(e,{signal:s.signal,...t})}catch(I){throw new ci(I)}finally{clearTimeout(g)}if(t.mode!=="no-cors"&&(l.status<200||l.status>=400))throw new Et(l,o);return l},{...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 o=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(r){if(!wB(r))throw r;await Ru(r)}},n;try{return await Promise.race([new Promise((r,o)=>{n=he(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,o("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 ku=require("fs"),Pu=require("readline"),Oo=new Ne.ReduceableCache(25),Nu=new Ne.ReduceableCache(20),qa=7,NB=1000,xB=1e4;async function xu(e){let t={};for(let r=e.length-1;r>=0;r--){let o=e[r],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||EB(s)||TB(o))continue;if(!t[s])t[s]=[];t[s].push(o.lineno)}let i=Object.keys(t);if(i.length==0)return e;let n=[];for(let r of i){if(Nu.get(r))continue;let o=t[r];if(!o)continue;o.sort((g,l)=>g-l);let s=UB(o);if(s.every((g)=>JB(r,g)))continue;let a=OB(Oo,r,{});n.push(YB(r,s,a))}if(await Promise.all(n).catch(()=>{}),e&&e.length>0)SB(e,Oo);return Oo.reduce(),e}function YB(e,t,i){return new Promise((n)=>{let r=ku.createReadStream(e),o=Pu.createInterface({input:r});function s(){r.destroy(),n()}let a=0,g=0,l=t[g];if(l===void 0)return void s();let d=l[0],I=l[1];function C(){Nu.set(e,1),o.close(),o.removeAllListeners(),s()}r.on("error",C),o.on("error",C),o.on("close",s),o.on("line",(m)=>{if(a++,a<d)return;if(i[a]=zB(m,0),a>=I){if(g===t.length-1){o.close(),o.removeAllListeners();return}g++;let A=t[g];if(A===void 0){o.close(),o.removeAllListeners();return}d=A[0],I=A[1]}})})}function SB(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;XB(i.lineno,i,n)}}function XB(e,t,i){if(t.lineno===void 0||i===void 0)return;t.pre_context=[];for(let r=Yu(e);r<e;r++){let o=i[r];if(o===void 0)return void Hu(t);t.pre_context.push(o)}if(i[e]===void 0)return void Hu(t);t.context_line=i[e];let n=Su(e);t.post_context=[];for(let r=e+1;r<=n;r++){let o=i[r];if(o===void 0)break;t.post_context.push(o)}}function Hu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function EB(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function TB(e){if(e.lineno!==void 0&&e.lineno>xB)return!0;if(e.colno!==void 0&&e.colno>NB)return!0;return!1}function JB(e,t){let i=Oo.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 UB(e){if(!e.length)return[];let t=0,i=e[0];if(typeof i!="number")return[];let n=vu(i),r=[];while(!0){if(t===e.length-1){r.push(n);break}let o=e[t+1];if(typeof o!="number")break;if(o<=n[1])n[1]=o+qa;else r.push(n),n=vu(o);t++}return r}function vu(e){return[Yu(e),Su(e)]}function Yu(e){return Math.max(1,e-qa)}function Su(e){return e+qa}function OB(e,t,i){let n=e.get(t);if(n===void 0)return e.set(t,i),i;return n}function zB(e,t){let i=e,n=i.length;if(n<=150)return i;if(t>n)t=n;let r=Math.max(t-60,0);if(r<5)r=0;let o=Math.min(r+140,n);if(o>n-5)o=n;if(o===n)r=Math.max(o-140,0);if(i=i.slice(r,o),r>0)i=`...${i}`;if(o<n)i+="...";return i}var Li=require("path");function Xu(e=process.cwd()){let t=Li.sep==="\\",i=(r)=>t?r.replace(/\\/g,"/"):r,n=i(e);return async(r)=>{for(let o of r)if(!(!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:"))){if(Li.isAbsolute(o.filename))o.filename=i(Li.relative(n,i(o.filename)))}return r}}var Eu="5.46.1";var Ft={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class ui{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 r=this._flags[n];if(r)t[n]=r;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 r=n.enabled===!1?!1:n.variant??!0;if(e[`$feature/${i}`]=r,n.enabled)t.push(i)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new ui({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 r=[];if(this._errorsWhileComputing)r.push(Ft.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)r.push(Ft.QUOTA_LIMITED);if(t===void 0)r.push(Ft.FLAG_MISSING);if(r.length>0)n.$feature_flag_error=r.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:n})}}async function Tu(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((r)=>r.toString(16).padStart(2,"0")).join("")}var jB=60000,DB=1152921504606847000,_B=["is_not","is_set"];class Mi extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,Mi.prototype)}}function zu(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class U extends Error{constructor(e){super(e);zu(this,U)}}class Ct extends Error{constructor(e){super(e);zu(this,Ct)}}class eg{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:i,timeout:n,host:r,customHeaders:o,...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=r,this.poller=void 0,this.fetch=s.fetch||fetch,this.onError=s.onError,this.customHeaders=o,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={},r={}){return{distinctId:e,groups:t,personProperties:i,groupProperties:n,evaluationCache:r}}async getFeatureFlag(e,t,i={},n={},r={}){await this.loadFeatureFlags();let o,s;if(!this.loadedSuccessfullyOnce)return o;if(s=this.featureFlagsByKey[e],s!==void 0){let a=this.createEvaluationContext(t,i,n,r);try{o=(await this.computeFlagAndPayloadLocally(s,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(g){if(g instanceof Ct||g instanceof U)this.logMsgIfDebug(()=>console.debug(`${g.name} when computing flag locally: ${e}: ${g.message}`));else if(g instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${g}`))}}return o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let i={},n={},r=this.featureFlags.length==0,o=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,s={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(o.map(async(a)=>{try{let{value:g,payload:l}=await this.computeFlagAndPayloadLocally(a,s);if(i[a.key]=g,l)n[a.key]=l}catch(g){if(g instanceof Ct||g instanceof U)this.logMsgIfDebug(()=>console.debug(`${g.name} when computing flag locally: ${a.key}: ${g.message}`));else if(g instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${g}`));r=!0}})),{response:i,payloads:n,fallbackToFlags:r}}async computeFlagAndPayloadLocally(e,t,i={}){let{matchValue:n,skipLoadCheck:r=!1}=i;if(!r)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let o;o=n!==void 0?n:await this.computeFlagValueLocally(e,t);let s=this.getFeatureFlagPayload(e.key,o);return{value:o,payload:s}}async computeFlagValueLocally(e,t){let{distinctId:i,groups:n,personProperties:r,groupProperties:o}=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 g=this.groupTypeMapping[String(a)];if(!g)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(!(g 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"&&(r?.$device_id===void 0||r?.$device_id===null||r?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=o[g];return await this.matchFeatureFlagProperties(e,n[g],l,t)}{let g=this.getBucketingValueForFlag(e,i,r);if(g===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,g,r,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,r=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 '${r}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new U(`Flag dependency property for '${r}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new U(`Circular dependency detected for flag '${r}' (empty dependency chain)`);for(let a of o){if(!(a in n)){let l=this.featureFlagsByKey[a];if(l)if(l.active)try{let d=await this.computeFlagValueLocally(l,i);n[a]=d}catch(d){throw new U(`Error evaluating flag dependency '${a}' for flag '${r}': ${d}`)}else n[a]=!1;else throw new U(`Missing flag dependency '${a}' for flag '${r}'`)}if(n[a]==null)throw new U(`Dependency '${a}' could not be evaluated`)}let s=n[r];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 r=e.filters||{},o=r.groups||[],s=r.aggregation_group_type_index,a=r.early_exit??!1,{groups:g,groupProperties:l}=n,d=!1,I;for(let C of o)try{let m=C.aggregation_group_type_index!==void 0?C.aggregation_group_type_index:s,A=i,c=t;if(m!==s){if(m!=null){let p=this.groupTypeMapping[String(m)];if(!p||!(p in g)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${m} not available`));continue}if(!(p in l)){d=!0;continue}A=l[p],c=g[p]}}let u=await this.isConditionMatch(e,c,C,A,n);if(u==="match"){let p=C.variant,Z=r.multivariate?.variants||[];I=p&&Z.some((h)=>h.key===p)?p:await this.getMatchingVariant(e,c)||!0;break}if(a&&u==="out_of_rollout_bound")return!1}catch(m){if(m instanceof Ct)throw m;if(m instanceof U)d=!0;else throw m}if(I!==void 0)return I;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,r){let o=i.rollout_percentage,s=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((i.properties||[]).length>0){for(let a of i.properties){let g=a.type,l=!1;if(g==="cohort"){let d=await Du(a,n,this.cohorts,this.debugMode,(I)=>this.evaluateFlagDependency(I,n,r));l=a.operator==="not_in"?!d:d}else l=g==="flag"?await this.evaluateFlagDependency(a,n,r):ju(a,n,s);if(!l)return"no_match"}if(o==null)return"match"}if(o!=null&&await Ju(e.key,t)>o/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let i=await Ju(e.key,t,"variant"),n=this.variantLookupTable(e).find((r)=>i>=r.valueMin&&i<r.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(jB,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 Mi(`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 Mi(`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 Mi(`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(r){this.onError?.(Error(`Failed to store in cache: ${r}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(e){if(e instanceof Mi)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=he(()=>{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 Ju(e,t,i=""){let n=await Tu(`${e}.${t}${i}`);return parseInt(n.slice(0,15),16)/DB}function ju(e,t,i){let{key:n,value:r}=e,o=e.operator||"exact";if(n in t){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new U(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!_B.includes(o)){if(i)i(`Property ${n} cannot have a value of null/undefined with the ${o} operator`);return!1}function a(l,d){if(Array.isArray(l))return l.map((I)=>String(I).toLowerCase()).includes(String(d).toLowerCase());return String(l).toLowerCase()===String(d).toLowerCase()}function g(l,d,I){if(I==="gt")return l>d;if(I==="gte")return l>=d;if(I==="lt")return l<d;if(I==="lte")return l<=d;throw Error(`Invalid operator: ${I}`)}switch(o){case"exact":return a(r,s);case"is_not":return!a(r,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(r).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(r).toLowerCase());case"regex":return Uu(String(r))&&String(s).match(String(r))!==null;case"not_regex":return Uu(String(r))&&String(s).match(String(r))===null;case"gt":case"gte":case"lt":case"lte":{let l=typeof r=="number"?r:parseFloat(String(r)),d;if(d=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(l)&&Number.isFinite(d))return g(d,l,o);return g(String(s),String(r),o)}case"is_date_after":case"is_date_before":{if(typeof r=="boolean")throw new U("Date operations cannot be performed on boolean values");let l=$B(String(r));if(l==null)l=Ou(r);if(l==null)throw new U(`Invalid date: ${r}`);let d=Ou(s);if(["is_date_before"].includes(o))return d<l;return d>l}case"semver_eq":return De(ue(String(s)),ue(String(r)))===0;case"semver_neq":return De(ue(String(s)),ue(String(r)))!==0;case"semver_gt":return De(ue(String(s)),ue(String(r)))>0;case"semver_gte":return De(ue(String(s)),ue(String(r)))>=0;case"semver_lt":return De(ue(String(s)),ue(String(r)))<0;case"semver_lte":return De(ue(String(s)),ue(String(r)))<=0;case"semver_tilde":{let l=ue(String(s)),{lower:d,upper:I}=KB(String(r));return De(l,d)>=0&&De(l,I)<0}case"semver_caret":{let l=ue(String(s)),{lower:d,upper:I}=LB(String(r));return De(l,d)>=0&&De(l,I)<0}case"semver_wildcard":{let l=ue(String(s)),{lower:d,upper:I}=MB(String(r));return De(l,d)>=0&&De(l,I)<0}default:throw new U(`Unknown operator: ${o}`)}}function QB(e,t){if(!(e in t))throw new Ct(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Du(e,t,i,n=!1,r){let o=String(e.value);QB(o,i);let s=i[o];return _u(s,t,i,n,r)}async function _u(e,t,i,n=!1,r){if(!e)return!0;let{type:o,values:s}=e;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let g of s)try{let l=await _u(g,t,i,n,r);if(o==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof Ct)throw l;if(l instanceof U){if(n)console.debug(`Failed to compute property ${g} locally: ${l}`);a=!0}else throw l}if(a)throw new U("Can't match cohort without a given cohort property value");return o==="AND"}for(let g of s)try{let l;if(g.type==="cohort")l=await Du(g,t,i,n,r);else if(g.type==="flag"){if(!r)throw new U(`Flag dependency '${g.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await r(g)}else l=ju(g,t);let d=g.negation||!1;if(o==="AND"){if(!l&&!d)return!1;if(l&&d)return!1}else{if(l&&!d)return!0;if(!l&&d)return!0}}catch(l){if(l instanceof Ct)throw l;if(l instanceof U){if(n)console.debug(`Failed to compute property ${g} locally: ${l}`);a=!0}else throw l}if(a)throw new U("can't match cohort without a given cohort property value");return o==="AND"}function Uu(e){try{return new RegExp(e),!0}catch(t){return!1}}function Qu(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 ue(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("."),r=(g)=>{if(g===void 0||g==="")return 0;return Qu(g,e)},o=r(n[0]),s=r(n[1]),a=r(n[2]);return[o,s,a]}function De(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 KB(e){let t=ue(e),i=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:i,upper:n}}function LB(e){let t=ue(e),[i,n,r]=t,o=[i,n,r],s;return s=i>0?[i+1,0,0]:n>0?[0,n+1,0]:[0,0,r+1],{lower:o,upper:s}}function MB(e){let i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new U(`Invalid wildcard semver: ${e}`);let n=i.split("."),r=(g)=>{try{return Qu(g,e)}catch{throw new U(`Invalid wildcard semver: ${e}`)}},o=r(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let g=r(n[1]);s=[o,g,0],a=[o,g+1,0]}return{lower:s,upper:a}}function Ou(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 $B(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 r=parseInt(i.groups.number);if(r>=1e4)return null;let o=i.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-r);else if(o=="d")n.setUTCDate(n.getUTCDate()-r);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*r);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-r);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-r)}return n}}function qB(e,t){let i=!1;return Object.assign((n)=>{let o=global.process.listeners("uncaughtException").filter((s)=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;if(e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!i&&o)i=!0,t(n)},{_posthogErrorHandler:!0})}function Ku(e,t){globalThis.process?.on("uncaughtException",qB(e,t))}function Lu(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var eR=2000;class mt{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Pa({...Tc(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return qn(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,i,n,r){let o={...r},s=e.buildFromUnknown(t,i);return s.$exception_list=await e.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())Ku(this.onException.bind(this),this.onFatalError.bind(this)),Lu(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!mt.isPreviouslyCapturedError(e)){let i=await mt.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),r=i.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(r))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:r});return this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(eR),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class tg{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function tR(e){return e==="v0"||e==="v1"}function Mu(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return tR(e)?e:"v0"}var ar="analytics",gr="ai";function $u(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class $i extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:n}){super($i.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 r=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${i.length} undelivered`;if(n instanceof Error)r+=` (${n.message})`;return r}}function ig(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 iR(e){return typeof e=="string"?e:void 0}var nR=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:ig},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:ig},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:ig},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:iR}],rR=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function oR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sR(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 qu(e,t,i){if(i!==void 0&&!(t in e))e[t]=i}function aR(e){let i={...oR(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of nR)if(o in i){let g=a(i[o]);if(g!==void 0)n[s]=g;delete i[o]}let r={};for(let{property:o,field:s}of rR)if(o in i){let a=i[o];if(typeof a=="string")r[s]=a;delete i[o]}return delete i.$lib,delete i.$lib_version,qu(i,"$set",e.$set),qu(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:sR(e.timestamp),...r,options:n,properties:i}}function eC(e,{createdAt:t,historicalMigration:i}){let n={created_at:t,batch:e.map(aR)};if(i)n.historical_migration=!0;return n}var gR="/i/v1/analytics/events",lR=30000,dR=new Set([408,500,502,503,504]);class ng{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??lR,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((i)=>new Promise((n)=>he(n,i))),this.generateRequestId=t.generateRequestId??Oe,this.compress=t.compress??gi}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:n}=eC(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),r=`${this.config.host}${gR}`,o=[],s=n,a=Math.max(1,this.config.maxAttempts);for(let g=1;g<=a;g++){let l=g===a,d=ji({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:s}),I;try{I=await this.sendOnce(r,d,g,t)}catch(u){if(l)return this.surfaceBatchFailure(t,o,s,u);await this.sleep(this.backoffDelay(g));continue}let{status:C}=I;if(C<200||C>=300){if(!l&&dR.has(C)){let p=this.parseRetryAfter(I);await this.cancelBody(I),await this.sleep(this.backoffDelay(g,p));continue}let u=await this.buildHttpError(I,C);return this.surfaceBatchFailure(t,o,s,u)}let m;try{m=await this.parseResponse(I)}catch{return this.surfaceBatchFailure(t,o,s,Error(`Capture V1 returned an unparseable ${C} response body`))}let A=this.classify(s,m,o);if(A.length===0)return this.surfacePartialDrops(t,o);if(l)return void this.onError(new $i({requestId:t,drops:o,retryExhausted:A.map((u)=>u.uuid)}));s=A;let c=this.parseRetryAfter(I);await this.sleep(this.backoffDelay(g,c))}}async sendOnce(e,t,i,n){let r=this.buildHeaders(i,n),o=t;if(this.config.compressionEnabled){let g=await this.compress(t,this.config.isDebug);if(g!==null)o=g,r["Content-Encoding"]="gzip"}let s=new AbortController,a=he(()=>s.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:r,body:o,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??{},r=[];for(let o of e){let s=n[o.uuid];if(s){if(s.result==="drop")i.push({uuid:o.uuid,details:s.details??void 0});else if(s.result==="retry")r.push(o)}}return r}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 o=parseInt(i,10);return Number.isFinite(o)&&o>0?1000*o:void 0}let n=Date.parse(i);if(Number.isNaN(n))return;let r=n-this.now();return r>0?r: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 $i({requestId:e,drops:t,retryExhausted:i.map((r)=>r.uuid),cause:n}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new $i({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var IR=100,tC=30000,cR=50000,uR=50,CR=500,mR="https://us.i.posthog.com",iC=new Set;function zo(e,t){if(iC.has(e))return;iC.add(e),console.warn(`[PostHog] ${t}`)}function pR(e){return typeof e=="string"?e.trim():""}function AR(e){return(typeof e=="string"?e.trim():"")||void 0}function bR(e){return(typeof e=="string"?e.trim():"")||mR}function ZR(e){return(Array.isArray(e)?e:[e]).filter((i)=>typeof i=="string"&&i.trim().length>0)}function hR(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e))t[`$feature/${n}`]=r;let i=Object.keys(e).filter((n)=>e[n]!==!1).sort();if(i.length>0)t.$active_feature_flags=i;return t}class rg extends Uo{constructor(e,t={}){let i=pR(e),n={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:bR(t.host),personalApiKey:AR(t.secretKey??t.personalApiKey)};if(super(i,n),this._memoryStorage=new tg,this._minimalFlagCalledEvents=!1,this.options=n,this.captureMode=Mu(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof n.featureFlagsPollingInterval=="number"?Math.max(n.featureFlagsPollingInterval,IR):tC,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 eg({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:n.personalApiKey,projectApiKey:i,timeout:n.requestTimeout??1e4,host:this.host,fetch:n.fetch,onError:(o)=>{this._events.emit("error",o)},onLoad:(o)=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:(o)=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:n.flagDefinitionCacheProvider,strictLocalEvaluation:n.strictLocalEvaluation})}this.errorTracking=new mt(this,n,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=n.maxCacheSize||cR}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 o,s=new Promise((a)=>{o=a});try{e(s)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,i=this.options.waitUntilMaxWaitMs??CR,n=t>=i;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(n)return void this.resolveWaitUntilFlush();let r=this.options.waitUntilDebounceMs??uR;this._waitUntilCycle.timer=he(()=>{this.resolveWaitUntilFlush()},r)}_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"&&$u(e)?gr:ar}persistedQueueKeyForRoute(e){return e===gr?Ue.AiQueue:Ue.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[ar,gr]:[ar]}async sendBatch(e,t,i=ar){if(this.captureMode!=="v1"||i===gr)return super.sendBatch(e,t,i);let n=e.filter((r)=>r!==void 0);await this.getV1Sender().sendV1Batch(n)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new ng({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 Eu}get metrics(){if(!this._metrics)this._metrics=new vo(this,Ho(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:r,event:o,properties:s,options:a})=>{let g={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:r,event:o,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,l,g):this.enqueue(e,l,g)}).catch((r)=>{if(r)console.error(r)}))}_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:r,$anon_distinct_id:o,...s}=t,l={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:i},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,l={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,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=ZR(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=tC){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",(r)=>{clearTimeout(i),n(),t(r>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 r=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:o,disableGeoip:s}=i,{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=i,d=this.addLocalPersonAndGroupProperties(t,o,g,l);g=d.allPersonProperties,l=d.allGroupProperties;let I=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C,m=!1,A,c,u,p,Z,h,W;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,I,{matchValue:n});if(H){m=!0;let Y=H.value;p=V.id,h="Evaluated locally",W=V.has_experiment,C={key:e,enabled:Y!==!1,variant:typeof Y=="string"?Y:void 0,payload:H.payload??void 0}}}catch(H){if(H instanceof Ct||H instanceof U)this._logger?.info(`${H.name} when computing flag locally: ${e}: ${H.message}`);else throw H}}if(!m&&!a){let V=await super.getFeatureFlagDetailsStateless(I.distinctId,I.groups,g,l,s,[e]);if(V===void 0)u=Ft.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=V.minimalFlagCalledEvents===!0,A=V.requestId,c=V.evaluatedAt;let H=[];if(V.errorsWhileComputingFlags)H.push(Ft.ERRORS_WHILE_COMPUTING);if(V.quotaLimited?.includes("feature_flags"))H.push(Ft.QUOTA_LIMITED);let Y=V.flags[e];if(Y===void 0)H.push(Ft.FLAG_MISSING);else{p=Y.metadata?.id,Z=Y.metadata?.version,h=Y.reason?.description??Y.reason?.code,W=Y.metadata?.has_experiment;let v;if(Y.metadata?.payload!==void 0)try{v=JSON.parse(Y.metadata.payload)}catch{v=Y.metadata.payload}C={key:e,enabled:Y.enabled,variant:Y.variant,payload:v}}if(H.length>0)u=H.join(",")}}if(r){let V=C===void 0?void 0:C.enabled===!1?!1:C.variant??!0,H={$feature_flag:e,$feature_flag_response:V,$feature_flag_id:p,$feature_flag_version:Z,$feature_flag_reason:h,locally_evaluated:m,[`$feature/${e}`]:V,$feature_flag_request_id:A,$feature_flag_evaluated_at:m?Date.now():c};if(W!==void 0)H.$feature_flag_has_experiment=W;if(m&&this.featureFlagsPoller){let Y=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(Y!==void 0)H.$feature_flag_definitions_loaded_at=Y}if(u)H.$feature_flag_error=u;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:V,groups:o,disableGeoip:s,properties:H})}if(C!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)C={...C,payload:this._payloadOverrides[e]};return C}async getFeatureFlag(e,t,i){zo("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(zo("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 r=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:!1},i);if(r===void 0)return;return r.payload??null}async getFeatureFlagResult(e,t,i){let{distinctId:n,options:r}=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,{...r,sendFeatureFlagEvents:r?.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){zo("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:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=n||{},d=this.addLocalPersonAndGroupProperties(i,r,g,l);g=d.allPersonProperties,l=d.allGroupProperties;let I=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(I,s),m={},A={},c=!0;if(C)m=C.response,A=C.payloads,c=C.fallbackToFlags;if(c&&!a){let u=await super.getFeatureFlagsAndPayloadsStateless(I.distinctId,I.groups,g,l,o,s);m={...m,...u.flags||{}},A={...A,...u.payloads||{}}}if(this._flagOverrides!==void 0)m={...m,...this._flagOverrides};if(this._payloadOverrides!==void 0)A={...A,...this._payloadOverrides};return{featureFlags:m,featureFlagPayloads:A}}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 ui({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new ui({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,flags:{}});let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=n||{},d=this.addLocalPersonAndGroupProperties(i,r,g,l);g=d.allPersonProperties,l=d.allGroupProperties;let I=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C={},m,A,c=!1,u=!1,p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(I,s),Z=new Set;if(p)for(let[W,y]of Object.entries(p.response)){let V=this.featureFlagsPoller?.featureFlagsByKey[W];C[W]={key:W,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:p.payloads[W],id:V?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:V?.has_experiment},Z.add(W)}if((p?p.fallbackToFlags:!0)&&!a){let W=await super.getFeatureFlagDetailsStateless(I.distinctId,I.groups,g,l,o,s);if(W){this._minimalFlagCalledEvents=W.minimalFlagCalledEvents===!0,m=W.requestId,A=W.evaluatedAt,c=Boolean(W.errorsWhileComputingFlags),u=Array.isArray(W.quotaLimited)&&W.quotaLimited.includes("feature_flags");for(let[y,V]of Object.entries(W.flags)){if(Z.has(y))continue;let H;if(V.metadata?.payload!==void 0)try{H=JSON.parse(V.metadata.payload)}catch{H=V.metadata.payload}C[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[W,y]of Object.entries(this._flagOverrides)){if(y===void 0){delete C[W];continue}let V=C[W];C[W]={key:W,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[W,y]of Object.entries(this._payloadOverrides)){let V=C[W];if(V)C[W]={...V,payload:y}}return new ui({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,groups:r,disableGeoip:o,flags:C,requestId:m,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:c,quotaLimited:u})}_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:r,disableGeoip:o,properties:s}=e,a=r&&Object.keys(r).length>0?`_${JSON.stringify(Object.entries(r).sort(([l],[d])=>l<d?-1:l>d?1:0))}`:"",g=`${i}_${n}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(g))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(g);else this.distinctIdHasSentFlagCalls[t]=new Set([g]);this.capture({distinctId:t,event:"$feature_flag_called",properties:s,groups:r,disableGeoip:o})}_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:r}){this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:r}){await this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!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)=>he(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 r=new AbortController;n=he(()=>{r.abort()},this.options.requestTimeout),i.signal=r.signal}try{return await this.fetch(t,i)}catch(r){this._events.emit("error",r);return}finally{if(n)clearTimeout(n)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[r,o]of Object.entries(e))if(Ec(o)&&t&&r in t){let s={};for(let[a,g]of Object.entries(o))s[String(a)]=String(g);n[String(r)]=s}else i[String(r)]=String(o);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 r=n?.personProperties||{},o=n?.groupProperties||{},s=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let g={};for(let[l,d]of Object.entries(t||{}))g[l]=String(d);return await this.getAllFlags(e,{groups:g,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[l,d]of Object.entries(t||{}))g[l]=String(d);return await this.getAllFlags(e,{groups:g,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}return(await super.getFeatureFlagsStateless(e,t,r,o,i)).flags}addLocalPersonAndGroupProperties(e,t,i,n){let r={...i||{}},o={};if(t)for(let s of Object.keys(t))o[s]={$group_key:t[s],...n?.[s]||{}};return{allPersonProperties:r,allGroupProperties:o}}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,r){if(!mt.isPreviouslyCapturedError(e)){let o=Error("PostHog syntheticException");this.addPendingPromise(mt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,i).then((s)=>this._capturePreparedEvent({...s,uuid:n,flags:r},!1)))}}async captureExceptionImmediate(e,t,i,n){if(!mt.isPreviouslyCapturedError(e)){let r=Error("PostHog syntheticException");return this.addPendingPromise(mt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:r},t,i).then((o)=>this.captureImmediate({...o,flags:n})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:i,event:n,properties:r,groups:o,flags:s,sendFeatureFlags:a,timestamp:g,disableGeoip:l,uuid:d}=e,I=this.context?.get(),C=t.includeContextProperties??!0,m=i||I?.distinctId,A=C?{...this.props,...I?.properties||{},...r||{}}:{...r||{}};if(!m)m=Oe(),A.$process_person_profile=!1;if(C&&I?.sessionId&&!A.$session_id)A.$session_id=I.sessionId;let c=this._shouldSendMinimalFlagCalledEvent(n,A)?Mn(A):A,u=this._runBeforeSend({distinctId:m,event:n,properties:c,groups:o,flags:s,sendFeatureFlags:a,timestamp:g,disableGeoip:l,uuid:d});if(!u)return Promise.reject(null);let p=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){zo("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 Z=typeof a=="object"?a:void 0,h=await this.getFeatureFlagsForEvent(u.distinctId,o,l,Z);return hR(h)}return{}}).catch(()=>({})).then((Z)=>{let h=u.groups||o;return{...Z,...u.properties||{},...h!==void 0&&Object.keys(h).length>0?{$groups:h}:{}}});if(u.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof p.$raw_user_agent=="string"){if(kc(p.$raw_user_agent,this.options.custom_blocked_useragents||[]))u.event="$bot_pageview",p.$browser_type="bot"}return{distinctId:u.distinctId,event:u.event,properties:p,options:{timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let i=Array.isArray(t)?t:[t],n=e;for(let r of i){if(n=r(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 o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}}var nC=require("async_hooks");class og{constructor(){this.storage=new nC.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 fR(e,{organization:t,projectId:i,prefix:n,severityAllowList:r=["error"],sendExceptionsToPostHog:o=!0}={}){return(s)=>{if(!(r==="*"||r.includes(s.level)))return s;if(!s.tags)s.tags={};let g=s.tags[rC.POSTHOG_ID_TAG];if(g===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",d=new URL(`/project/${e.apiKey}/person/${g}`,l).toString();s.tags["PostHog Person URL"]=d;let I=s.exception?.values||[],C=I.map((A)=>({...A,stacktrace:A.stacktrace?{...A.stacktrace,type:"raw",frames:(A.stacktrace.frames||[]).map((c)=>({...c,platform:"node:javascript"}))}:void 0})),m={$exception_message:I[0]?.value||s.message,$exception_type:I[0]?.type,$exception_level:s.level,$exception_list:C,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:I[0]?.value||s.message,$sentry_exception_type:I[0]?.type,$sentry_tags:s.tags};if(t&&i)m.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+s.event_id;if(o)e.capture({event:"$exception",distinctId:g,properties:m});return s}}class rC{static#i=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,i,n,r){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(o,s){let a=s()?.getClient()?.getDsn()?.projectId;o(fR(e,{organization:t,projectId:a,prefix:i,severityAllowList:n,sendExceptionsToPostHog:r??!0}))}}}class sg extends rg{getLibraryId(){return"posthog-node"}initializeContext(){return new og}createErrorPropertiesBuilder(){return new Ne.ErrorPropertiesBuilder([new Ne.EventCoercer,new Ne.ErrorCoercer,new Ne.ObjectCoercer,new Ne.StringCoercer,new Ne.PrimitiveCoercer],Ne.createStackParser("node:javascript",Ne.nodeStackLineParser),[Fc(),xu,Xu()])}}class te extends Error{code;status;body;requestId;constructor(e,t,i,n,r){super(e);this.name="PotatoApiError",this.code=t,this.status=i,this.body=n,this.requestId=r}static fromResponse(e,t,i){let n=i===void 0?"":` (request id: ${i})`;return new te(`Potato API request failed with status ${e}${n}`,"http",e,t,i)}static waitTimeout(e){return new te(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class qi 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 qi(`Pipeline graph validation failed
|
|
38
38
|
${t}`,e)}}var Ge=require("fs/promises"),gC=require("os"),Ci=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 b(e,t,i){if(!e)throw new F(t,i)}var oC=(e)=>("disabled"in e)?void 0:`Hint: ${e.description}`,P={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>."},Tt={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>."},Ce={description:"Reinstall @toloka-platform/sdk to restore the bundled files."};class lr extends F{constructor(e,t){super(e,t);this.name="CredentialsError"}}var lC=(e)=>e.HOME??gC.homedir(),WR=(e)=>e.XDG_CONFIG_HOME??Ci.join(lC(e),".config"),_e=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??Ci.join(WR(e),"toloka","credentials.json"),dC=(e=process.env)=>Ci.join(lC(e),".toloka","credentials.json"),Do=(e=process.env)=>Ci.dirname(_e(e)),sC=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},pt=(e)=>{let t=sC(e.trim());try{let i=new URL(t);return i.hash="",i.search="",sC(i.toString())}catch{return t}},jo=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,yR=(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}},VR=(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 r=yR(n);if(r===void 0)return;Object.defineProperty(t,i,{value:r,writable:!0,enumerable:!0,configurable:!0})}return t},BR=(e,t)=>{let i=VR(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}},RR=(e)=>{let t=jo(e,"baseUrl"),i=jo(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},r=jo(e,"current"),o=jo(e,"projects");if(r===void 0&&o===void 0)return n;let s=BR(o,r);if(s===void 0)return;return{...n,...s}};async function dr(e){let t;try{t=await Ge.readFile(e,"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return"missing";return"invalid"}try{let i=RR(JSON.parse(t));return i===void 0?"invalid":{credentials:i}}catch{return"invalid"}}async function ag(e=process.env){let t=_e(e),i=await dr(t);if(i!=="missing"){if(i==="invalid")throw new lr(`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=dC(e),r=await dr(n);if(r==="missing")return;if(r==="invalid")throw new lr(`Invalid credentials file at ${n}. Run toloka logout, then toloka login.`,{hint:{disabled:!0}});return{credentials:r.credentials,path:n,legacy:!0}}async function en(e,t){try{return{found:await ag(e)}}catch(i){if(!(i instanceof lr)||t===void 0)throw i;return{found:void 0,warning:i.message}}}async function IC(e=process.env){return(await ag(e))?.credentials}async function Jt(e=process.env){let t=await ag(e);if(t!==void 0)return t;throw new lr(`No stored credentials found at ${_e(e)}. Run toloka login.`,{hint:{disabled:!0}})}var GR=(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}:{}}},aC=async(e)=>{try{let t=await Ge.lstat(e);b(!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 Ht(e){let t=Ci.dirname(e);await aC(t),await aC(e),await Ge.mkdir(t,{recursive:!0,mode:448}),await Ge.chmod(t,448)}async function Ir(e,t=process.env){let i=_e(t);return await Ht(i),await Ge.writeFile(i,`${JSON.stringify(GR(e),null,2)}
|
|
39
|
-
`,{mode:384}),await Ge.chmod(i,384),i}var wR=async(e)=>{try{return await Ge.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},gg=(e=process.env)=>[_e(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[dC(e)]:[]];async function cC(e=process.env){let t=[];for(let i of gg(e)){if(!await wR(i))continue;await Ge.rm(i,{force:!0}),t.push(i)}return t}var FR=16,uC=(e)=>e.length>FR?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var Qe=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},tn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var lg={name:"@toloka-platform/sdk",version:"0.
|
|
39
|
+
`,{mode:384}),await Ge.chmod(i,384),i}var wR=async(e)=>{try{return await Ge.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},gg=(e=process.env)=>[_e(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[dC(e)]:[]];async function cC(e=process.env){let t=[];for(let i of gg(e)){if(!await wR(i))continue;await Ge.rm(i,{force:!0}),t.push(i)}return t}var FR=16,uC=(e)=>e.length>FR?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var Qe=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},tn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var lg={name:"@toloka-platform/sdk",version:"0.8.0",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:"3b77aaf48605ba6980443e341f697877a08d6173"}};var fe=lg.name,oe=lg.version,dg=(e)=>{let t=/^(\d+)\.(\d+)\.(\d+)(?:-preview\.(\d+))?$/u.exec(e);if(t===null)return;let[,i,n,r,o]=t;return[Number(i),Number(n),Number(r),o===void 0?Number.POSITIVE_INFINITY:Number(o)]},CC=(e)=>{let t=dg(e);if(t===void 0)return;return t[3]===Number.POSITIVE_INFINITY?"latest":"preview"},Ig=(e,t)=>{let i=dg(e),n=dg(t);if(i===void 0||n===void 0)return;let r=Math.max(i.length,n.length);for(let o=0;o<r;o+=1){let s=i[o]??0,a=n[o]??0;if(s<a)return-1;if(s>a)return 1}return 0};var cr=(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},vR=(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!==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},mC=(e)=>e.filter((t)=>t!==void 0&&t.length>0).join(`
|
|
40
40
|
`),nn=(e)=>{if(e instanceof te)return e;if(e instanceof AggregateError)for(let t of e.errors){let i=nn(t);if(i!==void 0)return i}return e instanceof Error?nn(e.cause):void 0},Ut=(e)=>{if(e instanceof F){let t=nn(e.cause),i=t===void 0?[]:t.message===e.message?[cr(t)]:[t.message,cr(t)];return mC([e.message,...i,oC(e.hint)])}if(e instanceof te)return mC([e.message,cr(e),vR(e)]);return e instanceof Error?e.message:String(e)};var kR="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",PR="https://eu.posthog.com",NR={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0};function xR(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(tn(t))return!1;if(Qe(t))return!0;if(Qe(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if(Qe(e.CI??process.env.CI))return!1;if(Qe(process.env.VITEST))return!1;return!0}var YR={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},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}},SR={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},AC=(e)=>{let t=e[0];if(t===void 0)return"help";let i=YR[t];if(i===void 0)return SR[t]===!0?t:"unknown";let n=e[1],r=n===void 0?void 0:i[n];if(r===void 0)return t;if(r===!0)return`${t} ${n}`;let o=e[2];return o!==void 0&&r[o]===!0?`${t} ${n} ${o}`:`${t} ${n}`};function Qo(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(NR[n]===!0)i+=1;continue}t.push(n)}return AC(t)}function XR(e){if(e===void 0)return{error_code:"command_failed"};let t=nn(e);if(t!==void 0)return{error_code:t.code};if(e instanceof qi)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var ER=(e)=>{let t=nn(e);return t===void 0?{}:{status_code:t.status,request_id:t.requestId}},TR=(e)=>_o.join(_o.dirname(_e(e)),"anonymous-id"),JR=async(e)=>{let t=TR(e);await Ht(t);try{let n=(await mi.readFile(t,"utf8")).trim();if(n.length>0)return await mi.chmod(t,384),n}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ENOENT"))throw n}let i=pC.randomUUID();return await mi.writeFile(t,`${i}
|
|
41
41
|
`,{mode:384}),await mi.chmod(t,384),i},UR=()=>({shouldIdentify:!1,issueReportingEnabled:!1,identifyCurrentUser(){},captureCommand(){},async submitIssueReport(){b(!1,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.",{hint:{disabled:!0}})},async shutdown(){}});function bC(e){let{environment:t}=e;if(e.client===void 0&&!xR(t))return UR();let{client:i,distinctId:n}=e,r,o=[],s=(d)=>{o.push(d)};i?.on?.("error",s);let a=async()=>{if(i!==void 0&&n!==void 0)return;if(i===void 0){let d=new sg(kR,{host:PR,flushAt:1,flushInterval:0});d.on("error",s),i=d}n??=await JR(t)},g=()=>({sdk_version:oe,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),l=a().catch(()=>{});return{issueReportingEnabled:!0,shouldIdentify:!0,identifyCurrentUser(d){l=l.then(()=>{if(i===void 0||n===void 0)return;if(r===d.id)return;if(r=d.id,n!==d.id)i.alias({distinctId:d.id,alias:n});n=d.id}).catch(()=>{})},captureCommand(d){l=l.then(()=>{if(i===void 0||n===void 0)return;let I=g(),C=AC(d.command.split(" "));if(d.outcome==="failed"){let m=XR(d.error),A=ER(d.error);if(d.error!==void 0){let c=new F(`CLI command failed: ${m.error_code}`,{hint:{disabled:!0}});c.name="PotatoCliError",i.captureException(c,n,{...I,command:C,duration_ms:d.durationMs,exit_code:d.exitCode,$process_person_profile:!1,$geoip_disable:!0,...m,...A})}i.capture({distinctId:n,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...I,command:C,duration_ms:d.durationMs,exit_code:d.exitCode,...m,...A}});return}i.capture({distinctId:n,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...I,command:C,duration_ms:d.durationMs,exit_code:d.exitCode,outcome:d.outcome}})}).catch(()=>{})},submitIssueReport(d){let I=l.then(async()=>{b(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."}}),o.length=0,i.capture({distinctId:n,event:"sdk_cli_issue_report_submitted",disableGeoip:!0,properties:{...g(),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 C=o[0];if(o.length=0,C!==void 0)throw C});return l=I.catch(()=>{}),I},async shutdown(){try{await l,await i?.shutdown(2000)}catch{}}}}var wn=require("crypto"),Us=require("child_process"),Lr=require("events"),xt=require("fs"),D=require("fs/promises"),ae=require("path"),Os=require("stream"),Yb=require("stream/promises");var mr=require("fs"),Ai=require("path");var pi=()=>Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0,ur=(e,t=pi())=>t?{...e,BUN_BE_BUN:"1"}:e;var ZC=Ai.join("bin","toloka.js"),hC=(e)=>{try{return mr.realpathSync(e)}catch{return e}},Cr=(e)=>{let t=Ai.join(e,ZC);if(mr.existsSync(t))return t;let i=Ai.dirname(e);return i===e?void 0:Cr(i)},fC=(e=process.argv[1])=>(e===void 0?void 0:Cr(Ai.dirname(hC(e))))??Cr(process.cwd()),OR=(e=process.argv[1])=>{let t=e===void 0?void 0:hC(e);if(t!==void 0&&mr.existsSync(t)&&Cr(Ai.dirname(t))!==void 0)return t;let i=Cr(process.cwd());return b(i!==void 0,`Cannot locate the toloka CLI entry point. An installed @toloka-platform/sdk ships ${ZC} 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},Ko=(e,t,i={})=>{let n=i.executable??process.execPath;if(!(i.native??pi()))return{executable:i.executable??(Reflect.get(process.versions,"bun")?process.execPath:"bun"),args:[OR(i.runtimeEntry),...e],environment:t};let r={...t};return delete r.BUN_BE_BUN,{executable:n,args:[...e],environment:r}};var on=require("fs/promises"),WC=require("path");var rn="auto-update",yC={autoUpdate:!0};class Lo extends F{constructor(e,t){super(e,t);this.name="SettingsError"}}var VC=(e=process.env)=>WC.join(Do(e),"settings.json"),zR=(e)=>{let t=typeof e==="object"&&e!==null?Reflect.get(e,"autoUpdate"):void 0;if(typeof t!=="boolean")return yC;return{autoUpdate:t}};async function pr(e=process.env){try{return zR(JSON.parse(await on.readFile(VC(e),"utf8")))}catch{return yC}}async function jR(e,t=process.env){let i=VC(t);return await Ht(i),await on.writeFile(i,`${JSON.stringify({autoUpdate:e.autoUpdate},null,2)}
|
|
42
42
|
`,{mode:384}),await on.chmod(i,384),i}var DR=(e)=>{if(Qe(e))return!0;if(tn(e))return!1;throw new Lo(`Expected a boolean (true or false), got ${JSON.stringify(e)}.`,{hint:{description:"Run toloka config set auto-update true or false."}})},_R=(e)=>`${rn}=${e.autoUpdate}`,cg=(e,t)=>{if(t===void 0||t.length===0)return{output:_R(e)};if(t!==rn)throw new Lo(`Unknown setting "${t}". Known settings: ${rn}.`,{hint:{disabled:!0}});return{output:String(e.autoUpdate)}};async function BC(e,t,i){if(t!==rn)throw new Lo(`Unknown setting "${t}". Known settings: ${rn}.`,{hint:{disabled:!0}});let n={autoUpdate:DR(i)};return await jR(n,e),{settings:n,output:`Set ${rn} to ${n.autoUpdate}.`}}var wb=require("fs"),Fb=require("child_process"),Hb=require("module"),vb=require("events"),ti=require("fs/promises"),Nd=require("os"),ei=require("path");var wC=require("oxc-parser");var RC=require("oxc-parser"),ug=(e,t,i)=>{let n=RC.parseSync(e,t,{lang:i,preserveParens:!1});return n.errors.some((r)=>r.severity==="Error")?null:n.program},GC=(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 Cg=(e)=>{let t=KR(e.postprocess);if(!t||t.size===0)return[];let i=QR(e.code);if(!i||i.size===0)return[];return[...i].filter(([n])=>t.has(n)).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{let o=r===n?`path="${r}"`:`path="${r}" \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 (${o}). 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.`}})},QR=(e)=>{let t=ug("code.tsx",`(
|
|
@@ -115,7 +115,7 @@ ${e.code}
|
|
|
115
115
|
`),g=s.category===ze.default.DiagnosticCategory.Error?"error":"warning";R(s.file&&s.start!=null,"Diagnostic location is missing");let{line:l,character:d}=s.file.getLineAndCharacterOfPosition(r),{line:I,character:C}=s.file.getLineAndCharacterOfPosition(s.start),m=I-l,A=I===l?C-d:C,c=s.file.text.split(/\r?\n/gu)[I]??"",u=" ".repeat(C)+"^".repeat(s.length&&s.length>0?s.length:1);return{severity:g,text:[`${m}:${A+1} - [${ze.default.DiagnosticCategory[s.category]}] TS${s.code}`,a,"",c,u].join(`
|
|
116
116
|
`)}})};return{data:i(At.data),constants:i(At.constants),preprocess:i(At.preprocess),postprocess:i(At.postprocess),code:i(At.code)}},pg=(e,t)=>{let i=[0];for(let g=0;g<e.length;g+=1)if(e[g]===`
|
|
117
117
|
`)i.push(g+1);let n=(g)=>{let l=0;while(l+1<i.length&&i[l+1]<=g)l+=1;return{line:l,character:g-i[l]}},r=e.split(/\r?\n/gu),o=cF.map(([g,l])=>({key:g,start:e.indexOf(`/* ${l}_START */`)+`/* ${l}_START */`.length+1,end:e.indexOf(`/* ${l}_END */`)-1})),s=(g)=>{let l=o.find((C)=>g>=C.start&&g<=C.end);if(l)return l;let I=o.filter((C)=>C.start<=g).at(-1)??o[0];return R(I,"Task UI diagnostic block is missing"),I},a=uF();for(let g of t){let l=g.labels[0],d=l?.start??e.length,I=s(d),C=g.severity==="Error"?"error":"warning",{line:m,character:A}=n(I.start),{line:c,character:u}=n(d),p=c-m,Z=c===m?u-A:u,h=r[c]??"",W=l?l.end-l.start:0,y=" ".repeat(u)+"^".repeat(W>0?W:1);a[I.key].push({severity:C,text:[`${p}:${Z+1} - [${g.severity}]`,g.message,"",h,y].join(`
|
|
118
|
-
`)})}return a},NC=(e)=>{let t=pg(e,$o.parseSync("runtime.jsx",e).errors);return{...pg(e,$o.parseSync("runtime.tsx",e).errors),preprocess:t.preprocess,postprocess:t.postprocess}},xC=({reactDeclaration:e,elementsDeclaration:t})=>({performTypeCheck:async(i)=>{let n=HC(i),r=vt.createDefaultMapFromNodeModules({target:ze.default.ScriptTarget.Latest},ze.default,IF);r.set("node_modules/@types/react/index.d.ts",e),r.set("node_modules/elements/index.d.ts",t),r.set(sn,n);let o=vt.createSystem(r),{languageService:s}=vt.createVirtualTypeScriptEnvironment(o,[sn],ze.default,{target:ze.default.ScriptTarget.Latest,allowNonTsExtensions:!0,ignoreDeprecations:"6.0",module:ze.default.ModuleKind.CommonJS,moduleResolution:ze.default.ModuleResolutionKind.Node10,noEmit:!0,typeRoots:["node_modules/@types"],jsx:ze.default.JsxEmit.React,jsxFactory:"React.createElement",noErrorTruncation:!0}),a=[],g=[];try{a=s.getSyntacticDiagnostics(sn),g=[...s.getSemanticDiagnostics(sn),...s.getSuggestionDiagnostics(sn),...s.getCompilerOptionsDiagnostics()]}finally{s.dispose()}let l=PC(n,a),d=PC(n,[...a,...g]),I=NC(vC(i));return kC(d,l,I)},performSyntaxCheck:(i)=>{let n=HC(i),r=pg(n,$o.parseSync(sn,n).errors),o=NC(vC(i));return kC(r,r,o)}}),Ag=()=>xC({reactDeclaration:Ar.react.source,elementsDeclaration:Ar.elements.source});var Zg=require("crypto"),an=require("fs/promises"),SC=require("path");var XC="TOLOKA_CHECK_EVIDENCE_DIR",hg="TOLOKA_CHECK_PIPELINE_FINGERPRINT",fg="TOLOKA_CHECK_NODE_ID",Wg="TOLOKA_CHECK_TYPED_ONLY",mF=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),pF=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),bg=(e)=>{if(Array.isArray(e))return e.map(bg);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,bg(i)]))},yg=(e)=>Zg.createHash("sha256").update(JSON.stringify(bg(e))).digest("hex"),AF=(e,t)=>`[toloka:${e}:${t??"pipeline"}]`,YC=(e)=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),EC=(e,t)=>t===void 0?YC(`[toloka:${e}:`):YC(AF(e,t));var bF=(e)=>e==="code"||e==="ui"||e==="pipeline",ZF=(e)=>e==="passed"||e==="failed"||e==="infrastructure_error",hF=(e,t)=>{R(mF(e),`Invalid test evidence ${t}`);let i=e;R(i.version===1,`Unsupported test evidence version in ${t}`),R(typeof i.pipelineFingerprint==="string",`Missing pipeline fingerprint in ${t}`),R(bF(i.kind),`Invalid test evidence kind in ${t}`),R(ZF(i.status),`Invalid test evidence status in ${t}`),R(typeof i.testName==="string",`Missing test name in ${t}`),R(i.nodeId===void 0||typeof i.nodeId==="string",`Invalid node id in ${t}`),R(i.diagnostic===void 0||typeof i.diagnostic==="string",`Invalid diagnostic in ${t}`),R(i.partial===void 0||typeof i.partial==="boolean",`Invalid partial coverage in ${t}`),R(i.untestedHardwareFields===void 0||pF(i.untestedHardwareFields),`Invalid hardware fields in ${t}`);let n=i.untestedHardwareFields;return{version:1,pipelineFingerprint:i.pipelineFingerprint,kind:i.kind,status:i.status,testName:i.testName,...i.nodeId===void 0?{}:{nodeId:i.nodeId},...i.diagnostic===void 0?{}:{diagnostic:i.diagnostic},...i.partial===void 0?{}:{partial:i.partial},...n===void 0?{}:{untestedHardwareFields:n}}};var TC=async(e)=>{let i=(await an.readdir(e,{withFileTypes:!0})).filter((n)=>n.isFile()&&n.name.endsWith(".json")).map((n)=>n.name).toSorted();return Promise.all(i.map(async(n)=>{let r=SC.join(e,n),o;try{o=JSON.parse(await an.readFile(r,"utf8"))}catch(s){throw Error(`Invalid test evidence ${r}`,{cause:s})}return hF(o,r)}))};var fF={POTATO_API_KEY:"TOLOKA_API_KEY",POTATO_BASE_URL:"TOLOKA_BASE_URL",POTATO_PROJECT_ID:"TOLOKA_PROJECT_ID"},br=["TOLOKA_API_KEY","POTATO_API_KEY"],JC=(e)=>{let t={...e},i=[];for(let[n,r]of Object.entries(fF)){let o=e[n];if(o===void 0)continue;t[r]??=o,i.push(`${n} is deprecated and will stop being read; set ${r} instead.`)}return{environment:t,warnings:i}};var Qr=require("fs/promises"),He=require("path"),Zb=require("url");var Ib=Pe(hd(),1),cb=Pe(gb(),1);var lb={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{default:[],type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{default:[],type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{default:[],type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.6-terra"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","gemini-3.7-flash","claude-sonnet-5","claude-opus-5","claude-fable-5","gpt-5.6-terra","gpt-5.6-luna","gpt-5.6-sol"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"},maxCostPerAttempt:{type:"number"}},required:["audienceType","maxCostPerAttempt"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","annotation_qa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.6-terra"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","annotation_qa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var ub=new Ib.default({strict:!1});cb.default(ub);var db=ub.compile(lb),V2=(e)=>{let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return{path:typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/",reason:e.message??`failed ${e.keyword} validation`}};function Hd(e){if(db(e))return;let t=db.errors;R(t,"Pipeline graph validation failed without errors");let i=new Set,n=[];for(let r of t){let o=V2(r),s=`${o.path}
|
|
118
|
+
`)})}return a},NC=(e)=>{let t=pg(e,$o.parseSync("runtime.jsx",e).errors);return{...pg(e,$o.parseSync("runtime.tsx",e).errors),preprocess:t.preprocess,postprocess:t.postprocess}},xC=({reactDeclaration:e,elementsDeclaration:t})=>({performTypeCheck:async(i)=>{let n=HC(i),r=vt.createDefaultMapFromNodeModules({target:ze.default.ScriptTarget.Latest},ze.default,IF);r.set("node_modules/@types/react/index.d.ts",e),r.set("node_modules/elements/index.d.ts",t),r.set(sn,n);let o=vt.createSystem(r),{languageService:s}=vt.createVirtualTypeScriptEnvironment(o,[sn],ze.default,{target:ze.default.ScriptTarget.Latest,allowNonTsExtensions:!0,ignoreDeprecations:"6.0",module:ze.default.ModuleKind.CommonJS,moduleResolution:ze.default.ModuleResolutionKind.Node10,noEmit:!0,typeRoots:["node_modules/@types"],jsx:ze.default.JsxEmit.React,jsxFactory:"React.createElement",noErrorTruncation:!0}),a=[],g=[];try{a=s.getSyntacticDiagnostics(sn),g=[...s.getSemanticDiagnostics(sn),...s.getSuggestionDiagnostics(sn),...s.getCompilerOptionsDiagnostics()]}finally{s.dispose()}let l=PC(n,a),d=PC(n,[...a,...g]),I=NC(vC(i));return kC(d,l,I)},performSyntaxCheck:(i)=>{let n=HC(i),r=pg(n,$o.parseSync(sn,n).errors),o=NC(vC(i));return kC(r,r,o)}}),Ag=()=>xC({reactDeclaration:Ar.react.source,elementsDeclaration:Ar.elements.source});var Zg=require("crypto"),an=require("fs/promises"),SC=require("path");var XC="TOLOKA_CHECK_EVIDENCE_DIR",hg="TOLOKA_CHECK_PIPELINE_FINGERPRINT",fg="TOLOKA_CHECK_NODE_ID",Wg="TOLOKA_CHECK_TYPED_ONLY",mF=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),pF=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),bg=(e)=>{if(Array.isArray(e))return e.map(bg);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,bg(i)]))},yg=(e)=>Zg.createHash("sha256").update(JSON.stringify(bg(e))).digest("hex"),AF=(e,t)=>`[toloka:${e}:${t??"pipeline"}]`,YC=(e)=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),EC=(e,t)=>t===void 0?YC(`[toloka:${e}:`):YC(AF(e,t));var bF=(e)=>e==="code"||e==="ui"||e==="pipeline",ZF=(e)=>e==="passed"||e==="failed"||e==="infrastructure_error",hF=(e,t)=>{R(mF(e),`Invalid test evidence ${t}`);let i=e;R(i.version===1,`Unsupported test evidence version in ${t}`),R(typeof i.pipelineFingerprint==="string",`Missing pipeline fingerprint in ${t}`),R(bF(i.kind),`Invalid test evidence kind in ${t}`),R(ZF(i.status),`Invalid test evidence status in ${t}`),R(typeof i.testName==="string",`Missing test name in ${t}`),R(i.nodeId===void 0||typeof i.nodeId==="string",`Invalid node id in ${t}`),R(i.diagnostic===void 0||typeof i.diagnostic==="string",`Invalid diagnostic in ${t}`),R(i.partial===void 0||typeof i.partial==="boolean",`Invalid partial coverage in ${t}`),R(i.untestedHardwareFields===void 0||pF(i.untestedHardwareFields),`Invalid hardware fields in ${t}`);let n=i.untestedHardwareFields;return{version:1,pipelineFingerprint:i.pipelineFingerprint,kind:i.kind,status:i.status,testName:i.testName,...i.nodeId===void 0?{}:{nodeId:i.nodeId},...i.diagnostic===void 0?{}:{diagnostic:i.diagnostic},...i.partial===void 0?{}:{partial:i.partial},...n===void 0?{}:{untestedHardwareFields:n}}};var TC=async(e)=>{let i=(await an.readdir(e,{withFileTypes:!0})).filter((n)=>n.isFile()&&n.name.endsWith(".json")).map((n)=>n.name).toSorted();return Promise.all(i.map(async(n)=>{let r=SC.join(e,n),o;try{o=JSON.parse(await an.readFile(r,"utf8"))}catch(s){throw Error(`Invalid test evidence ${r}`,{cause:s})}return hF(o,r)}))};var fF={POTATO_API_KEY:"TOLOKA_API_KEY",POTATO_BASE_URL:"TOLOKA_BASE_URL",POTATO_PROJECT_ID:"TOLOKA_PROJECT_ID"},br=["TOLOKA_API_KEY","POTATO_API_KEY"],JC=(e)=>{let t={...e},i=[];for(let[n,r]of Object.entries(fF)){let o=e[n];if(o===void 0)continue;t[r]??=o,i.push(`${n} is deprecated and will stop being read; set ${r} instead.`)}return{environment:t,warnings:i}};var Qr=require("fs/promises"),He=require("path"),Zb=require("url");var Ib=Pe(hd(),1),cb=Pe(gb(),1);var lb={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.6-terra"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","gemini-3.7-flash","claude-sonnet-5","claude-opus-5","claude-fable-5","gpt-5.6-terra","gpt-5.6-luna","gpt-5.6-sol"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"},maxCostPerAttempt:{type:"number"}},required:["audienceType","maxCostPerAttempt"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","annotation_qa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.6-terra"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","annotation_qa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var ub=new Ib.default({strict:!1});cb.default(ub);var db=ub.compile(lb),V2=(e)=>{let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return{path:typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/",reason:e.message??`failed ${e.keyword} validation`}};function Hd(e){if(db(e))return;let t=db.errors;R(t,"Pipeline graph validation failed without errors");let i=new Set,n=[];for(let r of t){let o=V2(r),s=`${o.path}
|
|
119
119
|
${o.reason}`;if(i.has(s))continue;i.add(s),n.push(o)}throw qi.fromIssues(n)}var B2=Symbol("fieldDefinition"),R2=Symbol.for("@toloka-platform/sdk/pipeline-definition"),mb=Symbol("portDefinition"),G2=Symbol("nodeFieldReferences");function pb(e,t){return{node:e,handle:t,direction:"input",[mb]:"input"}}function Ab(e,t){return{node:e,handle:t,direction:"output",[mb]:"output"}}function bb(e){return typeof e==="object"&&e!==null&&B2 in e}function vd(e,t){if(bb(e)){t.push(e);return}if(Array.isArray(e)){for(let i of e)vd(i,t);return}if(typeof e==="object"&&e!==null)for(let i of Object.values(e))vd(i,t)}function w2(e){let t=[];return vd(e,t),t}function Cb(e){return bb(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function F2(e,t={}){R(typeof e==="object"&&e!==null&&!Array.isArray(e),"root() defines the single pipeline boundary; call root({ started, completed }) without a name");let i=t.id??"root",{started:n,completed:r,...o}=e;return{id:i,type:"root",settings:{...o,startedFieldProxies:{output:n.map(Cb)},completedFieldProxies:{input:r.map(Cb)}},started:Ab(i,"started"),completed:pb(i,"completed"),[G2]:w2(e)}}var mD=Object.assign(F2,{started:Ab("root","started"),completed:pb("root","completed")});function H2(e){return typeof e==="object"&&e!==null&&R2 in e}function Ss(e){R(H2(e),"Invalid pipeline definition: expected a value returned by definePipeline"),R(e.dataset.length>0,"Dataset name must not be empty");for(let t of e.graph.nodes){if(t.type!=="root")continue;R(!("datasetId"in t.settings),"An unresolved pipeline definition cannot contain a dataset id"),R(!("itemFilter"in t.settings),"An unresolved pipeline definition cannot contain a dataset item filter")}Hd(e.graph)}function _r(e,t){let i={version:e.graph.version,fields:e.graph.fields.map((n)=>({...n})),nodes:e.graph.nodes.map((n)=>n.type==="root"?{...n,settings:{...n.settings,datasetId:t.datasetId}}:n),connections:e.graph.connections.map((n)=>({from:{...n.from},to:{...n.to},settings:{...n.settings}}))};return Hd(i),i}var hb=async(e)=>{let t;try{t=await Qr.readdir(e,{withFileTypes:!0})}catch(n){if(n instanceof Error&&Reflect.get(n,"code")==="ENOENT")return[];throw n}let i=[];for(let n of t.toSorted((r,o)=>r.name.localeCompare(o.name))){let r=He.join(e,n.name);if(n.isDirectory())i.push(...await hb(r));else if(n.isFile()&&n.name==="pipeline.ts")i.push(r)}return i},v2="toloka.json",k2=async(e)=>{try{return(await Qr.stat(He.join(e,v2))).isFile()}catch{return!1}};async function fb(e){let t=He.resolve(e);for(;;){if(await k2(t))return t;let i=He.dirname(t);if(i===t)return;t=i}}async function Rn(e){let t=await hb(He.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(n)=>{let r=await Qr.stat(n),o=Zb.pathToFileURL(n);o.searchParams.set("version",`${r.mtimeMs}-${r.size}`);let s=await import(o.href);b(typeof s==="object"&&s!==null,`Invalid ${n}: expected a module`,{hint:{description:"Make the file a TypeScript module that exports the pipeline definition."}});let a=Reflect.get(s,"default");Ss(a);let g=He.relative(e,He.dirname(n)).split(He.sep).join("/");return{sourceDirectory:g,name:He.basename(g),definition:a}}))).toSorted((n,r)=>n.sourceDirectory.localeCompare(r.sourceDirectory))}}class Gn extends F{phase;constructor(e,t,i){super(t,i);this.name="FreshCheckProcessError",this.phase=e}}var Wb=5000,P2=65536,ii="TOLOKA_INTERNAL_CHECK_RESULT_FILE",N2=(e)=>e.message.length<=Wb?e:{...e,message:`${e.message.slice(0,Wb)}
|
|
120
120
|
\u2026output truncated`},kd=20,yb=async(e)=>{let t=[],i=0,n=!1;for await(let o of e){let s=Buffer.isBuffer(o)?o:Buffer.from(o),a=P2-i;if(a>0){let g=s.subarray(0,a);t.push(g),i+=g.length}if(s.length>a)n=!0}let r=Buffer.concat(t).toString("utf8");return n?`${r}
|
|
121
121
|
\u2026output truncated`:r},xd=async(e,t,i,n,r)=>{r?.throwIfAborted();let o=Fb.spawn(t,i,{cwd:e,env:n,stdio:["ignore","pipe","pipe"]}),s=()=>o.kill("SIGTERM");if(r?.addEventListener("abort",s,{once:!0}),r?.aborted===!0)s();try{let[a,g,l]=await Promise.all([vb.once(o,"close"),yb(o.stdout),yb(o.stderr)]),d=a[0];return typeof d==="number"?{exitCode:d,stdout:g,stderr:l}:{exitCode:2,stdout:g,stderr:[l,`Process terminated by ${String(a[1])}`].filter(Boolean).join(`
|
|
@@ -393,7 +393,7 @@ More metrics exist than the server returns.`:i},yE=(e)=>{let t=ge([["Metric",e.k
|
|
|
393
393
|
|
|
394
394
|
Not every recorded point is shown: the series is thinned to fit --resolution, and a very long run keeps only its most recent points.`:"";return`${t}
|
|
395
395
|
|
|
396
|
-
${i}${n}`},Jy=async(e,t,i)=>{let n=await e.trainings.getRunMetrics({trainingRunId:t.trainingRunId});ie(i,t.json,n,WE(n))},Uy=async(e,t,i)=>{let n=await e.trainings.getRunMetricHistory({trainingRunId:t.trainingRunId,metricKey:t.metricKey,resolution:t.resolution});ie(i,t.json,n,yE(n))};var Oy=(e,t)=>{let{context:i,globals:n}=t,r=e.command("training").description("manage project Training drafts");r.command("list").option("--json","print JSON",!1).description("list active Trainings owned by the selected project").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);S(a),await wy(s,{projectId:a,json:o.json},i.io)}),r.command("get").argument("<name-or-id>","Training name or ID").option("--json","print JSON",!1).description("show one Training draft").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Fy(a,{projectId:g,nameOrId:o,json:s.json},i.io)}),r.command("create").argument("<name>","new Training name").option("--method <method>","Training method",hh,"sft").option("--base-model <id>","catalog Base Model source",Sn).option("--model-version <id>","exact Model Version source").requiredOption("--dataset <id>","required training Dataset ID").option("--validation-dataset <id>","optional validation Dataset ID").option("--train-filter <field=value>","training Dataset field equality filter").option("--validation-filter <field=value>","validation Dataset field equality filter").option("--lora-rank <rank>","SFT LoRA adapter rank: 8, 16, or 32 (default 16)",CI).option("--gist-tokens <count>",'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default
|
|
396
|
+
${i}${n}`},Jy=async(e,t,i)=>{let n=await e.trainings.getRunMetrics({trainingRunId:t.trainingRunId});ie(i,t.json,n,WE(n))},Uy=async(e,t,i)=>{let n=await e.trainings.getRunMetricHistory({trainingRunId:t.trainingRunId,metricKey:t.metricKey,resolution:t.resolution});ie(i,t.json,n,yE(n))};var Oy=(e,t)=>{let{context:i,globals:n}=t,r=e.command("training").description("manage project Training drafts");r.command("list").option("--json","print JSON",!1).description("list active Trainings owned by the selected project").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);S(a),await wy(s,{projectId:a,json:o.json},i.io)}),r.command("get").argument("<name-or-id>","Training name or ID").option("--json","print JSON",!1).description("show one Training draft").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Fy(a,{projectId:g,nameOrId:o,json:s.json},i.io)}),r.command("create").argument("<name>","new Training name").option("--method <method>","Training method",hh,"sft").option("--base-model <id>","catalog Base Model source",Sn).option("--model-version <id>","exact Model Version source").requiredOption("--dataset <id>","required training Dataset ID").option("--validation-dataset <id>","optional validation Dataset ID").option("--train-filter <field=value>","training Dataset field equality filter").option("--validation-filter <field=value>","validation Dataset field equality filter").option("--lora-rank <rank>","SFT LoRA adapter rank: 8, 16, or 32 (default 16)",CI).option("--gist-tokens <count>",'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default "1/8")',mI).option("--epochs <count>","training epochs, 1 through 5 (default 3)",pI).option("--learning-rate <rate>","optimizer learning rate (default 0.00015 for SFT, 0.03 for gisting)",AI).option("--batch-size <count>","sequences per optimizer step: 8, 16, 32, or 64 (default 8)",bI).option("--max-sequence-length <tokens>","token budget per example, 64 through 16384 (default 12288 for SFT, 3072 for gisting)",ZI).option("--prompt-file <path>","gisting prompt text file").option("--json","print JSON",!1).description("create a normalized Training draft").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Hy(a,{...hI(s),projectId:g,name:o,json:s.json},i.io)}),r.command("update").argument("<name-or-id>","Training name or ID").option("--base-model <id>","catalog Base Model source",Sn).option("--model-version <id>","exact Model Version source").option("--dataset <id>","required training Dataset ID").option("--validation-dataset <id>","replacement validation Dataset ID").option("--train-filter <field=value>","replacement training Dataset field equality filter").option("--validation-filter <field=value>","replacement validation Dataset field equality filter").option("--lora-rank <rank>","SFT LoRA adapter rank: 8, 16, or 32 (default 16)",CI).option("--gist-tokens <count>",'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default "1/8")',mI).option("--epochs <count>","training epochs, 1 through 5 (default 3)",pI).option("--learning-rate <rate>","optimizer learning rate (default 0.00015 for SFT, 0.03 for gisting)",AI).option("--batch-size <count>","sequences per optimizer step: 8, 16, 32, or 64 (default 8)",bI).option("--max-sequence-length <tokens>","token budget per example, 64 through 16384 (default 12288 for SFT, 3072 for gisting)",ZI).option("--prompt-file <path>","replacement gisting prompt text file").option("--json","print JSON",!1).description("replace the complete Training draft").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await vy(a,{...hI(s),projectId:g,nameOrId:o,json:s.json},i.io)}),r.command("cost").argument("<name-or-id>","Training name or ID").option("--idempotency-key <key>","reuse one Cost Estimate input preparation").option("--json","print JSON",!1).description("validate Training inputs and calculate the maximum charge").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Py(a,{projectId:g,nameOrId:o,idempotencyKey:s.idempotencyKey,json:s.json},i.io)}),r.command("run").argument("<name-or-id>","Training name or ID").option("--estimate-file <path>","ready Training Cost Estimate JSON").option("--version-name <name>","unique Model Version name for this run").option("--idempotency-key <key>","reuse one Training Run creation").option("--json","print JSON",!1).description("calculate a ready Cost Estimate and create one queued Training Run").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Ny(a,{projectId:g,nameOrId:o,...s},i.io)}),r.command("runs").argument("<name-or-id>","Training name or ID").option("--json","print JSON",!1).description("list Training Run history").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await xy(a,{projectId:g,nameOrId:o,json:s.json},i.io)}),r.command("status").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("show one Training Run").action(async(o,s)=>{let{client:a}=await w(n(),i);await Yy(a,{trainingRunId:o,json:s.json},i.io)}),r.command("resume").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("resume a Training Run blocked on funds or payment").action(async(o,s)=>{let{client:a}=await w(n(),i);await Sy(a,{trainingRunId:o,json:s.json},i.io)}),r.command("cancel").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("cancel a Training Run before provider work completes").action(async(o,s)=>{let{client:a}=await w(n(),i);await Xy(a,{trainingRunId:o,json:s.json},i.io)}),r.command("metrics").argument("<training-run-id>","Training Run ID").option("--key <metric>","read the point history of one metric instead of the summary").option("--resolution <count>","history points to return, 2 to 500 (default 200)",Te).option("--json","print JSON",!1).description("read Training Run metrics").action(async(o,s)=>{let{client:a}=await w(n(),i);if(s.key===void 0){await Jy(a,{trainingRunId:o,json:s.json},i.io);return}await Uy(a,{trainingRunId:o,metricKey:s.key,resolution:s.resolution,json:s.json},i.io)}),r.command("logs").argument("<training-run-id>","Training Run ID").option("--follow","wait for new log entries until complete",!1).description("read sanitized Training Run logs").action(async(o,s)=>{let{client:a}=await w(n(),i);await Ey(a,{trainingRunId:o,follow:s.follow},i.io)})};var zy=require("fs"),jy=require("os"),ke=require("path");var VE=`${ke.sep}install${ke.sep}global${ke.sep}`,Ga=(e)=>{try{return zy.realpathSync(e)}catch{return e}},BE=(e,t,i,n)=>{if(Ga(e).includes(VE))return"global-registry";if(Ga(n)===t)return"linked";if(ke.dirname(ke.resolve(e))===ke.resolve(i))return"linked";return"project-local"},Dy=(e=process.argv[1],t={})=>{if(t.native??pi())return{version:oe,commit:"3b77aaf48605",channel:"native",path:Ga(t.executablePath??process.execPath)};b(e,"CLI entry path is unavailable",{hint:P});let i=t.globalBinDirectory??ke.resolve(process.env.BUN_INSTALL??ke.join(jy.homedir(),".bun"),"bin"),n=t.globalPackageDirectory??ke.resolve(i,"..","install","global","node_modules","@toloka-platform","sdk"),r=ke.resolve(ke.dirname(Ga(e)),".."),o=BE(e,r,i,n);return{version:oe,commit:"3b77aaf48605",channel:o,...o==="linked"?{path:r}:{}}};var _y=(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(Dy()):oe))};var Ky=require("readline/promises");var Qy=()=>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."}}),RE=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},GE=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:r}=Promise.withResolvers(),o="",s=()=>{process.stdin.off("data",d),process.stdin.off("end",g),process.stdin.off("error",l),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{s(),process.stdout.write(`
|
|
397
397
|
`)},g=()=>{a(),r(Qy())},l=(I)=>{a(),r(I)},d=(I)=>{for(let C of I){if(C==="\r"||C===`
|
|
398
398
|
`){a(),n(o);return}if(C==="\x03"||C==="\x04"){a(),r(C==="\x03"?new F("Canceled.",{hint:{disabled:!0}}):Qy());return}if(C==="\x7F"||C==="\b"){if(o.length>0)o=o.slice(0,-1),process.stdout.write("\b \b");continue}o+=C,process.stdout.write("*")}};process.stdin.on("data",d),process.stdin.once("end",g),process.stdin.once("error",l);try{return await i}finally{s()}},wE=async(e,t={})=>{if(t.mask===!0)return GE(e);let i=Ky.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await i.question(e)}finally{i.close()}},FE=(e,t)=>ha({message:e,choices:t}),fc=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:RE,style:Rh(process.env,process.stdout.isTTY),...process.stdin.isTTY?{prompt:wE,choose:FE,select:vW}:{}});function HE(e){let t=new Oi("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(oe,"-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",`
|
|
399
399
|
${bh}`).configureOutput({writeOut:(s)=>e.io.stdout(s.replace(/\n$/u,"")),writeErr:(s)=>e.io.stderr(s.replace(/\n$/u,""))}).exitOverride();let r=()=>t.opts(),o={context:e,exitCode:i,globals:r};return t.hook("postAction",async(s,a)=>{if(n)return;let g=[];for(let I=a;I!==null;I=I.parent)g.push(I.name());if(g.includes("init")||g.includes("help")||g.includes("report")||g.includes("url")||g.includes("version")||g.includes("config"))return;let l=await Be(r(),e.io),d=await by(l).catch(()=>{return});if(d===void 0)return;n=!0,e.io.stderr(d)}),_y(t,o),zh(t,o),Oh(t,o),zW(t,o),Bf(t,o),fh(t,o),fy(t,o),QW(t,o),Yf(t,o),Oy(t,o),yf(t,o),OW(t,o),Wy(t,o),_W(t,o),dy(t,o),{program:t,exitCode:i}}var vE=(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 r=e.options.find((o)=>o.short===n||o.long===n);if(r!==void 0&&(r.required||r.optional)&&!n.includes("="))i+=1}return},kE=(e,t)=>{let i=vE(e,t);if(i===void 0||i==="help")return;return e.commands.some((r)=>r.name()===i||r.aliases().includes(i))?void 0:i},PE=async(e,t,i,n)=>{let r=kE(e,i);if(r!==void 0)return n.stderr(`error: unknown command '${r}'
|
package/dist/cli/toloka.js.jsc
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
43342cdc2c3101cf1efc53b6575ab28ee511d26b5f7cf4d9c727a8a2e1db651f toloka.js.jsc
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
4988a5132e865cb74b7ee8622b1f0ccc57a19bd1f9bc1429c0b21d810582b7ff toloka.js
|
package/docs/cli.md
CHANGED
|
@@ -377,7 +377,7 @@ toloka training logs <training-run-id>
|
|
|
377
377
|
toloka training metrics <training-run-id> [--key <metric>] [--resolution <n>] [--json]
|
|
378
378
|
```
|
|
379
379
|
|
|
380
|
-
Hyperparameters are optional flags on `training create` and `training update`: `--epochs 1..5` (default 3), `--learning-rate` (SFT 0.00001–0.001, default 0.00015; gisting 0.001–0.3, default 0.03), `--batch-size 8|16|32|64` (default 8; sequences per optimizer step across all GPUs) and `--max-sequence-length 64..16384` (default 12288 for SFT, 3072 for gisting) apply to both methods; `--lora-rank 8|16|32` (default 16) is SFT-only and `--gist-tokens` (default
|
|
380
|
+
Hyperparameters are optional flags on `training create` and `training update`: `--epochs 1..5` (default 3), `--learning-rate` (SFT 0.00001–0.001, default 0.00015; gisting 0.001–0.3, default 0.03), `--batch-size 8|16|32|64` (default 8; sequences per optimizer step across all GPUs) and `--max-sequence-length 64..16384` (default 12288 for SFT, 3072 for gisting) apply to both methods; `--lora-rank 8|16|32` (default 16) is SFT-only and `--gist-tokens` (default `1/8`) is gisting-only — passing one to the other method fails before any request. `--gist-tokens` takes an absolute count `8|32|64` or a fraction of the prompt being compressed (`1/4`, `1/8`, `1/16`, `1/32`), which the run resolves to `ceil(prompt tokens / N)` clamped to 8..256. `--regime` and `--eval-steps` no longer exist. `training update` has no `--method` flag: the method stays as created, and every flag you omit keeps its current value. `training cost` is blocked when the longest example exceeds `--max-sequence-length` or when the training selection leaves fewer rows than `--batch-size` after the 10% holdout. `training get` prints the resolved recipe, so omitted flags are visible as their defaults.
|
|
381
381
|
|
|
382
382
|
## dataset
|
|
383
383
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@toloka-platform/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
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": "3b77aaf48605ba6980443e341f697877a08d6173"
|
|
81
81
|
}
|
|
82
82
|
}
|
package/skills/catalog.json
CHANGED
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
"testing",
|
|
12
12
|
"checks"
|
|
13
13
|
],
|
|
14
|
-
"version": "0.
|
|
15
|
-
"digest": "
|
|
14
|
+
"version": "0.8.0",
|
|
15
|
+
"digest": "346ab5d8cbd8e3ff2e0797e1c6cc02b97d621c4fddcbc130bd7a11e47d090cef",
|
|
16
16
|
"files": [
|
|
17
17
|
"SKILL.md",
|
|
18
18
|
"references/node-semantics.md",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"bug",
|
|
30
30
|
"report"
|
|
31
31
|
],
|
|
32
|
-
"version": "0.
|
|
32
|
+
"version": "0.8.0",
|
|
33
33
|
"digest": "70f0bd2c80b32f87896aeb27c363b8a2d37f40e22424f57fe1aad142e125ad67",
|
|
34
34
|
"files": [
|
|
35
35
|
"SKILL.md",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"getting-started",
|
|
47
47
|
"agent"
|
|
48
48
|
],
|
|
49
|
-
"version": "0.
|
|
49
|
+
"version": "0.8.0",
|
|
50
50
|
"digest": "ccf148c682de4e452bb031db95d3933257899006b1766f0fdbc3d15265a63bb9",
|
|
51
51
|
"files": [
|
|
52
52
|
"SKILL.md"
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"sft",
|
|
64
64
|
"models"
|
|
65
65
|
],
|
|
66
|
-
"version": "0.
|
|
66
|
+
"version": "0.8.0",
|
|
67
67
|
"digest": "279c69977eef170dada20b664ee0c30858681e84a2cabb2fdff18b8bb1bdc055",
|
|
68
68
|
"files": [
|
|
69
69
|
"SKILL.md"
|
|
@@ -80,8 +80,8 @@
|
|
|
80
80
|
"prompt",
|
|
81
81
|
"models"
|
|
82
82
|
],
|
|
83
|
-
"version": "0.
|
|
84
|
-
"digest": "
|
|
83
|
+
"version": "0.8.0",
|
|
84
|
+
"digest": "b9f314eb6b39754bc8d2ae79aca3dc680fced5f14948c975d1e084a83c2e0a8c",
|
|
85
85
|
"files": [
|
|
86
86
|
"SKILL.md"
|
|
87
87
|
]
|
|
@@ -201,7 +201,7 @@ The global Base Model Catalog is read-only and uses `toloka base-model`. `base-m
|
|
|
201
201
|
|
|
202
202
|
`toloka training create` requires one source (`--base-model` or `--model-version`) and a training Dataset. A `--model-version` source must be a LoRA adapter Model Version (one produced by fine-tuning) and works for both methods — SFT continues the adapter, gisting merges it and trains gist tokens over it; a full-weights version is rejected with "Training from a Model Version requires a LoRA adapter source". The first Training Run creates a new output Model named after the Training; a source Model Version is only the training parent, never the output binding.
|
|
203
203
|
|
|
204
|
-
Hyperparameters are optional flags on `training create` and `training update`: `--epochs 1..5` (default 3), `--learning-rate` (SFT 0.00001–0.001, default 0.00015; gisting 0.001–0.3, default 0.03), `--batch-size 8|16|32|64` (default 8; sequences per optimizer step across all GPUs) and `--max-sequence-length 64..16384` (default 12288 for SFT, 3072 for gisting) apply to both methods; `--lora-rank 8|16|32` (default 16) is SFT-only and `--gist-tokens` (default
|
|
204
|
+
Hyperparameters are optional flags on `training create` and `training update`: `--epochs 1..5` (default 3), `--learning-rate` (SFT 0.00001–0.001, default 0.00015; gisting 0.001–0.3, default 0.03), `--batch-size 8|16|32|64` (default 8; sequences per optimizer step across all GPUs) and `--max-sequence-length 64..16384` (default 12288 for SFT, 3072 for gisting) apply to both methods; `--lora-rank 8|16|32` (default 16) is SFT-only and `--gist-tokens` (default `1/8`) is gisting-only — passing one to the other method fails before any request. `--gist-tokens` takes an absolute count `8|32|64` or a fraction of the prompt being compressed (`1/4`, `1/8`, `1/16`, `1/32`), which the run resolves to `ceil(prompt tokens / N)` clamped to 8..256. `--regime` and `--eval-steps` no longer exist. `training update` has no `--method` flag: the method stays as created, and every flag you omit keeps its current value. `training cost` is blocked when the longest example exceeds `--max-sequence-length` or when the training selection leaves fewer rows than `--batch-size` after the 10% holdout.
|
|
205
205
|
|
|
206
206
|
Use `training cost` to validate inputs and show the maximum charge before `training run`. A blocked estimate exits 1 and lists the issues on stderr instead of printing the estimate; fix them and recalculate. `training run` accepts that ready estimate JSON through `--estimate-file`; without it, the command calculates a fresh ready estimate itself before creating the run. `--version-name` defaults to the Training name; pass it when a Model Version with that name already exists. Use `training status`, `training logs`, `training metrics`, `training resume`, and `training cancel` with the returned Training Run ID. `training metrics` lists each metric's latest value while the run is still training; `--key` prints one metric's point history instead. `training cancel` before training starts is free; on a run that is already training it stops the GPU job, and the run is charged only for the GPU seconds used until then and produces no Model Version.
|
|
207
207
|
|
|
@@ -114,7 +114,7 @@ toloka training create "<training-name>" \
|
|
|
114
114
|
|
|
115
115
|
Without `--validation-dataset`, the platform holds out 10% of training rows for evaluation. To select disjoint rows from top-level Dataset fields, use `--train-filter <field>=<value>` and `--validation-filter <field>=<value>`.
|
|
116
116
|
|
|
117
|
-
Preserve requested hyperparameters. The current CLI uses `--gist-tokens` (default
|
|
117
|
+
Preserve requested hyperparameters. The current CLI uses `--gist-tokens` (default `1/8`), `--epochs 1..5` (default 3), `--learning-rate` within 0.001–0.3 (default 0.03), `--batch-size 8|16|32|64` (default 8), and `--max-sequence-length 64..16384` (default 3072), rather than `regime`. Use defaults when suitable. `--gist-tokens` takes an absolute count `8|32|64` or a fraction of the prompt being compressed — `1/4`, `1/8`, `1/16`, `1/32`. An absolute count fixes the soft-prompt size: 8 favors compression for simple prompts, while 64 may help when 32 loses holdout accuracy. A fraction fixes the compression ratio instead — the run resolves it to `ceil(prompt tokens / N)` and clamps it to 8..256 — so the default `1/8` suits a prompt whose length changes between drafts; go to `1/16` or `1/32` for harder compression when holdout accuracy holds. `training get` reports the fraction you set, not the count it resolved to. Choose sequence length from actual examples within the supported limit. `--lora-rank` is rejected for gisting. `training update <name-or-id>` takes the same flags except `--method`; omitted flags retain current values.
|
|
118
118
|
|
|
119
119
|
Verify the saved method, exact source, prompt file, selections, filters, and configuration with `toloka training get <training-id> --json`.
|
|
120
120
|
|
|
@@ -66,7 +66,7 @@ export const registerTrainingCommands = (program: Command, host: CommandHost): v
|
|
|
66
66
|
.option("--lora-rank <rank>", "SFT LoRA adapter rank: 8, 16, or 32 (default 16)", trainingLoraRank)
|
|
67
67
|
.option(
|
|
68
68
|
"--gist-tokens <count>",
|
|
69
|
-
'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default
|
|
69
|
+
'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default "1/8")',
|
|
70
70
|
trainingGistTokens,
|
|
71
71
|
)
|
|
72
72
|
.option("--epochs <count>", "training epochs, 1 through 5 (default 3)", trainingEpochs)
|
|
@@ -117,7 +117,7 @@ export const registerTrainingCommands = (program: Command, host: CommandHost): v
|
|
|
117
117
|
.option("--lora-rank <rank>", "SFT LoRA adapter rank: 8, 16, or 32 (default 16)", trainingLoraRank)
|
|
118
118
|
.option(
|
|
119
119
|
"--gist-tokens <count>",
|
|
120
|
-
'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default
|
|
120
|
+
'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default "1/8")',
|
|
121
121
|
trainingGistTokens,
|
|
122
122
|
)
|
|
123
123
|
.option("--epochs <count>", "training epochs, 1 through 5 (default 3)", trainingEpochs)
|
|
@@ -203,7 +203,6 @@
|
|
|
203
203
|
"type": "object",
|
|
204
204
|
"properties": {
|
|
205
205
|
"fieldValues": {
|
|
206
|
-
"default": [],
|
|
207
206
|
"type": "array",
|
|
208
207
|
"items": {
|
|
209
208
|
"type": "object",
|
|
@@ -298,7 +297,6 @@
|
|
|
298
297
|
}
|
|
299
298
|
},
|
|
300
299
|
"fieldSources": {
|
|
301
|
-
"default": [],
|
|
302
300
|
"type": "array",
|
|
303
301
|
"items": {
|
|
304
302
|
"type": "object",
|
|
@@ -360,7 +358,6 @@
|
|
|
360
358
|
}
|
|
361
359
|
},
|
|
362
360
|
"missingRevisionFields": {
|
|
363
|
-
"default": [],
|
|
364
361
|
"type": "array",
|
|
365
362
|
"items": {
|
|
366
363
|
"type": "string",
|
|
@@ -2164,12 +2161,6 @@
|
|
|
2164
2161
|
]
|
|
2165
2162
|
},
|
|
2166
2163
|
"exam": {
|
|
2167
|
-
"default": {
|
|
2168
|
-
"enabled": false,
|
|
2169
|
-
"gradedEntities": [],
|
|
2170
|
-
"tasksPerExpert": 1,
|
|
2171
|
-
"passThreshold": 1
|
|
2172
|
-
},
|
|
2173
2164
|
"type": "object",
|
|
2174
2165
|
"properties": {
|
|
2175
2166
|
"enabled": {
|
|
@@ -2244,7 +2235,6 @@
|
|
|
2244
2235
|
"additionalProperties": false
|
|
2245
2236
|
},
|
|
2246
2237
|
"reuseAudienceWithNodeId": {
|
|
2247
|
-
"default": null,
|
|
2248
2238
|
"anyOf": [
|
|
2249
2239
|
{
|
|
2250
2240
|
"type": "object",
|
|
@@ -3997,12 +3987,6 @@
|
|
|
3997
3987
|
]
|
|
3998
3988
|
},
|
|
3999
3989
|
"exam": {
|
|
4000
|
-
"default": {
|
|
4001
|
-
"enabled": false,
|
|
4002
|
-
"gradedEntities": [],
|
|
4003
|
-
"tasksPerExpert": 1,
|
|
4004
|
-
"passThreshold": 1
|
|
4005
|
-
},
|
|
4006
3990
|
"type": "object",
|
|
4007
3991
|
"properties": {
|
|
4008
3992
|
"enabled": {
|
|
@@ -4077,7 +4061,6 @@
|
|
|
4077
4061
|
"additionalProperties": false
|
|
4078
4062
|
},
|
|
4079
4063
|
"reuseAudienceWithNodeId": {
|
|
4080
|
-
"default": null,
|
|
4081
4064
|
"anyOf": [
|
|
4082
4065
|
{
|
|
4083
4066
|
"type": "object",
|