@alva-ai/toolkit 0.34.0 → 0.35.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.
@@ -1,4 +1,4 @@
1
- "use strict";var AlvaToolkit=(()=>{var Ie=Object.defineProperty;var Yn=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var Kn=Object.prototype.hasOwnProperty;var s=(t,e)=>Ie(t,"name",{value:e,configurable:!0});var Xn=(t,e)=>{for(var n in e)Ie(t,n,{get:e[n],enumerable:!0})},zn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wn(e))!Kn.call(t,o)&&o!==n&&Ie(t,o,{get:()=>e[o],enumerable:!(i=Yn(e,o))||i.enumerable});return t};var Jn=t=>zn(Ie({},"__esModule",{value:!0}),t);var mr={};Xn(mr,{AlertsResource:()=>te,AlvaClient:()=>mt,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>Re,AutomationResource:()=>ee,CliUsageError:()=>qe,CompanyNewsResource:()=>ae,ForYouResource:()=>Z,MarketsResource:()=>ne,PBSV_UPDATE_MESSAGE:()=>Gt,SUBSCRIBE_MANAGE_MESSAGE:()=>Vt,SUBSCRIBE_PROPOSE_MESSAGE:()=>Bt,SUBSCRIBE_RESULT_MESSAGE:()=>Qt,SchedulesResource:()=>ie,StewardResource:()=>se,ThesesResource:()=>oe,TradingPairsResource:()=>re,UDF_AUTH_REQUIRED_MESSAGE:()=>jt,UDF_CONSENT_REQUEST_MESSAGE:()=>Mt,UDF_CONSENT_RESPONSE_MESSAGE:()=>$t,UdfAuthRequiredError:()=>W,UdfConsentDeniedError:()=>pe,UdfConsentRequiredError:()=>de,UdfConsentTimeoutError:()=>me,UdfError:()=>T,UdfExecutionError:()=>be,UdfFunctionDisabledError:()=>ye,UdfFunctionNotFoundError:()=>fe,UdfInsufficientCredits:()=>he,UdfPidMismatchError:()=>$,UdfRateLimitedError:()=>ge,UdfTokenExpiredError:()=>ce,UdfTokenInvalidError:()=>le,UdfTransportError:()=>K,VERSION:()=>pr,XResource:()=>X,getViewerToken:()=>_e,installPlaybookRuntime:()=>Pt,mapUdfErrorResponse:()=>bt,playbookIdFromToken:()=>gt,subscribe:()=>zt,udf:()=>Jt});var T=class extends Error{static{s(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:i={},status:o}){super(e),this.name=new.target.name,this.code=n,this.metadata=i,this.status=o}},W=class extends T{static{s(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},ce=class extends T{static{s(this,"UdfTokenExpiredError")}},le=class extends T{static{s(this,"UdfTokenInvalidError")}},$=class extends T{static{s(this,"UdfPidMismatchError")}},de=class extends T{static{s(this,"UdfConsentRequiredError")}},pe=class extends T{static{s(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},me=class extends T{static{s(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},he=class extends T{static{s(this,"UdfInsufficientCredits")}},fe=class extends T{static{s(this,"UdfFunctionNotFoundError")}},ye=class extends T{static{s(this,"UdfFunctionDisabledError")}},ge=class extends T{static{s(this,"UdfRateLimitedError")}},be=class extends T{static{s(this,"UdfExecutionError")}},K=class extends T{static{s(this,"UdfTransportError")}},Gt="alva:pbsv:update",Mt="alva:udf:consent-request",$t="alva:udf:consent-response",jt="alva:udf:auth-required",Bt="alva:subscribe:propose",Qt="alva:subscribe:result",Vt="alva:subscribe:manage",Ht="https://api-llm.prd.alva.ai",Yt=300*1e3,ue=null,x=null,yt=Ht,D=null,A=null,Ot=!1,Ce=new Map,xe=new Map,Zn=s(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),ei=s(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),gt=s(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(ei(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),_e=s(()=>ue,"getViewerToken"),Y=s(()=>!!_e(),"isAuthenticated"),ti=s(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),ni=s(t=>{let e=new URLSearchParams(t.location.search);ue=e.get("_pbsv"),x=e.get("parent_origin"),yt=(e.get("api_origin")||Ht).replace(/\/$/,""),D=gt(ue),ue&&ti(t)},"parseBootParams"),Wt=s(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),ii=s(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),si=s(t=>{let e=t;return{...e,result:ii(e.result)}},"normalizeInvokeResponse"),Kt=s(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),bt=s((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,o=Kt(t),r={code:n,metadata:o,status:e};switch(n){case"PBSV_EXPIRED":return new ce(i,r);case"PBSV_INVALID":case"UNAUTHENTICATED":return new le(i,r);case"PBSV_PID_MISMATCH":return new $(i,r);case"CONSENT_REQUIRED":return new de(i,r);case"INSUFFICIENT_CREDITS":return new he(i,r);case"FUNCTION_NOT_FOUND":return new fe(i,r);case"FUNCTION_DISABLED":return new ye(i,r);case"RESOURCE_EXHAUSTED":return new ge(i,r);case"EXECUTION_FAILED":return new be(i,r);default:return new K(i,r)}},"mapUdfErrorResponse"),ri=s(t=>{if(!A||!x||t.origin!==x||t.source!==A.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===Gt){typeof e.token=="string"&&e.token.length>0&&(ue=e.token,D=gt(e.token));return}if(e.type===Qt){if(typeof e.request_id!="string")return;let i=xe.get(e.request_id);if(!i)return;clearTimeout(i.timer),xe.delete(e.request_id),i.resolve(Zn(e.status));return}if(e.type!==$t||typeof e.request_id!="string")return;let n=Ce.get(e.request_id);n&&(clearTimeout(n.timer),Ce.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Xt=s(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),oi=s(()=>{if(!D)return null;let t=Number(D);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),ai=s(async(t,e)=>{if(!A||!x)return"denied";let n=x,i=Xt();return new Promise(o=>{let r=setTimeout(()=>{Ce.delete(i),o("timeout")},Yt);Ce.set(i,{resolve:o,timer:r}),A?.parent.postMessage({type:Mt,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),ui=s(async t=>{if(!A||!x)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let i=x,o=Xt();return new Promise(r=>{let a=setTimeout(()=>{xe.delete(o),r("timeout")},Yt);xe.set(o,{resolve:r,timer:a}),A?.parent.postMessage({type:Bt,request_id:o,playbook_id:D,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),ci=s(()=>{!A||!x||A.parent.postMessage({type:Vt,playbook_id:D},x)},"manageSubscriptions"),zt={propose:ui,manage:ci},li=s(t=>{!A||!x||A.parent.postMessage({type:jt,function_name:t},x)},"requestAuthentication"),_t=s(async(t,e,n=!1)=>{let i=_e();if(!i)throw new W;if(!D)throw new $("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let o=oi();if(!o)throw new $("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let r;try{r=await fetch(`${yt}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:o,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new K("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Wt(r);if(r.ok)return si(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let u=Kt(a),c=typeof u.playbook_id=="string"?u.playbook_id:D,d=typeof u.min_allowance_suggested=="number"?u.min_allowance_suggested:1,y=await ai(c,d);if(y==="granted")return _t(t,e,!0);throw y==="timeout"?new me:new pe}throw bt(a,r.status)},"call"),di=s(async()=>{let t=_e();if(!t)throw new W;if(!D)throw new $("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${yt}/api/v1/service/functions`);e.searchParams.set("playbook_id",D);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await Wt(n);if(!n.ok)throw bt(i,n.status);let o=i.functions;return Array.isArray(o)?o:[]},"list"),ft=s((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),pi=s(t=>{if(typeof t!="string")return t;let n=A?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),mi=s((t,e)=>{if(!A)throw new Error("Playbook runtime is not installed.");let n=pi(t),i=A.document.createElement("button"),o=e.label||e.functionName,r=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=Y()?o:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),Y()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!Y()){li(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=r,ft(i,"alva:udf-button:loading",{functionName:e.functionName});try{let u=await _t(e.functionName,e.params??{});ft(i,"alva:udf-button:result",{functionName:e.functionName,result:u})}catch(u){ft(i,"alva:udf-button:error",{functionName:e.functionName,error:u})}finally{i.disabled=!1,i.textContent=Y()?o:a,Y()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),Jt={call:_t,list:di,getViewerToken:_e,isAuthenticated:Y,renderButton:mi,UdfError:T,UdfAuthRequiredError:W,UdfTokenExpiredError:ce,UdfTokenInvalidError:le,UdfPidMismatchError:$,UdfConsentRequiredError:de,UdfConsentDeniedError:pe,UdfConsentTimeoutError:me,UdfInsufficientCredits:he,UdfFunctionNotFoundError:fe,UdfFunctionDisabledError:ye,UdfRateLimitedError:ge,UdfExecutionError:be,UdfTransportError:K},Pt=s(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||Ot)return;A=e,Ot=!0,ni(e),e.addEventListener("message",ri);let n=e,i=n.alva||{};n.alva={...i,udf:Jt,subscribe:zt}},"installPlaybookRuntime");var l=class extends Error{static{s(this,"AlvaError")}code;status;details;constructor(e,n,i,o){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=o}},qe=class extends Error{static{s(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function Zt(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}s(Zt,"isArrayBuffer");var en=1;function hi(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,o=0,r=0;if(n>=194&&n<=223)i=1,o=128,r=n&31;else if(n>=224&&n<=239)i=2,o=2048,r=n&15;else if(n>=240&&n<=244)i=3,o=65536,r=n&7;else return!1;if(e+i>=t.length)return!1;for(let a=1;a<=i;a+=1){let u=t[e+a];if((u&192)!==128)return!1;r=r<<6|u&63}if(r<o||r>1114111||r>=55296&&r<=57343)return!1;e+=i+1}return!0}s(hi,"isValidUtf8");var Ne=class{constructor(e){this.client=e}client;static{s(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!Zt(n)||!hi(new Uint8Array(n)))return n;let i=new TextDecoder("utf-8").decode(n);try{return JSON.parse(i)}catch{return i}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:en}:{}}})}async rawWrite(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{query:{path:e.path,mkdir_parents:e.mkdir_parents,...e.append?{flags:en}:{}},rawBody:e.body})}async stat(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/stat",{query:{path:e.path}})}async readdir(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readdir",{query:{path:e.path,recursive:e.recursive}})}async mkdir(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/mkdir",{body:{path:e.path}})}async remove(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/fs/remove",{query:{path:e.path,recursive:e.recursive}})}async rename(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/rename",{body:{old_path:e.old_path,new_path:e.new_path}})}async copy(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/copy",{body:{src_path:e.src_path,dst_path:e.dst_path}})}async symlink(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/symlink",{body:{target_path:e.target_path,link_path:e.link_path}})}async readlink(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readlink",{query:{path:e.path}})}async chmod(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/chmod",{body:{path:e.path,mode:e.mode}})}async grant(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/grant",{body:{path:e.path,subject:e.subject,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/revoke",{body:{path:e.path,subject:e.subject,permission:e.permission}})}};var tn="9007199254740991";function nn(t,e,n,i){let o=t.length+e,r=n.length+i;if(o!==r)return o>r;for(let a=0;a<o;a++){let u=a<t.length?t[a]:"0",c=a<n.length?n[a]:"0";if(u!==c)return u>c}return!1}s(nn,"scaledIntegerGreater");function fi(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,i=e.groups.fraction??"",o=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(o))return!0;let r=(n+i).replace(/^0+/,"")||"0";if(r==="0")return!1;let a=o-i.length;return a>=0?nn(r,a,tn,0):nn(r,0,tn,-a)}s(fi,"numberOutsideSafeRange");function yi(t){let e=0;for(;e<t.length;){if(t[e]==='"'){for(e++;e<t.length;)if(t[e]==="\\")e+=2;else if(t[e++]==='"')break;continue}if(t[e]==="-"||/\d/.test(t[e]??"")){let n=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(n){if(fi(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}s(yi,"validateJSONNumberTokens");function wt(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((i,o)=>wt(i,`${e}[${o}]`,n));else{let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[o,r]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(r.enumerable){if(!("value"in r))throw new TypeError(`${e} must not contain accessors`);wt(r.value,`${e}.${o}`,n)}}n.delete(t)}}s(wt,"assertPlainJSONData");function Pe(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");wt(t,"args",new Set);let e=JSON.stringify(t);return sn(e),e}s(Pe,"serializeStructuredArgs");function sn(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");yi(t)}s(sn,"validateSerializedArgs");function we(t,e,n){let i=Object.entries(t).filter(([o,r])=>r!==void 0&&(n===void 0||o!==e));return n!==void 0&&(sn(n),i.push([e,n])),`{${i.map(([o,r])=>{let a=o===e&&n!==void 0?n:JSON.stringify(r);return`${JSON.stringify(o)}:${a}`}).join(",")}}`}s(we,"objectWithRawJSONField");var De=class{constructor(e){this.client=e}client;static{s(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,Pe(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let i={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:i}:{jsonBody:we(i,"args",n)},timeoutMs:e.timeout_ms})}};var Ue=class{constructor(e){this.client=e}client;static{s(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,Pe(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let i={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:i}:{jsonBody:we(i,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,Pe(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:i,...o}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...n===void 0?{body:o}:{jsonBody:we(o,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var Le=class{constructor(e){this.client=e}client;static{s(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var Fe=class{constructor(e){this.client=e}client;static{s(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url,confirm_bundled_feed_exposure:e.confirm_bundled_feed_exposure}})}};var Ge=class{constructor(e){this.client=e}client;static{s(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=Oe(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=Oe(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=Oe(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=Oe(e.id);if(e.visibility!=="public"&&e.visibility!=="private")throw new Error("visibility must be 'public' or 'private'");return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/visibility`,{body:{visibility:e.visibility}})}};function Oe(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}s(Oe,"requireFeedID");var rn={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504};function I(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(I,"record");function gi(t){if(!I(t))throw new Error("X read parameters must be an object");let e=t.first??20;if(t.first===null||typeof e!="number"||!Number.isInteger(e)||e<5||e>100)throw new Error("first must be an integer between 5 and 100");if(t.after!==void 0&&(typeof t.after!="string"||!t.after.trim()||t.after.length>4096))throw new Error("after must be a non-empty X cursor of at most 4096 characters")}s(gi,"validateXReadParams");function U(t){throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${t} response`,502)}s(U,"invalidResponse");function on(t,e){if(!I(t))return U(e);if(t.errors!==void 0){if(!Array.isArray(t.errors))return U(e);if(t.errors.length>0){let n=t.errors.flatMap(r=>I(r)&&typeof r.message=="string"?[r.message]:[]),i=t.errors.map(r=>I(r)&&I(r.extensions)?r.extensions.code:void 0),o=typeof i[0]=="string"&&Object.hasOwn(rn,i[0])&&i.every(r=>r===i[0])?i[0]:"GRAPHQL_ERROR";throw new l(o,n.join("; ")||"X read failed",rn[o]??502,{errors:t.errors})}}return!I(t.data)||!I(t.data.viewer)?U(e):t.data.viewer[e]}s(on,"viewerField");function bi(t,e,n){if(!I(t)||!Array.isArray(t.edges)||!I(t.pageInfo))return U(e);let i=t.pageInfo;if(typeof i.startCursor!="string"||typeof i.endCursor!="string"||typeof i.hasNextPage!="boolean"||typeof i.hasPreviousPage!="boolean"||i.hasNextPage&&!i.endCursor)return U(e);for(let a of t.edges){if(!I(a)||typeof a.cursor!="string"||!a.cursor||!I(a.node))return U(e);let u=a.node;if(n.some(c=>typeof u[c]!="string")||!u.id)return U(e)}let o=t.edges[0],r=t.edges[t.edges.length-1];return i.startCursor!==(o?.cursor??"")||r&&i.endCursor!==r.cursor?U(e):{edges:t.edges,pageInfo:i,retrievedAt:new Date().toISOString()}}s(bi,"readPage");var X=class{constructor(e){this.client=e}client;static{s(this,"XResource")}async status(){this.client._requireAuth();let e=await this.client._request("POST","/query",{body:{query:"query ToolkitXStatus { viewer { xConnection { connected canReadFollowing canReadPosts } } }"}}),n=on(e,"xConnection");return!I(n)||["connected","canReadFollowing","canReadPosts"].some(i=>typeof n[i]!="boolean")?U("xConnection"):n}async following(e={}){return this.read("xFollowing","id username name",e)}async posts(e={}){return this.read("xPosts","id text authorId createdAt",e)}async read(e,n,i){gi(i),this.client._requireAuth();let o=await this.client._request("POST","/query",{body:{query:`query ToolkitXRead($first: Int, $after: String) { viewer { ${e}(first: $first, after: $after) { edges { cursor node { ${n} } } pageInfo { startCursor endCursor hasNextPage hasPreviousPage } } } }`,variables:{first:i.first??20,after:i.after}}});return bi(on(o,e),e,n.split(" "))}};function m(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(m,"record");function k(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}s(k,"isPositiveInt64");var z=`
1
+ "use strict";var AlvaToolkit=(()=>{var Ne=Object.defineProperty;var yi=Object.getOwnPropertyDescriptor;var bi=Object.getOwnPropertyNames;var wi=Object.prototype.hasOwnProperty;var s=(t,e)=>Ne(t,"name",{value:e,configurable:!0});var Pi=(t,e)=>{for(var n in e)Ne(t,n,{get:e[n],enumerable:!0})},_i=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of bi(e))!wi.call(t,o)&&o!==n&&Ne(t,o,{get:()=>e[o],enumerable:!(i=yi(e,o))||i.enumerable});return t};var Ti=t=>_i(Ne({},"__esModule",{value:!0}),t);var to={};Pi(to,{AlertsResource:()=>oe,AlvaClient:()=>bt,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>ve,AutomationResource:()=>re,CliUsageError:()=>Fe,CompanyNewsResource:()=>pe,FollowsResource:()=>se,ForYouResource:()=>ie,MarketsResource:()=>ae,PBSV_UPDATE_MESSAGE:()=>Kt,SUBSCRIBE_MANAGE_MESSAGE:()=>tn,SUBSCRIBE_PROPOSE_MESSAGE:()=>Zt,SUBSCRIBE_RESULT_MESSAGE:()=>en,SchedulesResource:()=>ue,StewardResource:()=>ce,ThesesResource:()=>de,TradingPairsResource:()=>le,UDF_AUTH_REQUIRED_MESSAGE:()=>Jt,UDF_CONSENT_REQUEST_MESSAGE:()=>Xt,UDF_CONSENT_RESPONSE_MESSAGE:()=>zt,UdfAuthRequiredError:()=>J,UdfConsentDeniedError:()=>ye,UdfConsentRequiredError:()=>ge,UdfConsentTimeoutError:()=>be,UdfError:()=>A,UdfExecutionError:()=>Re,UdfFunctionDisabledError:()=>_e,UdfFunctionNotFoundError:()=>Pe,UdfInsufficientCredits:()=>we,UdfPidMismatchError:()=>W,UdfRateLimitedError:()=>Te,UdfTokenExpiredError:()=>he,UdfTokenInvalidError:()=>fe,UdfTransportError:()=>Z,VERSION:()=>eo,XResource:()=>ee,getViewerToken:()=>Se,installPlaybookRuntime:()=>kt,mapUdfErrorResponse:()=>Rt,playbookIdFromToken:()=>Tt,subscribe:()=>un,udf:()=>cn});var A=class extends Error{static{s(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:i={},status:o}){super(e),this.name=new.target.name,this.code=n,this.metadata=i,this.status=o}},J=class extends A{static{s(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},he=class extends A{static{s(this,"UdfTokenExpiredError")}},fe=class extends A{static{s(this,"UdfTokenInvalidError")}},W=class extends A{static{s(this,"UdfPidMismatchError")}},ge=class extends A{static{s(this,"UdfConsentRequiredError")}},ye=class extends A{static{s(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},be=class extends A{static{s(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},we=class extends A{static{s(this,"UdfInsufficientCredits")}},Pe=class extends A{static{s(this,"UdfFunctionNotFoundError")}},_e=class extends A{static{s(this,"UdfFunctionDisabledError")}},Te=class extends A{static{s(this,"UdfRateLimitedError")}},Re=class extends A{static{s(this,"UdfExecutionError")}},Z=class extends A{static{s(this,"UdfTransportError")}},Kt="alva:pbsv:update",Xt="alva:udf:consent-request",zt="alva:udf:consent-response",Jt="alva:udf:auth-required",Zt="alva:subscribe:propose",en="alva:subscribe:result",tn="alva:subscribe:manage",nn="https://api-llm.prd.alva.ai",rn=300*1e3,me=null,U=null,_t=nn,O=null,N=null,Yt=!1,De=new Map,Ue=new Map,Ri=s(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Si=s(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),Tt=s(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Si(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),Se=s(()=>me,"getViewerToken"),z=s(()=>!!Se(),"isAuthenticated"),ki=s(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),Ei=s(t=>{let e=new URLSearchParams(t.location.search);me=e.get("_pbsv"),U=e.get("parent_origin"),_t=(e.get("api_origin")||nn).replace(/\/$/,""),O=Tt(me),me&&ki(t)},"parseBootParams"),sn=s(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Ai=s(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),vi=s(t=>{let e=t;return{...e,result:Ai(e.result)}},"normalizeInvokeResponse"),on=s(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),Rt=s((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,o=on(t),r={code:n,metadata:o,status:e};switch(n){case"PBSV_EXPIRED":return new he(i,r);case"PBSV_INVALID":case"UNAUTHENTICATED":return new fe(i,r);case"PBSV_PID_MISMATCH":return new W(i,r);case"CONSENT_REQUIRED":return new ge(i,r);case"INSUFFICIENT_CREDITS":return new we(i,r);case"FUNCTION_NOT_FOUND":return new Pe(i,r);case"FUNCTION_DISABLED":return new _e(i,r);case"RESOURCE_EXHAUSTED":return new Te(i,r);case"EXECUTION_FAILED":return new Re(i,r);default:return new Z(i,r)}},"mapUdfErrorResponse"),Ii=s(t=>{if(!N||!U||t.origin!==U||t.source!==N.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===Kt){typeof e.token=="string"&&e.token.length>0&&(me=e.token,O=Tt(e.token));return}if(e.type===en){if(typeof e.request_id!="string")return;let i=Ue.get(e.request_id);if(!i)return;clearTimeout(i.timer),Ue.delete(e.request_id),i.resolve(Ri(e.status));return}if(e.type!==zt||typeof e.request_id!="string")return;let n=De.get(e.request_id);n&&(clearTimeout(n.timer),De.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),an=s(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Ci=s(()=>{if(!O)return null;let t=Number(O);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),xi=s(async(t,e)=>{if(!N||!U)return"denied";let n=U,i=an();return new Promise(o=>{let r=setTimeout(()=>{De.delete(i),o("timeout")},rn);De.set(i,{resolve:o,timer:r}),N?.parent.postMessage({type:Xt,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),qi=s(async t=>{if(!N||!U)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let i=U,o=an();return new Promise(r=>{let a=setTimeout(()=>{Ue.delete(o),r("timeout")},rn);Ue.set(o,{resolve:r,timer:a}),N?.parent.postMessage({type:Zt,request_id:o,playbook_id:O,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Ni=s(()=>{!N||!U||N.parent.postMessage({type:tn,playbook_id:O},U)},"manageSubscriptions"),un={propose:qi,manage:Ni},Di=s(t=>{!N||!U||N.parent.postMessage({type:Jt,function_name:t},U)},"requestAuthentication"),St=s(async(t,e,n=!1)=>{let i=Se();if(!i)throw new J;if(!O)throw new W("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let o=Ci();if(!o)throw new W("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let r;try{r=await fetch(`${_t}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:o,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new Z("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await sn(r);if(r.ok)return vi(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let u=on(a),c=typeof u.playbook_id=="string"?u.playbook_id:O,d=typeof u.min_allowance_suggested=="number"?u.min_allowance_suggested:1,p=await xi(c,d);if(p==="granted")return St(t,e,!0);throw p==="timeout"?new be:new ye}throw Rt(a,r.status)},"call"),Ui=s(async()=>{let t=Se();if(!t)throw new J;if(!O)throw new W("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${_t}/api/v1/service/functions`);e.searchParams.set("playbook_id",O);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await sn(n);if(!n.ok)throw Rt(i,n.status);let o=i.functions;return Array.isArray(o)?o:[]},"list"),Pt=s((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),Fi=s(t=>{if(typeof t!="string")return t;let n=N?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),Li=s((t,e)=>{if(!N)throw new Error("Playbook runtime is not installed.");let n=Fi(t),i=N.document.createElement("button"),o=e.label||e.functionName,r=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=z()?o:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),z()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!z()){Di(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=r,Pt(i,"alva:udf-button:loading",{functionName:e.functionName});try{let u=await St(e.functionName,e.params??{});Pt(i,"alva:udf-button:result",{functionName:e.functionName,result:u})}catch(u){Pt(i,"alva:udf-button:error",{functionName:e.functionName,error:u})}finally{i.disabled=!1,i.textContent=z()?o:a,z()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),cn={call:St,list:Ui,getViewerToken:Se,isAuthenticated:z,renderButton:Li,UdfError:A,UdfAuthRequiredError:J,UdfTokenExpiredError:he,UdfTokenInvalidError:fe,UdfPidMismatchError:W,UdfConsentRequiredError:ge,UdfConsentDeniedError:ye,UdfConsentTimeoutError:be,UdfInsufficientCredits:we,UdfFunctionNotFoundError:Pe,UdfFunctionDisabledError:_e,UdfRateLimitedError:Te,UdfExecutionError:Re,UdfTransportError:Z},kt=s(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||Yt)return;N=e,Yt=!0,Ei(e),e.addEventListener("message",Ii);let n=e,i=n.alva||{};n.alva={...i,udf:cn,subscribe:un}},"installPlaybookRuntime");var l=class extends Error{static{s(this,"AlvaError")}code;status;details;constructor(e,n,i,o){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=o}},Fe=class extends Error{static{s(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function ln(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}s(ln,"isArrayBuffer");var dn=1;function Oi(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,o=0,r=0;if(n>=194&&n<=223)i=1,o=128,r=n&31;else if(n>=224&&n<=239)i=2,o=2048,r=n&15;else if(n>=240&&n<=244)i=3,o=65536,r=n&7;else return!1;if(e+i>=t.length)return!1;for(let a=1;a<=i;a+=1){let u=t[e+a];if((u&192)!==128)return!1;r=r<<6|u&63}if(r<o||r>1114111||r>=55296&&r<=57343)return!1;e+=i+1}return!0}s(Oi,"isValidUtf8");var Le=class{constructor(e){this.client=e}client;static{s(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!ln(n)||!Oi(new Uint8Array(n)))return n;let i=new TextDecoder("utf-8").decode(n);try{return JSON.parse(i)}catch{return i}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:dn}:{}}})}async rawWrite(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{query:{path:e.path,mkdir_parents:e.mkdir_parents,...e.append?{flags:dn}:{}},rawBody:e.body})}async stat(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/stat",{query:{path:e.path}})}async readdir(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readdir",{query:{path:e.path,recursive:e.recursive}})}async mkdir(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/mkdir",{body:{path:e.path}})}async remove(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/fs/remove",{query:{path:e.path,recursive:e.recursive}})}async rename(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/rename",{body:{old_path:e.old_path,new_path:e.new_path}})}async copy(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/copy",{body:{src_path:e.src_path,dst_path:e.dst_path}})}async symlink(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/symlink",{body:{target_path:e.target_path,link_path:e.link_path}})}async readlink(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readlink",{query:{path:e.path}})}async chmod(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/chmod",{body:{path:e.path,mode:e.mode}})}async grant(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/grant",{body:{path:e.path,subject:e.subject,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/revoke",{body:{path:e.path,subject:e.subject,permission:e.permission}})}};var pn="9007199254740991";function mn(t,e,n,i){let o=t.length+e,r=n.length+i;if(o!==r)return o>r;for(let a=0;a<o;a++){let u=a<t.length?t[a]:"0",c=a<n.length?n[a]:"0";if(u!==c)return u>c}return!1}s(mn,"scaledIntegerGreater");function Gi(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,i=e.groups.fraction??"",o=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(o))return!0;let r=(n+i).replace(/^0+/,"")||"0";if(r==="0")return!1;let a=o-i.length;return a>=0?mn(r,a,pn,0):mn(r,0,pn,-a)}s(Gi,"numberOutsideSafeRange");function Mi(t){let e=0;for(;e<t.length;){if(t[e]==='"'){for(e++;e<t.length;)if(t[e]==="\\")e+=2;else if(t[e++]==='"')break;continue}if(t[e]==="-"||/\d/.test(t[e]??"")){let n=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(n){if(Gi(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}s(Mi,"validateJSONNumberTokens");function Et(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((i,o)=>Et(i,`${e}[${o}]`,n));else{let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[o,r]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(r.enumerable){if(!("value"in r))throw new TypeError(`${e} must not contain accessors`);Et(r.value,`${e}.${o}`,n)}}n.delete(t)}}s(Et,"assertPlainJSONData");function ke(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");Et(t,"args",new Set);let e=JSON.stringify(t);return hn(e),e}s(ke,"serializeStructuredArgs");function hn(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Mi(t)}s(hn,"validateSerializedArgs");function Ee(t,e,n){let i=Object.entries(t).filter(([o,r])=>r!==void 0&&(n===void 0||o!==e));return n!==void 0&&(hn(n),i.push([e,n])),`{${i.map(([o,r])=>{let a=o===e&&n!==void 0?n:JSON.stringify(r);return`${JSON.stringify(o)}:${a}`}).join(",")}}`}s(Ee,"objectWithRawJSONField");var Oe=class{constructor(e){this.client=e}client;static{s(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,ke(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let i={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:i}:{jsonBody:Ee(i,"args",n)},timeoutMs:e.timeout_ms})}};var Ge=class{constructor(e){this.client=e}client;static{s(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,ke(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let i={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:i}:{jsonBody:Ee(i,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,ke(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:i,...o}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...n===void 0?{body:o}:{jsonBody:Ee(o,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var Me=class{constructor(e){this.client=e}client;static{s(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var $e=class{constructor(e){this.client=e}client;static{s(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url,confirm_bundled_feed_exposure:e.confirm_bundled_feed_exposure}})}};var Be=class{constructor(e){this.client=e}client;static{s(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=je(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=je(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=je(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=je(e.id);if(e.visibility!=="public"&&e.visibility!=="private")throw new Error("visibility must be 'public' or 'private'");return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/visibility`,{body:{visibility:e.visibility}})}};function je(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}s(je,"requireFeedID");var fn={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504};function D(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(D,"record");function $i(t){if(!D(t))throw new Error("X read parameters must be an object");let e=t.first??20;if(t.first===null||typeof e!="number"||!Number.isInteger(e)||e<5||e>100)throw new Error("first must be an integer between 5 and 100");if(t.after!==void 0&&(typeof t.after!="string"||!t.after.trim()||t.after.length>4096))throw new Error("after must be a non-empty X cursor of at most 4096 characters")}s($i,"validateXReadParams");function G(t){throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${t} response`,502)}s(G,"invalidResponse");function gn(t,e){if(!D(t))return G(e);if(t.errors!==void 0){if(!Array.isArray(t.errors))return G(e);if(t.errors.length>0){let n=t.errors.flatMap(r=>D(r)&&typeof r.message=="string"?[r.message]:[]),i=t.errors.map(r=>D(r)&&D(r.extensions)?r.extensions.code:void 0),o=typeof i[0]=="string"&&Object.hasOwn(fn,i[0])&&i.every(r=>r===i[0])?i[0]:"GRAPHQL_ERROR";throw new l(o,n.join("; ")||"X read failed",fn[o]??502,{errors:t.errors})}}return!D(t.data)||!D(t.data.viewer)?G(e):t.data.viewer[e]}s(gn,"viewerField");function ji(t,e,n){if(!D(t)||!Array.isArray(t.edges)||!D(t.pageInfo))return G(e);let i=t.pageInfo;if(typeof i.startCursor!="string"||typeof i.endCursor!="string"||typeof i.hasNextPage!="boolean"||typeof i.hasPreviousPage!="boolean"||i.hasNextPage&&!i.endCursor)return G(e);for(let a of t.edges){if(!D(a)||typeof a.cursor!="string"||!a.cursor||!D(a.node))return G(e);let u=a.node;if(n.some(c=>typeof u[c]!="string")||!u.id)return G(e)}let o=t.edges[0],r=t.edges[t.edges.length-1];return i.startCursor!==(o?.cursor??"")||r&&i.endCursor!==r.cursor?G(e):{edges:t.edges,pageInfo:i,retrievedAt:new Date().toISOString()}}s(ji,"readPage");var ee=class{constructor(e){this.client=e}client;static{s(this,"XResource")}async status(){this.client._requireAuth();let e=await this.client._request("POST","/query",{body:{query:"query ToolkitXStatus { viewer { xConnection { connected canReadFollowing canReadPosts } } }"}}),n=gn(e,"xConnection");return!D(n)||["connected","canReadFollowing","canReadPosts"].some(i=>typeof n[i]!="boolean")?G("xConnection"):n}async following(e={}){return this.read("xFollowing","id username name",e)}async posts(e={}){return this.read("xPosts","id text authorId createdAt",e)}async read(e,n,i){$i(i),this.client._requireAuth();let o=await this.client._request("POST","/query",{body:{query:`query ToolkitXRead($first: Int, $after: String) { viewer { ${e}(first: $first, after: $after) { edges { cursor node { ${n} } } pageInfo { startCursor endCursor hasNextPage hasPreviousPage } } } }`,variables:{first:i.first??20,after:i.after}}});return ji(gn(o,e),e,n.split(" "))}};function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(h,"record");function x(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}s(x,"isPositiveInt64");var te=`
2
2
  thesisId playbookId authorVersionId materialVersionId itemKey
3
3
  title body publishedAtMs changeKind visibility
4
4
  closed archived note closingNote researchPaused
@@ -19,7 +19,7 @@
19
19
  title sourceKind sourceContentId publicUrl sourceTimeMs locator
20
20
  }
21
21
  }
22
- `;function an(t){return Array.isArray(t)&&t.every(k)}s(an,"positiveInt64List");function _i(t){return Array.isArray(t)&&t.every(e=>m(e)&&k(e.entityId)&&typeof e.stance=="string"&&e.stance.trim()!=="")}s(_i,"stanceList");function Pi(t){return Array.isArray(t)&&t.every(e=>m(e)&&typeof e.id=="string"&&e.id.trim()!==""&&typeof e.ticker=="string"&&typeof e.name=="string")}s(Pi,"entityList");function wi(t){return Array.isArray(t)&&t.every(e=>m(e)&&typeof e.type=="string"&&e.type.trim()!==""&&typeof e.coverUrl=="string"&&(e.url===null||typeof e.url=="string"))}s(wi,"mediaList");function Ti(t){return Array.isArray(t)&&t.every(e=>m(e)&&(e.title===null||typeof e.title=="string")&&typeof e.sourceKind=="string"&&typeof e.sourceContentId=="string"&&typeof e.publicUrl=="string"&&Ri(e.sourceTimeMs)&&typeof e.locator=="string")}s(Ti,"sourceRefList");function Ri(t){return t===null||typeof t=="number"&&Number.isFinite(t)}s(Ri,"nullableMs");function Si(t){return m(t)&&k(t.versionId)&&k(t.materialVersionId)&&typeof t.publishedAtMs=="number"&&Number.isFinite(t.publishedAtMs)&&typeof t.changeKind=="string"&&t.changeKind.trim()!==""&&Ti(t.sourceRefs)}s(Si,"snapshot");function ki(t){return m(t)&&(t.__typename==="Person"&&typeof t.slug=="string"||t.__typename==="PublicUser"&&typeof t.username=="string")&&typeof t.id=="string"&&t.id.trim()!==""&&typeof t.displayName=="string"&&typeof t.avatarUrl=="string"&&typeof t.bio=="string"&&typeof t.followersCount=="number"&&Number.isInteger(t.followersCount)&&m(t.viewerState)&&(t.viewerState.following===null||typeof t.viewerState.following=="boolean")}s(ki,"publisher");function J(t){if(!m(t))return!1;for(let e of["thesisId","playbookId","authorVersionId","materialVersionId"])if(!k(t[e]))return!1;if(typeof t.itemKey!="string"||!t.itemKey.trim()||typeof t.title!="string"||typeof t.body!="string"||typeof t.publishedAtMs!="number"||!Number.isFinite(t.publishedAtMs)||typeof t.changeKind!="string"||!t.changeKind.trim()||typeof t.visibility!="string"||typeof t.note!="string"||typeof t.closingNote!="string")return!1;for(let e of["closed","archived","researchPaused"])if(typeof t[e]!="boolean")return!1;return!an(t.entityIds)||!an(t.categoryIds)||!_i(t.entityStances)||!Pi(t.entities)||!wi(t.medias)||!ki(t.publisher)||!Si(t.snapshotRelease)?!1:t.signalFeed===null||m(t.signalFeed)&&k(t.signalFeed.id)}s(J,"isThesisPublication");var Ei=`
22
+ `;function yn(t){return Array.isArray(t)&&t.every(x)}s(yn,"positiveInt64List");function Bi(t){return Array.isArray(t)&&t.every(e=>h(e)&&x(e.entityId)&&typeof e.stance=="string"&&e.stance.trim()!=="")}s(Bi,"stanceList");function Qi(t){return Array.isArray(t)&&t.every(e=>h(e)&&typeof e.id=="string"&&e.id.trim()!==""&&typeof e.ticker=="string"&&typeof e.name=="string")}s(Qi,"entityList");function Wi(t){return Array.isArray(t)&&t.every(e=>h(e)&&typeof e.type=="string"&&e.type.trim()!==""&&typeof e.coverUrl=="string"&&(e.url===null||typeof e.url=="string"))}s(Wi,"mediaList");function Vi(t){return Array.isArray(t)&&t.every(e=>h(e)&&(e.title===null||typeof e.title=="string")&&typeof e.sourceKind=="string"&&typeof e.sourceContentId=="string"&&typeof e.publicUrl=="string"&&Hi(e.sourceTimeMs)&&typeof e.locator=="string")}s(Vi,"sourceRefList");function Hi(t){return t===null||typeof t=="number"&&Number.isFinite(t)}s(Hi,"nullableMs");function Yi(t){return h(t)&&x(t.versionId)&&x(t.materialVersionId)&&typeof t.publishedAtMs=="number"&&Number.isFinite(t.publishedAtMs)&&typeof t.changeKind=="string"&&t.changeKind.trim()!==""&&Vi(t.sourceRefs)}s(Yi,"snapshot");function Ki(t){return h(t)&&(t.__typename==="Person"&&typeof t.slug=="string"||t.__typename==="PublicUser"&&typeof t.username=="string")&&typeof t.id=="string"&&t.id.trim()!==""&&typeof t.displayName=="string"&&typeof t.avatarUrl=="string"&&typeof t.bio=="string"&&typeof t.followersCount=="number"&&Number.isInteger(t.followersCount)&&h(t.viewerState)&&(t.viewerState.following===null||typeof t.viewerState.following=="boolean")}s(Ki,"publisher");function ne(t){if(!h(t))return!1;for(let e of["thesisId","playbookId","authorVersionId","materialVersionId"])if(!x(t[e]))return!1;if(typeof t.itemKey!="string"||!t.itemKey.trim()||typeof t.title!="string"||typeof t.body!="string"||typeof t.publishedAtMs!="number"||!Number.isFinite(t.publishedAtMs)||typeof t.changeKind!="string"||!t.changeKind.trim()||typeof t.visibility!="string"||typeof t.note!="string"||typeof t.closingNote!="string")return!1;for(let e of["closed","archived","researchPaused"])if(typeof t[e]!="boolean")return!1;return!yn(t.entityIds)||!yn(t.categoryIds)||!Bi(t.entityStances)||!Qi(t.entities)||!Wi(t.medias)||!Ki(t.publisher)||!Yi(t.snapshotRelease)?!1:t.signalFeed===null||h(t.signalFeed)&&x(t.signalFeed.id)}s(ne,"isThesisPublication");var Xi=`
23
23
  query ToolkitForYou($input: FeedEntryConnectionInput) {
24
24
  viewer {
25
25
  forYou(input: $input) {
@@ -46,7 +46,7 @@ query ToolkitForYou($input: FeedEntryConnectionInput) {
46
46
  }
47
47
  }
48
48
  }
49
- `.trim();function Ai(t){if(!m(t))throw new Error("For You parameters must be an object");let e=t.first===void 0?20:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw new Error("first must be an integer between 1 and 50");for(let n of["after","newerThan"]){let i=t[n];if(i!==void 0&&(typeof i!="string"||!i.trim()))throw new Error(`${n} must be a non-empty cursor`)}if(t.feedId!==void 0&&!k(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}s(Ai,"validateForYouListParams");function Te(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}s(Te,"invalidResponse");function vi(t){if(!m(t)||!Array.isArray(t.edges)||!m(t.pageInfo))return Te();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return Te();for(let o of t.edges){if(!m(o)||typeof o.cursor!="string"||!o.cursor.trim()||!m(o.node))return Te();let r=o.node;if(typeof r.id!="string"||!r.id.startsWith("FeedEntry:")||!k(r.id.slice(10))||!m(r.feed)||!k(r.feed.id)||!m(r.major)||typeof r.major.id!="string"||!k(r.major.feedId)||typeof r.title!="string"||typeof r.body!="string")return Te()}let n=t.edges[0],i=t.edges[t.edges.length-1];return e.startCursor!==(n?.cursor??"")||e.endCursor!==(i?.cursor??"")||t.edges.length===0&&e.hasNextPage?Te():t}s(vi,"connection");var Ii=`
49
+ `.trim();function zi(t){if(!h(t))throw new Error("For You parameters must be an object");let e=t.first===void 0?20:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw new Error("first must be an integer between 1 and 50");for(let n of["after","newerThan"]){let i=t[n];if(i!==void 0&&(typeof i!="string"||!i.trim()))throw new Error(`${n} must be a non-empty cursor`)}if(t.feedId!==void 0&&!x(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}s(zi,"validateForYouListParams");function Ae(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}s(Ae,"invalidResponse");function Ji(t){if(!h(t)||!Array.isArray(t.edges)||!h(t.pageInfo))return Ae();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return Ae();for(let o of t.edges){if(!h(o)||typeof o.cursor!="string"||!o.cursor.trim()||!h(o.node))return Ae();let r=o.node;if(typeof r.id!="string"||!r.id.startsWith("FeedEntry:")||!x(r.id.slice(10))||!h(r.feed)||!x(r.feed.id)||!h(r.major)||typeof r.major.id!="string"||!x(r.major.feedId)||typeof r.title!="string"||typeof r.body!="string")return Ae()}let n=t.edges[0],i=t.edges[t.edges.length-1];return e.startCursor!==(n?.cursor??"")||e.endCursor!==(i?.cursor??"")||t.edges.length===0&&e.hasNextPage?Ae():t}s(Ji,"connection");var Zi=`
50
50
  query ToolkitForYouTheses($input: ThesisRecommendationInput) {
51
51
  viewer {
52
52
  thesisRecommendations(input: $input) {
@@ -57,14 +57,14 @@ query ToolkitForYouTheses($input: ThesisRecommendationInput) {
57
57
  node {
58
58
  itemKey
59
59
  publication {
60
- ${z}
60
+ ${te}
61
61
  }
62
62
  }
63
63
  }
64
64
  }
65
65
  }
66
66
  }
67
- `.trim();function Ci(t){if(!m(t))throw new Error("Thesis parameters must be an object");let e=t.first===void 0?10:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>10)throw new Error("first must be an integer between 1 and 10");if(t.after!==void 0&&(typeof t.after!="string"||!t.after.trim()))throw new Error("after must be a non-empty cursor")}s(Ci,"validateForYouThesesParams");function un(t,e){if(!m(t))throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${e} response`,502);if(t.errors!==void 0){if(!Array.isArray(t.errors))throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${e} response`,502);if(t.errors.length>0){let n=t.errors.flatMap(i=>m(i)&&typeof i.message=="string"?[i.message]:[]);throw new l("GRAPHQL_ERROR",n.join("; ")||"GraphQL request failed",400,{errors:t.errors})}}if(!m(t.data)||!m(t.data.viewer)||t.data.viewer[e]==null)throw new l("GRAPHQL_EMPTY_RESPONSE",`GraphQL response did not include viewer.${e}`,502);return t.data.viewer[e]}s(un,"graphqlViewerField");function Me(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid Thesis recommendation page",502)}s(Me,"invalidPage");function xi(t){if(!m(t)||!Array.isArray(t.edges)||!m(t.pageInfo)||typeof t.listId!="string"||typeof t.pageCursor!="string"||typeof t.exhausted!="boolean"||typeof t.scanLimited!="boolean"||t.nextCursor!==null&&typeof t.nextCursor!="string")return Me();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean"||e.hasNextPage!==(t.nextCursor!==null))return Me();for(let i of t.edges)if(!m(i)||typeof i.cursor!="string"||!i.cursor.trim()||!m(i.node)||typeof i.node.itemKey!="string"||!i.node.itemKey.trim()||!J(i.node.publication))return Me();let n=t.edges[0];return e.startCursor!==(n?.cursor??"")?Me():t}s(xi,"recommendationPage");var Z=class{constructor(e){this.client=e}client;static{s(this,"ForYouResource")}async list(e={}){Ai(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Ei,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});return vi(un(n,"forYou"))}async theses(e={}){Ci(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Ii,variables:{input:{first:e.first??10,after:e.after}}}}),i=un(n,"thesisRecommendations");return xi(i)}};var qi=`
67
+ `.trim();function er(t){if(!h(t))throw new Error("Thesis parameters must be an object");let e=t.first===void 0?10:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>10)throw new Error("first must be an integer between 1 and 10");if(t.after!==void 0&&(typeof t.after!="string"||!t.after.trim()))throw new Error("after must be a non-empty cursor")}s(er,"validateForYouThesesParams");function bn(t,e){if(!h(t))throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${e} response`,502);if(t.errors!==void 0){if(!Array.isArray(t.errors))throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${e} response`,502);if(t.errors.length>0){let n=t.errors.flatMap(i=>h(i)&&typeof i.message=="string"?[i.message]:[]);throw new l("GRAPHQL_ERROR",n.join("; ")||"GraphQL request failed",400,{errors:t.errors})}}if(!h(t.data)||!h(t.data.viewer)||t.data.viewer[e]==null)throw new l("GRAPHQL_EMPTY_RESPONSE",`GraphQL response did not include viewer.${e}`,502);return t.data.viewer[e]}s(bn,"graphqlViewerField");function Qe(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid Thesis recommendation page",502)}s(Qe,"invalidPage");function tr(t){if(!h(t)||!Array.isArray(t.edges)||!h(t.pageInfo)||typeof t.listId!="string"||typeof t.pageCursor!="string"||typeof t.exhausted!="boolean"||typeof t.scanLimited!="boolean"||t.nextCursor!==null&&typeof t.nextCursor!="string")return Qe();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean"||e.hasNextPage!==(t.nextCursor!==null))return Qe();for(let i of t.edges)if(!h(i)||typeof i.cursor!="string"||!i.cursor.trim()||!h(i.node)||typeof i.node.itemKey!="string"||!i.node.itemKey.trim()||!ne(i.node.publication))return Qe();let n=t.edges[0];return e.startCursor!==(n?.cursor??"")?Qe():t}s(tr,"recommendationPage");var ie=class{constructor(e){this.client=e}client;static{s(this,"ForYouResource")}async list(e={}){zi(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Xi,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});return Ji(bn(n,"forYou"))}async theses(e={}){er(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Zi,variables:{input:{first:e.first??10,after:e.after}}}}),i=bn(n,"thesisRecommendations");return tr(i)}};var nr=`
68
68
  query ToolkitAutomationAlertDelivery($automationId: ID!) {
69
69
  automation(id: $automationId) {
70
70
  alertDelivery {
@@ -74,7 +74,7 @@ query ToolkitAutomationAlertDelivery($automationId: ID!) {
74
74
  }
75
75
  }
76
76
  }
77
- `.trim(),Ni=`
77
+ `.trim(),ir=`
78
78
  mutation ToolkitUpdateAutomationAlertDelivery(
79
79
  $input: UpdateAutomationAlertDeliveryInput!
80
80
  $includeAlvaChannels: Boolean!
@@ -89,7 +89,7 @@ mutation ToolkitUpdateAutomationAlertDelivery(
89
89
  }
90
90
  }
91
91
  }
92
- `.trim(),ee=class{constructor(e){this.client=e;this.delivery=new Re(e)}client;static{s(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=Di(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=$e(e.id);if(!Ui(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(n))}`,{body:{version:e.version,cronjob_id:e.cronjob_id,description:e.description,changelog:e.changelog,agent_type:e.agent_type,trigger:e.trigger}})}stop(e){return this.client.feed.stop(e)}resume(e){return this.client.feed.resume(e)}delete(e){return this.client.feed.delete(e)}publish(e){return this.client.release.feed(e)}},Re=class{constructor(e){this.client=e}client;static{s(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=$e(e.id),o=(await this.graphql(qi,{automationId:n})).automation?.alertDelivery;if(!o)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return o}async update(e){this.client._requireAuth();let n=$e(e.id),i=e.alvaChannelIds!==void 0,o=e.emailEnabled!==void 0;if(!i&&!o)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let r=i?Li(e.alvaChannelIds??[]):void 0,u=(await this.graphql(Ni,{input:{automationId:n,...i?{alvaChannelIds:r}:{},...o?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,includeEmail:o})).updateAutomationAlertDelivery;if(!u)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return u}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Fi(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};function Di(t){if(typeof t=="string")return $e(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}s(Di,"requireAutomationID");function $e(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}s($e,"requireAutomationIDString");function Ui(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}s(Ui,"hasAutomationUpdate");function Li(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}s(Li,"uniqueAlvaChannelIDs");function Fi(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}s(Fi,"graphQLErrorMessage");var cn=["public","private","paid"];var je=class{constructor(e){this.client=e}client;static{s(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new l("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let i=e.ref.slice(0,n),o=e.ref.slice(n+1),r;for(;;){let a=await this.listByOwner({owner:i,cursor:r,limit:100}),u=a.items.find(c=>c.name===o);if(u)return u;if(!a.has_next||!a.next_cursor)return null;r=a.next_cursor}}throw new l("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let n={};e.cursor&&(n.cursor=e.cursor),e.current&&(n.current=e.current),e.limit!==void 0&&(n.limit=e.limit),e.dir&&(n.dir=e.dir),e.sort&&(n.sort=e.sort),e.keyword&&(n.keyword=e.keyword),e.tags&&e.tags.length>0&&(n.tags=e.tags.join(","));let i=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),o=Oi(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(r=>Gi(r,o)),has_next:i.has_next??!1}}async setVisibility(e){if(!cn.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${cn.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Oi(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let i=n[1].toLowerCase();return i==="prd"?"https://alva.ai":`https://${i}.alva.ai`}}catch{}return"https://alva.ai"}s(Oi,"webOriginFromApiBase");function Gi(t,e){let n=t.creator?.name??"",i=t.name??"",o=n&&i?`${n}/${i}`:i,r=n&&i?`/u/${n}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:o,username:n,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:r,url:r?`${e}${r}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}s(Gi,"toAgentPlaybook");var Be=class{constructor(e){this.client=e}client;static{s(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var Qe=class{constructor(e){this.client=e}client;static{s(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var ln=[{skill:"arrays-data-api-crypto-futures-data",file:"binance-perp-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/perp/usdt/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"binance-spot-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/spot/usdt/kline"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"fear-greed-index",method:"GET",path:"/api/v1/crypto/fear-greed-index"},{skill:"arrays-data-api-crypto-futures-data",file:"funding-rate",method:"GET",path:"/api/v1/crypto/funding-rate"},{skill:"arrays-data-api-crypto-futures-data",file:"hyperliquid-perp-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/perp/usdc/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"hyperliquid-spot-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/spot/usdc/kline"},{skill:"arrays-data-api-crypto-futures-data",file:"long-short-ratio",method:"GET",path:"/api/v1/crypto/long-short-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-market-cap",method:"GET",path:"/api/v1/crypto/market-cap"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"market-metrics",method:"GET",path:"/api/v1/crypto/market-metrics"},{skill:"arrays-data-api-crypto-futures-data",file:"open-interest",method:"GET",path:"/api/v1/crypto/open-interest"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics",method:"GET",path:"/api/v1/crypto/screener/metrics"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics-timerange",method:"GET",path:"/api/v1/crypto/screener/metrics/timerange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-detail",method:"GET",path:"/api/v1/crypto/detail"},{skill:"arrays-data-api-etf-fundamentals",file:"country-weightings",method:"GET",path:"/api/v1/etf/country-weightings"},{skill:"arrays-data-api-etf-fundamentals",file:"holdings",method:"GET",path:"/api/v1/etf/holdings"},{skill:"arrays-data-api-etf-fundamentals",file:"info",method:"GET",path:"/api/v1/etf/info"},{skill:"arrays-data-api-etf-fundamentals",file:"sector-weightings",method:"GET",path:"/api/v1/etf/sector-weightings"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-historical",method:"GET",path:"/api/v1/macro/commodity/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-real-time",method:"GET",path:"/api/v1/macro/commodity/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-symbol-list",method:"GET",path:"/api/v1/macro/commodity/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"economic-indicators",method:"GET",path:"/api/v1/macro/economic-indicators"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-historical",method:"GET",path:"/api/v1/macro/forex/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-real-time",method:"GET",path:"/api/v1/macro/forex/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-symbol-list",method:"GET",path:"/api/v1/macro/forex/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-historical",method:"GET",path:"/api/v1/macro/index/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-real-time",method:"GET",path:"/api/v1/macro/index/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"rates",method:"GET",path:"/api/v1/macro/treasury-rates"},{skill:"arrays-data-api-equity-fundamentals",file:"company-balance-sheets",method:"GET",path:"/api/v1/stocks/company/balance-sheets"},{skill:"arrays-data-api-equity-fundamentals",file:"company-cashflow-statements",method:"GET",path:"/api/v1/stocks/company/cashflow-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail",method:"GET",path:"/api/v1/stocks/company/detail"},{skill:"arrays-data-api-equity-fundamentals",file:"company-income-statements",method:"GET",path:"/api/v1/stocks/company/income-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-kpi",method:"GET",path:"/api/v1/stocks/company/kpi"},{skill:"arrays-data-api-equity-events",file:"crowdfunding-offerings",method:"GET",path:"/api/v1/stocks/crowdfunding/offerings"},{skill:"arrays-data-api-equity-events",file:"dividends",method:"GET",path:"/api/v1/stocks/dividends"},{skill:"arrays-data-api-equity-events",file:"earnings-calendar",method:"GET",path:"/api/v1/stocks/earnings-calendar"},{skill:"arrays-data-api-equity-events",file:"equity-offering",method:"GET",path:"/api/v1/stocks/equity-offering"},{skill:"arrays-data-api-stock-metrics",file:"financial-metrics",method:"GET",path:"/api/v1/stocks/financial-metrics"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates",method:"GET",path:"/api/v1/stocks/fiscal-dates"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates-range",method:"GET",path:"/api/v1/stocks/fiscal-dates/range"},{skill:"arrays-data-api-equity-events",file:"ipo-calendar",method:"GET",path:"/api/v1/stocks/ipo-calendar"},{skill:"arrays-data-api-equity-events",file:"ipo-confirmed-calendar",method:"GET",path:"/api/v1/stocks/ipo-confirmed-calendar"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-kline",method:"GET",path:"/api/v1/stocks/kline"},{skill:"arrays-data-api-stock-metrics",file:"market-metrics",method:"GET",path:"/api/v1/stocks/market-metrics"},{skill:"arrays-data-api-equity-events",file:"mergers-acquisitions",method:"GET",path:"/api/v1/stocks/mergers-acquisitions"},{skill:"arrays-data-api-equity-fundamentals",file:"outstanding-shares",method:"GET",path:"/api/v1/stocks/outstanding-shares"},{skill:"arrays-data-api-stock-metrics",file:"ratings",method:"GET",path:"/api/v1/stocks/ratings"},{skill:"arrays-data-api-stock-screener",file:"basic-info-screener",method:"GET",path:"/api/v1/stocks/screener/basic-info/{sub}"},{skill:"arrays-data-api-stock-screener",file:"event-screener",method:"GET",path:"/api/v1/stocks/screener/events"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics",method:"GET",path:"/api/v1/stocks/screener/financial-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/financial-metrics/timerange"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics",method:"GET",path:"/api/v1/stocks/screener/technical-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/technical-metrics/timerange"},{skill:"arrays-data-api-equity-events",file:"sec-earnings-release",method:"GET",path:"/api/v1/stocks/sec-earnings-release"},{skill:"arrays-data-api-equity-fundamentals",file:"shares-float",method:"GET",path:"/api/v1/stocks/shares-float"},{skill:"arrays-data-api-equity-events",file:"splits",method:"GET",path:"/api/v1/stocks/splits"},{skill:"arrays-data-api-crypto-exchange-flow",file:"exchange-flows",method:"GET",path:"/api/v1/crypto/exchange-flows"},{skill:"arrays-data-api-company-crypto-holdings",file:"crypto-holdings",method:"GET",path:"/api/v1/crypto/holdings"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-inflow-cdd",method:"GET",path:"/api/v1/crypto/metrics/inflow-cdd"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-leverage-ratio",method:"GET",path:"/api/v1/crypto/metrics/leverage-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-miner-to-exchange",method:"GET",path:"/api/v1/crypto/metrics/miner-to-exchange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-mvrv",method:"GET",path:"/api/v1/crypto/metrics/mvrv"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-nupl",method:"GET",path:"/api/v1/crypto/metrics/nupl"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-puell-multiple",method:"GET",path:"/api/v1/crypto/metrics/puell-multiple"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-realized-price",method:"GET",path:"/api/v1/crypto/metrics/realized-price"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-sopr",method:"GET",path:"/api/v1/crypto/metrics/sopr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-ssr",method:"GET",path:"/api/v1/crypto/metrics/ssr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-whale-ratio",method:"GET",path:"/api/v1/crypto/metrics/whale-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-supply",method:"GET",path:"/api/v1/crypto/supply"},{skill:"arrays-data-api-crypto-futures-data",file:"taker-buy-sell-volume",method:"GET",path:"/api/v1/crypto/taker-buy-sell-volume"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"unlock-events",method:"GET",path:"/api/v1/crypto/unlock-events"},{skill:"arrays-data-api-etf-fundamentals",file:"flow",method:"GET",path:"/api/v1/etf/flow"},{skill:"arrays-data-api-options",file:"contracts",method:"GET",path:"/api/v1/options/contracts"},{skill:"arrays-data-api-options",file:"kline",method:"GET",path:"/api/v1/options/kline"},{skill:"arrays-data-api-options",file:"greeks",method:"GET",path:"/api/v1/options/greeks"},{skill:"arrays-data-api-options",file:"chain",method:"GET",path:"/api/v1/options/chain"},{skill:"arrays-data-api-equity-fundamentals",file:"company-executives",method:"GET",path:"/api/v1/stocks/company/executives"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-consensus",method:"GET",path:"/api/v1/stocks/company/price-target-consensus"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-news",method:"GET",path:"/api/v1/stocks/company/price-target-news"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-summary",method:"GET",path:"/api/v1/stocks/company/price-target-summary"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"congress-recent-trades",method:"GET",path:"/api/v1/stocks/congress/recent-trades"},{skill:"arrays-data-api-stock-metrics",file:"darkpool",method:"GET",path:"/api/v1/stocks/darkpool"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"estimates-guidance",method:"GET",path:"/api/v1/stocks/estimates-guidance"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"insider-transactions",method:"GET",path:"/api/v1/stocks/insider/transactions"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"institution-holder",method:"GET",path:"/api/v1/stocks/institution-holder"},{skill:"arrays-data-api-polymarket",file:"activity",method:"GET",path:"polymarket:/activity"},{skill:"arrays-data-api-polymarket",file:"book",method:"GET",path:"polymarket:/book"},{skill:"arrays-data-api-polymarket",file:"closed-positions",method:"GET",path:"polymarket:/closed-positions"},{skill:"arrays-data-api-polymarket",file:"events",method:"GET",path:"polymarket:/events"},{skill:"arrays-data-api-polymarket",file:"holders",method:"GET",path:"polymarket:/holders"},{skill:"arrays-data-api-polymarket",file:"markets",method:"GET",path:"polymarket:/markets"},{skill:"arrays-data-api-polymarket",file:"midpoint",method:"GET",path:"polymarket:/midpoint"},{skill:"arrays-data-api-polymarket",file:"oi",method:"GET",path:"polymarket:/oi"},{skill:"arrays-data-api-polymarket",file:"positions",method:"GET",path:"polymarket:/positions"},{skill:"arrays-data-api-polymarket",file:"price",method:"GET",path:"polymarket:/price"},{skill:"arrays-data-api-polymarket",file:"prices-history",method:"GET",path:"polymarket:/prices-history"},{skill:"arrays-data-api-polymarket",file:"public-search",method:"GET",path:"polymarket:/public-search"},{skill:"arrays-data-api-polymarket",file:"series",method:"GET",path:"polymarket:/series"},{skill:"arrays-data-api-polymarket",file:"sports",method:"GET",path:"polymarket:/sports"},{skill:"arrays-data-api-polymarket",file:"spread",method:"GET",path:"polymarket:/spread"},{skill:"arrays-data-api-polymarket",file:"tags",method:"GET",path:"polymarket:/tags"},{skill:"arrays-data-api-polymarket",file:"trades",method:"GET",path:"polymarket:/trades"},{skill:"arrays-data-api-polymarket",file:"value",method:"GET",path:"polymarket:/value"},{skill:"arrays-data-api-equity-events",file:"earnings-transcript",method:"GET",path:"/api/v1/stocks/earnings-transcript"},{skill:"arrays-data-api-news",file:"market-news",method:"GET",path:"/api/v1/stocks/market-news"},{skill:"arrays-data-api-social-feeds",file:"x-by-handle",method:"GET",path:"/api/v1/social-feeds/x/by-handle"},{skill:"arrays-data-api-social-feeds",file:"x-by-url",method:"GET",path:"/api/v1/social-feeds/x/by-url"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handle",method:"GET",path:"/api/v1/social-feeds/x/entities/handle/{twitter_handle}"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handles",method:"GET",path:"/api/v1/social-feeds/x/entities/handles"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail-non-us",method:"GET",path:"/api/v1/stocks/non-us/company/detail"},{skill:"arrays-data-api-social-feeds",file:"x-search",method:"GET",path:"/api/v1/social-feeds/x/search"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-non-us-kline",method:"GET",path:"/api/v1/stocks/non-us/kline"},{skill:"arrays-data-api-semiconductor-price",file:"dram-spot-price",method:"GET",path:"/api/v1/other/semiconductor/dram-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"dram-contract-price",method:"GET",path:"/api/v1/other/semiconductor/dram-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-spot-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-contract-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"memory-card-price",method:"GET",path:"/api/v1/other/semiconductor/memory-card-price"},{skill:"arrays-data-api-semiconductor-price",file:"dxi-index",method:"GET",path:"/api/v1/other/semiconductor/dxi-index"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"short-interest",method:"GET",path:"/api/v1/stocks/short-interest"},{skill:"arrays-data-api-social-feeds",file:"x-handles",method:"POST",path:"/api/v1/social-feeds/x/handles"}];function dn(t,e){return ln.find(n=>n.skill===t&&n.file===e)}s(dn,"getSkillEndpointMetadata");function Tt(t){return ln.filter(e=>e.skill===t)}s(Tt,"listSkillEndpointMetadata");var Ve=class{constructor(e){this.client=e}client;static{s(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...pn(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),o=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!o)throw new Error(`empty skills summary response for "${e.name}"`);let r=Tt(e.name);return{...o,...pn(e.name),...r.length>0?{endpoint_metadata:r}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),o=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!o)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let r=dn(e.name,e.file);return{...o,...r?{metadata:r}:{}}}};function pn(t){let e=Tt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}s(pn,"metadataSummaryForSkill");function mn(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}s(mn,"normalizePlaybookSkillSummary");function hn(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new l("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}s(hn,"parsePlaybookSkillId");var He=class{constructor(e){this.client=e}client;static{s(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(mn)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=hn(e),o=encodeURIComponent(n),r=encodeURIComponent(i),u=(await this.client._request("GET",`/api/v1/skills/${o}/${r}`)).data?.[0];if(!u)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...mn(u),files:u.files??[]}}async file(e,n){let{username:i,name:o}=hn(e),r=encodeURIComponent(i),a=encodeURIComponent(o),u=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${r}/${a}/files/${u}`)).data?.[0];if(!d)throw new l("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var Ye=class{constructor(e){this.client=e}client;static{s(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var We=class{constructor(e){this.client=e}client;static{s(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var Ke=class{constructor(e){this.client=e}client;static{s(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var Xe=class{constructor(e){this.client=e}client;static{s(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var ze=class{constructor(e){this.client=e}client;static{s(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var Je=class{constructor(e){this.client=e}client;static{s(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var Ze=class{constructor(e){this.client=e}client;static{s(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var et=class{constructor(e){this.client=e}client;static{s(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:Mi(e)})}};function Mi(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}s(Mi,"buildQuery");var tt=class{constructor(e){this.client=e}client;static{s(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var nt=class{constructor(e){this.client=e}client;static{s(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var te=class{constructor(e){this.client=e}client;static{s(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var it=class{constructor(e){this.client=e}client;static{s(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:fn(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:fn(e)})}async getGroupChatHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-history",{query:{channel:e.channel,remote_chat_id:e.remote_chat_id,from_micros:String(e.from_micros),to_micros:String(e.to_micros)}})}};function fn(t){return`{"session_id":${yn(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${yn(t.target_id)}}`}s(fn,"mutationBody");function yn(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}s(yn,"idLiteral");var st=class{constructor(e){this.client=e}client;static{s(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var rt=class{constructor(e){this.client=e}client;static{s(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:ji(n.result)}}async getAllowance(e){this.client._requireAuth();let n=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return Rt(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>Rt(n)).filter(n=>n!==null)}}async createAllowance(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:$i(n.allowance)}}async revokeAllowance(e){return this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}}),{ok:!0}}};function Rt(t){if(!t)return null;let e={id:t.id??"",consumer_uid:t.consumer_uid??t.consumerUid??"",playbook_id:t.playbook_id??t.playbookId??"",amount:t.amount??0,used:t.used??0,remaining:t.remaining??0},n=gn(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=gn(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),i!==void 0&&(e.updated_at_ms=i),e}s(Rt,"normalizeAllowance");function $i(t){let e=Rt(t);if(!e)throw new Error("allowance response missing allowance");return e}s($i,"requireAllowance");function gn(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let o=Number(t);if(Number.isFinite(o))return o;let r=Date.parse(t);return Number.isNaN(r)?void 0:r}if(typeof t!="object")return;let e=t,n=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,i=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}s(gn,"timestampMs");function ji(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}s(ji,"parseResultPayload");var Bi=`
92
+ `.trim(),re=class{constructor(e){this.client=e;this.delivery=new ve(e)}client;static{s(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=rr(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=We(e.id);if(!sr(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(n))}`,{body:{version:e.version,cronjob_id:e.cronjob_id,description:e.description,changelog:e.changelog,agent_type:e.agent_type,trigger:e.trigger}})}stop(e){return this.client.feed.stop(e)}resume(e){return this.client.feed.resume(e)}delete(e){return this.client.feed.delete(e)}publish(e){return this.client.release.feed(e)}},ve=class{constructor(e){this.client=e}client;static{s(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=We(e.id),o=(await this.graphql(nr,{automationId:n})).automation?.alertDelivery;if(!o)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return o}async update(e){this.client._requireAuth();let n=We(e.id),i=e.alvaChannelIds!==void 0,o=e.emailEnabled!==void 0;if(!i&&!o)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let r=i?or(e.alvaChannelIds??[]):void 0,u=(await this.graphql(ir,{input:{automationId:n,...i?{alvaChannelIds:r}:{},...o?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,includeEmail:o})).updateAutomationAlertDelivery;if(!u)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return u}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",ar(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};function rr(t){if(typeof t=="string")return We(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}s(rr,"requireAutomationID");function We(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}s(We,"requireAutomationIDString");function sr(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}s(sr,"hasAutomationUpdate");function or(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}s(or,"uniqueAlvaChannelIDs");function ar(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}s(ar,"graphQLErrorMessage");var wn=["public","private","paid"];var Ve=class{constructor(e){this.client=e}client;static{s(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new l("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let i=e.ref.slice(0,n),o=e.ref.slice(n+1),r;for(;;){let a=await this.listByOwner({owner:i,cursor:r,limit:100}),u=a.items.find(c=>c.name===o);if(u)return u;if(!a.has_next||!a.next_cursor)return null;r=a.next_cursor}}throw new l("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let n={};e.cursor&&(n.cursor=e.cursor),e.current&&(n.current=e.current),e.limit!==void 0&&(n.limit=e.limit),e.dir&&(n.dir=e.dir),e.sort&&(n.sort=e.sort),e.keyword&&(n.keyword=e.keyword),e.tags&&e.tags.length>0&&(n.tags=e.tags.join(","));let i=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),o=ur(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(r=>cr(r,o)),has_next:i.has_next??!1}}async setVisibility(e){if(!wn.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${wn.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function ur(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let i=n[1].toLowerCase();return i==="prd"?"https://alva.ai":`https://${i}.alva.ai`}}catch{}return"https://alva.ai"}s(ur,"webOriginFromApiBase");function cr(t,e){let n=t.creator?.name??"",i=t.name??"",o=n&&i?`${n}/${i}`:i,r=n&&i?`/u/${n}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:o,username:n,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:r,url:r?`${e}${r}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}s(cr,"toAgentPlaybook");var He=class{constructor(e){this.client=e}client;static{s(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var Ye=class{constructor(e){this.client=e}client;static{s(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var Pn=[{skill:"arrays-data-api-crypto-futures-data",file:"binance-perp-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/perp/usdt/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"binance-spot-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/spot/usdt/kline"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"fear-greed-index",method:"GET",path:"/api/v1/crypto/fear-greed-index"},{skill:"arrays-data-api-crypto-futures-data",file:"funding-rate",method:"GET",path:"/api/v1/crypto/funding-rate"},{skill:"arrays-data-api-crypto-futures-data",file:"hyperliquid-perp-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/perp/usdc/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"hyperliquid-spot-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/spot/usdc/kline"},{skill:"arrays-data-api-crypto-futures-data",file:"long-short-ratio",method:"GET",path:"/api/v1/crypto/long-short-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-market-cap",method:"GET",path:"/api/v1/crypto/market-cap"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"market-metrics",method:"GET",path:"/api/v1/crypto/market-metrics"},{skill:"arrays-data-api-crypto-futures-data",file:"open-interest",method:"GET",path:"/api/v1/crypto/open-interest"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics",method:"GET",path:"/api/v1/crypto/screener/metrics"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics-timerange",method:"GET",path:"/api/v1/crypto/screener/metrics/timerange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-detail",method:"GET",path:"/api/v1/crypto/detail"},{skill:"arrays-data-api-etf-fundamentals",file:"country-weightings",method:"GET",path:"/api/v1/etf/country-weightings"},{skill:"arrays-data-api-etf-fundamentals",file:"holdings",method:"GET",path:"/api/v1/etf/holdings"},{skill:"arrays-data-api-etf-fundamentals",file:"info",method:"GET",path:"/api/v1/etf/info"},{skill:"arrays-data-api-etf-fundamentals",file:"sector-weightings",method:"GET",path:"/api/v1/etf/sector-weightings"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-historical",method:"GET",path:"/api/v1/macro/commodity/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-real-time",method:"GET",path:"/api/v1/macro/commodity/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-symbol-list",method:"GET",path:"/api/v1/macro/commodity/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"economic-indicators",method:"GET",path:"/api/v1/macro/economic-indicators"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-historical",method:"GET",path:"/api/v1/macro/forex/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-real-time",method:"GET",path:"/api/v1/macro/forex/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-symbol-list",method:"GET",path:"/api/v1/macro/forex/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-historical",method:"GET",path:"/api/v1/macro/index/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-real-time",method:"GET",path:"/api/v1/macro/index/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"rates",method:"GET",path:"/api/v1/macro/treasury-rates"},{skill:"arrays-data-api-equity-fundamentals",file:"company-balance-sheets",method:"GET",path:"/api/v1/stocks/company/balance-sheets"},{skill:"arrays-data-api-equity-fundamentals",file:"company-cashflow-statements",method:"GET",path:"/api/v1/stocks/company/cashflow-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail",method:"GET",path:"/api/v1/stocks/company/detail"},{skill:"arrays-data-api-equity-fundamentals",file:"company-income-statements",method:"GET",path:"/api/v1/stocks/company/income-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-kpi",method:"GET",path:"/api/v1/stocks/company/kpi"},{skill:"arrays-data-api-equity-events",file:"crowdfunding-offerings",method:"GET",path:"/api/v1/stocks/crowdfunding/offerings"},{skill:"arrays-data-api-equity-events",file:"dividends",method:"GET",path:"/api/v1/stocks/dividends"},{skill:"arrays-data-api-equity-events",file:"earnings-calendar",method:"GET",path:"/api/v1/stocks/earnings-calendar"},{skill:"arrays-data-api-equity-events",file:"equity-offering",method:"GET",path:"/api/v1/stocks/equity-offering"},{skill:"arrays-data-api-stock-metrics",file:"financial-metrics",method:"GET",path:"/api/v1/stocks/financial-metrics"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates",method:"GET",path:"/api/v1/stocks/fiscal-dates"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates-range",method:"GET",path:"/api/v1/stocks/fiscal-dates/range"},{skill:"arrays-data-api-equity-events",file:"ipo-calendar",method:"GET",path:"/api/v1/stocks/ipo-calendar"},{skill:"arrays-data-api-equity-events",file:"ipo-confirmed-calendar",method:"GET",path:"/api/v1/stocks/ipo-confirmed-calendar"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-kline",method:"GET",path:"/api/v1/stocks/kline"},{skill:"arrays-data-api-stock-metrics",file:"market-metrics",method:"GET",path:"/api/v1/stocks/market-metrics"},{skill:"arrays-data-api-equity-events",file:"mergers-acquisitions",method:"GET",path:"/api/v1/stocks/mergers-acquisitions"},{skill:"arrays-data-api-equity-fundamentals",file:"outstanding-shares",method:"GET",path:"/api/v1/stocks/outstanding-shares"},{skill:"arrays-data-api-stock-metrics",file:"ratings",method:"GET",path:"/api/v1/stocks/ratings"},{skill:"arrays-data-api-stock-screener",file:"basic-info-screener",method:"GET",path:"/api/v1/stocks/screener/basic-info/{sub}"},{skill:"arrays-data-api-stock-screener",file:"event-screener",method:"GET",path:"/api/v1/stocks/screener/events"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics",method:"GET",path:"/api/v1/stocks/screener/financial-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/financial-metrics/timerange"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics",method:"GET",path:"/api/v1/stocks/screener/technical-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/technical-metrics/timerange"},{skill:"arrays-data-api-equity-events",file:"sec-earnings-release",method:"GET",path:"/api/v1/stocks/sec-earnings-release"},{skill:"arrays-data-api-equity-fundamentals",file:"shares-float",method:"GET",path:"/api/v1/stocks/shares-float"},{skill:"arrays-data-api-equity-events",file:"splits",method:"GET",path:"/api/v1/stocks/splits"},{skill:"arrays-data-api-crypto-exchange-flow",file:"exchange-flows",method:"GET",path:"/api/v1/crypto/exchange-flows"},{skill:"arrays-data-api-company-crypto-holdings",file:"crypto-holdings",method:"GET",path:"/api/v1/crypto/holdings"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-inflow-cdd",method:"GET",path:"/api/v1/crypto/metrics/inflow-cdd"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-leverage-ratio",method:"GET",path:"/api/v1/crypto/metrics/leverage-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-miner-to-exchange",method:"GET",path:"/api/v1/crypto/metrics/miner-to-exchange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-mvrv",method:"GET",path:"/api/v1/crypto/metrics/mvrv"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-nupl",method:"GET",path:"/api/v1/crypto/metrics/nupl"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-puell-multiple",method:"GET",path:"/api/v1/crypto/metrics/puell-multiple"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-realized-price",method:"GET",path:"/api/v1/crypto/metrics/realized-price"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-sopr",method:"GET",path:"/api/v1/crypto/metrics/sopr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-ssr",method:"GET",path:"/api/v1/crypto/metrics/ssr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-whale-ratio",method:"GET",path:"/api/v1/crypto/metrics/whale-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-supply",method:"GET",path:"/api/v1/crypto/supply"},{skill:"arrays-data-api-crypto-futures-data",file:"taker-buy-sell-volume",method:"GET",path:"/api/v1/crypto/taker-buy-sell-volume"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"unlock-events",method:"GET",path:"/api/v1/crypto/unlock-events"},{skill:"arrays-data-api-etf-fundamentals",file:"flow",method:"GET",path:"/api/v1/etf/flow"},{skill:"arrays-data-api-options",file:"contracts",method:"GET",path:"/api/v1/options/contracts"},{skill:"arrays-data-api-options",file:"kline",method:"GET",path:"/api/v1/options/kline"},{skill:"arrays-data-api-options",file:"greeks",method:"GET",path:"/api/v1/options/greeks"},{skill:"arrays-data-api-options",file:"chain",method:"GET",path:"/api/v1/options/chain"},{skill:"arrays-data-api-equity-fundamentals",file:"company-executives",method:"GET",path:"/api/v1/stocks/company/executives"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-consensus",method:"GET",path:"/api/v1/stocks/company/price-target-consensus"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-news",method:"GET",path:"/api/v1/stocks/company/price-target-news"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-summary",method:"GET",path:"/api/v1/stocks/company/price-target-summary"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"congress-recent-trades",method:"GET",path:"/api/v1/stocks/congress/recent-trades"},{skill:"arrays-data-api-stock-metrics",file:"darkpool",method:"GET",path:"/api/v1/stocks/darkpool"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"estimates-guidance",method:"GET",path:"/api/v1/stocks/estimates-guidance"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"insider-transactions",method:"GET",path:"/api/v1/stocks/insider/transactions"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"institution-holder",method:"GET",path:"/api/v1/stocks/institution-holder"},{skill:"arrays-data-api-polymarket",file:"activity",method:"GET",path:"polymarket:/activity"},{skill:"arrays-data-api-polymarket",file:"book",method:"GET",path:"polymarket:/book"},{skill:"arrays-data-api-polymarket",file:"closed-positions",method:"GET",path:"polymarket:/closed-positions"},{skill:"arrays-data-api-polymarket",file:"events",method:"GET",path:"polymarket:/events"},{skill:"arrays-data-api-polymarket",file:"holders",method:"GET",path:"polymarket:/holders"},{skill:"arrays-data-api-polymarket",file:"markets",method:"GET",path:"polymarket:/markets"},{skill:"arrays-data-api-polymarket",file:"midpoint",method:"GET",path:"polymarket:/midpoint"},{skill:"arrays-data-api-polymarket",file:"oi",method:"GET",path:"polymarket:/oi"},{skill:"arrays-data-api-polymarket",file:"positions",method:"GET",path:"polymarket:/positions"},{skill:"arrays-data-api-polymarket",file:"price",method:"GET",path:"polymarket:/price"},{skill:"arrays-data-api-polymarket",file:"prices-history",method:"GET",path:"polymarket:/prices-history"},{skill:"arrays-data-api-polymarket",file:"public-search",method:"GET",path:"polymarket:/public-search"},{skill:"arrays-data-api-polymarket",file:"series",method:"GET",path:"polymarket:/series"},{skill:"arrays-data-api-polymarket",file:"sports",method:"GET",path:"polymarket:/sports"},{skill:"arrays-data-api-polymarket",file:"spread",method:"GET",path:"polymarket:/spread"},{skill:"arrays-data-api-polymarket",file:"tags",method:"GET",path:"polymarket:/tags"},{skill:"arrays-data-api-polymarket",file:"trades",method:"GET",path:"polymarket:/trades"},{skill:"arrays-data-api-polymarket",file:"value",method:"GET",path:"polymarket:/value"},{skill:"arrays-data-api-equity-events",file:"earnings-transcript",method:"GET",path:"/api/v1/stocks/earnings-transcript"},{skill:"arrays-data-api-news",file:"market-news",method:"GET",path:"/api/v1/stocks/market-news"},{skill:"arrays-data-api-social-feeds",file:"x-by-handle",method:"GET",path:"/api/v1/social-feeds/x/by-handle"},{skill:"arrays-data-api-social-feeds",file:"x-by-url",method:"GET",path:"/api/v1/social-feeds/x/by-url"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handle",method:"GET",path:"/api/v1/social-feeds/x/entities/handle/{twitter_handle}"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handles",method:"GET",path:"/api/v1/social-feeds/x/entities/handles"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail-non-us",method:"GET",path:"/api/v1/stocks/non-us/company/detail"},{skill:"arrays-data-api-social-feeds",file:"x-search",method:"GET",path:"/api/v1/social-feeds/x/search"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-non-us-kline",method:"GET",path:"/api/v1/stocks/non-us/kline"},{skill:"arrays-data-api-semiconductor-price",file:"dram-spot-price",method:"GET",path:"/api/v1/other/semiconductor/dram-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"dram-contract-price",method:"GET",path:"/api/v1/other/semiconductor/dram-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-spot-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-contract-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"memory-card-price",method:"GET",path:"/api/v1/other/semiconductor/memory-card-price"},{skill:"arrays-data-api-semiconductor-price",file:"dxi-index",method:"GET",path:"/api/v1/other/semiconductor/dxi-index"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"short-interest",method:"GET",path:"/api/v1/stocks/short-interest"},{skill:"arrays-data-api-social-feeds",file:"x-handles",method:"POST",path:"/api/v1/social-feeds/x/handles"}];function _n(t,e){return Pn.find(n=>n.skill===t&&n.file===e)}s(_n,"getSkillEndpointMetadata");function At(t){return Pn.filter(e=>e.skill===t)}s(At,"listSkillEndpointMetadata");var Ke=class{constructor(e){this.client=e}client;static{s(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...Tn(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),o=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!o)throw new Error(`empty skills summary response for "${e.name}"`);let r=At(e.name);return{...o,...Tn(e.name),...r.length>0?{endpoint_metadata:r}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),o=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!o)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let r=_n(e.name,e.file);return{...o,...r?{metadata:r}:{}}}};function Tn(t){let e=At(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}s(Tn,"metadataSummaryForSkill");function Rn(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}s(Rn,"normalizePlaybookSkillSummary");function Sn(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new l("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}s(Sn,"parsePlaybookSkillId");var Xe=class{constructor(e){this.client=e}client;static{s(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(Rn)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=Sn(e),o=encodeURIComponent(n),r=encodeURIComponent(i),u=(await this.client._request("GET",`/api/v1/skills/${o}/${r}`)).data?.[0];if(!u)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...Rn(u),files:u.files??[]}}async file(e,n){let{username:i,name:o}=Sn(e),r=encodeURIComponent(i),a=encodeURIComponent(o),u=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${r}/${a}/files/${u}`)).data?.[0];if(!d)throw new l("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var ze=class{constructor(e){this.client=e}client;static{s(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var Je=class{constructor(e){this.client=e}client;static{s(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var Ze=class{constructor(e){this.client=e}client;static{s(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var et=class{constructor(e){this.client=e}client;static{s(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var tt=class{constructor(e){this.client=e}client;static{s(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var nt=class{constructor(e){this.client=e}client;static{s(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var it=class{constructor(e){this.client=e}client;static{s(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var rt=class{constructor(e){this.client=e}client;static{s(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:lr(e)})}};function lr(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}s(lr,"buildQuery");var st=class{constructor(e){this.client=e}client;static{s(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var ot=class{constructor(e){this.client=e}client;static{s(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var kn=50,En=40,dr=100,Un=50,An=200,pr=5,mr=["STOCK","ETF","CRYPTO"],hr=["USER","PERSON"],fr=new Set(["NOT_FOUND","FAILED_PRECONDITION"]),Fn={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},vn="id ticker name kind",vt="__typename id displayName followersCount viewerState { following } ... on PublicUser { username } ... on Person { slug xHandle }";function b(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(b,"record");function k(t){throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid ${t} response`,502)}s(k,"invalidResponse");function Ln(t){if(!b(t)||t.errors===void 0)return;if(!Array.isArray(t.errors))return k("GraphQL");if(t.errors.length===0)return;let e=t.errors,n=e.flatMap(r=>b(r)&&typeof r.message=="string"?[r.message]:[]),i=e.map(r=>b(r)&&b(r.extensions)?r.extensions.code:void 0);return{code:typeof i[0]=="string"&&Object.hasOwn(Fn,i[0])&&i.every(r=>r===i[0])?i[0]:"GRAPHQL_ERROR",message:n.join("; ")||"Request failed",errors:e}}s(Ln,"graphQLFailure");function On(t){throw new l(t.code,t.message,Fn[t.code]??502,{errors:t.errors})}s(On,"throwFailure");function at(t,e){let n=Ln(t);return n&&On(n),!b(t)||!b(t.data)?k(e):t.data}s(at,"responseData");function In(t,e){let n=at(t,e);return b(n.viewer)?n.viewer[e]:k(e)}s(In,"viewerField");function $(t,e){return typeof t!="string"||!t?k(e):t}s($,"requireString");function Cn(t,e){return!b(t)||typeof t.hasNextPage!="boolean"||t.endCursor!==null&&t.endCursor!==void 0&&typeof t.endCursor!="string"||t.hasNextPage&&!t.endCursor?k(e):{endCursor:typeof t.endCursor=="string"?t.endCursor:"",hasNextPage:t.hasNextPage}}s(Cn,"pageInfo");function xn(t,e){if(!b(t)||!b(t.viewerState))return k(e);let n=t.viewerState.following;if(typeof t.followersCount!="number"||typeof t.displayName!="string"||n!==null&&typeof n!="boolean")return k(e);let i={id:$(t.id,e),displayName:t.displayName,followersCount:t.followersCount,following:n??null};return t.__typename==="PublicUser"?{kind:"USER",...i,username:$(t.username,e)}:t.__typename==="Person"?t.xHandle!==null&&t.xHandle!==void 0&&typeof t.xHandle!="string"?k(e):{kind:"PERSON",...i,slug:$(t.slug,e),xHandle:t.xHandle??null}:k(e)}s(xn,"normalizeProfile");function It(t,e,n="first"){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>e)throw new Error(`${n} must be an integer between 1 and ${e}`);return t}}s(It,"boundedFirst");function qn(t){if(t!==void 0){if(typeof t!="string"||!t.trim()||t.length>4096)throw new Error("after must be a non-empty cursor of at most 4096 characters");return t}}s(qn,"optionalCursor");function Ct(t,e){if(!(t===void 0&&!e)){if(typeof t!="string"||!hr.includes(t))throw new Error("kind must be USER or PERSON");return t}}s(Ct,"profileKind");function Nn(t){if(t!==void 0){if(typeof t!="string"||!mr.includes(t))throw new Error("kind must be STOCK, ETF, or CRYPTO");return t}}s(Nn,"tickerKind");function gr(t){if(!b(t)||!Array.isArray(t.tickers))throw new Error("tickers must be a list of ticker symbols");let e=Nn(t.kind),n=[];for(let i of t.tickers){let o=typeof i=="string"?{ticker:i}:i;if(!b(o)||typeof o.ticker!="string")throw new Error("tickers must be symbols or {ticker, kind} specs");let r=o.ticker.trim().toUpperCase();if(!r||/\s/.test(r)||r.length>En)throw new Error(`ticker '${o.ticker}' must be a non-empty symbol of at most ${En} characters`);let a=Nn(o.kind)??e;n.some(u=>u.ticker===r&&u.kind===a)||n.push(a===void 0?{ticker:r}:{ticker:r,kind:a})}if(n.length===0||n.length>kn)throw new Error(`tickers must contain between 1 and ${kn} symbols`);return{tickers:n}}s(gr,"normalizeWatchlistTickersParams");function yr(t){if(!b(t))throw new Error("profile reference must be an object");let e=Ct(t.kind,!0);if(typeof t.id!="string"||!/^[1-9]\d{0,18}$/.test(t.id))throw new Error("id must be a positive decimal profile id");return{kind:e,id:t.id}}s(yr,"validateProfileRef");function br(t){if(!b(t)||typeof t.query!="string")throw new Error("query is required");let e=t.query.trim();if(!e||e.length>An)throw new Error(`query must be non-empty and at most ${An} characters`);return{query:e,kind:Ct(t.kind,!1),first:It(t.first,Un)}}s(br,"validateSearchProfilesParams");function Dn(t,e,n,i){return e===void 0?{ok:!1,unresolved:{input:t,code:n,message:i}}:{ok:!1,unresolved:{input:t,kind:e,code:n,message:n==="NOT_FOUND"?`no ${e} entity found for ticker ${t}; it may exist as another kind (retry with a different :kind suffix or none)`:i}}}s(Dn,"unresolvedTicker");var se=class{constructor(e){this.client=e}client;static{s(this,"FollowsResource")}async addToWatchlist(e){let{changed:n,unchanged:i,unresolved:o}=await this.changeWatchlist(e,"add");return{added:n,unchanged:i,unresolved:o}}async removeFromWatchlist(e){let{changed:n,unchanged:i,unresolved:o}=await this.changeWatchlist(e,"remove");return{removed:n,unchanged:i,unresolved:o}}async watchlist(e={}){let n=It(e.first,dr),i=qn(e.after);this.client._requireAuth();let o=await this.client._request("POST","/query",{body:{query:`query ToolkitWatchlist($input: MarketWatchlistConnectionInput) { viewer { marketWatchlist(input: $input) { totalCount edges { cursor followedAtMs node { ${vn} } } pageInfo { endCursor hasNextPage } } } }`,variables:{input:{first:n??20,after:i}}}}),r="viewer.marketWatchlist",a=In(o,"marketWatchlist");if(!b(a)||typeof a.totalCount!="number"||!Array.isArray(a.edges))return k(r);let u=a.edges.map(c=>!b(c)||!b(c.node)||typeof c.followedAtMs!="number"?k(r):{entityId:$(c.node.id,r),ticker:$(c.node.ticker,r),name:typeof c.node.name=="string"?c.node.name:"",kind:$(c.node.kind,r),addedAtMs:c.followedAtMs});return{totalCount:a.totalCount,tickers:u,pageInfo:Cn(a.pageInfo,r)}}async searchProfiles(e){let{query:n,kind:i,first:o}=br(e);this.client._requireAuth();let r=await this.client._request("POST","/query",{body:{query:`query ToolkitSearchProfiles($input: PublicProfileConnectionInput) { profiles(input: $input) { edges { node { ${vt} } } pageInfo { endCursor hasNextPage } } }`,variables:{input:{query:n,kind:i,first:o??10}}}});return this.profilesPage(at(r,"profiles").profiles,"profiles")}async profiles(e={}){let n=Ct(e.kind,!1),i=It(e.first,Un),o=qn(e.after);this.client._requireAuth();let r=await this.client._request("POST","/query",{body:{query:`query ToolkitFollowedProfiles($input: FollowingProfileConnectionInput) { viewer { followingProfiles(input: $input) { edges { node { ${vt} } } pageInfo { endCursor hasNextPage } } } }`,variables:{input:{kind:n,first:i??20,after:o}}}});return this.profilesPage(In(r,"followingProfiles"),"viewer.followingProfiles")}async followProfile(e){return this.changeProfile(e,"followProfile")}async unfollowProfile(e){return this.changeProfile(e,"unfollowProfile")}profilesPage(e,n){return!b(e)||!Array.isArray(e.edges)?k(n):{profiles:e.edges.map(i=>b(i)?xn(i.node,n):k(n)),pageInfo:Cn(e.pageInfo,n)}}async changeProfile(e,n){let i=yr(e);this.client._requireAuth();let o=await this.client._request("POST","/query",{body:{query:`mutation ToolkitChangeProfileFollow($input: PublicProfileRefInput!) { ${n}(input: $input) { following target { ${vt} } } }`,variables:{input:i}}}),r=at(o,n)[n];return!b(r)||typeof r.following!="boolean"?k(n):{following:r.following,profile:r.target===null||r.target===void 0?null:xn(r.target,n)}}async changeWatchlist(e,n){let{tickers:i}=gr(e);this.client._requireAuth();let o=await this.lookupTickers(i),r=[],a=[],u=[],c=new Map,d=[];for(let p of o){if(!p.ok){u.push(p.unresolved);continue}let y=c.get(p.ticker.entityId);if(y){y.push(p.ticker);continue}let w=n==="add"?!p.inWatchlist:p.inWatchlist,_=w?r:a;_.push(p.ticker),c.set(p.ticker.entityId,_),(w||n==="remove")&&d.push(p.ticker.entityId)}if(d.length>0){let p=n==="add"?"followTickers":"unfollowTickers",y=n==="add"?"FollowTickersInput":"UnfollowTickersInput",w=await this.client._request("POST","/query",{body:{query:`mutation ToolkitChangeWatchlist($input: ${y}!) { ${p}(input: $input) { entities { id } } }`,variables:{input:{entityIds:d}}}}),_=at(w,p)[p];if(!b(_)||!Array.isArray(_.entities))return k(p)}return{changed:r,unchanged:a,unresolved:u}}async lookupTickers(e){let n=new Array(e.length),i=0,o=s(async()=>{for(;i<e.length;){let r=i++,{ticker:a,kind:u}=e[r];n[r]=await this.lookupTicker(a,u)}},"worker");return await Promise.all(Array.from({length:Math.min(pr,e.length)},o)),n}async lookupTicker(e,n){let i=await this.client._request("POST","/query",{body:{query:`query ToolkitTickerLookup($input: MarketEntityLookupInput!) { market { entity(input: $input) { ${vn} viewerState { isFollowed } } } }`,variables:{input:{ticker:e,kind:n}}}}),o=Ln(i);if(o){if(fr.has(o.code))return Dn(e,n,o.code,o.message);On(o)}let r="market.entity";if(!b(i)||!b(i.data)||!b(i.data.market))return k(r);let a=i.data.market.entity;if(a==null)return Dn(e,n,"NOT_FOUND",`no entity found for ticker: ${e}`);if(!b(a))return k(r);let u=a.viewerState;if(u==null)throw new l("PERMISSION_DENIED","This credential cannot read the user's watchlist",403);return!b(u)||typeof u.isFollowed!="boolean"?k(r):{ok:!0,inWatchlist:u.isFollowed,ticker:{input:e,entityId:$(a.id,r),ticker:$(a.ticker,r),name:typeof a.name=="string"?a.name:"",kind:$(a.kind,r)}}}};var oe=class{constructor(e){this.client=e}client;static{s(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var ut=class{constructor(e){this.client=e}client;static{s(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:Gn(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:Gn(e)})}async getGroupChatHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-history",{query:{channel:e.channel,remote_chat_id:e.remote_chat_id,from_micros:String(e.from_micros),to_micros:String(e.to_micros)}})}};function Gn(t){return`{"session_id":${Mn(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${Mn(t.target_id)}}`}s(Gn,"mutationBody");function Mn(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}s(Mn,"idLiteral");var ct=class{constructor(e){this.client=e}client;static{s(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var lt=class{constructor(e){this.client=e}client;static{s(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:Pr(n.result)}}async getAllowance(e){this.client._requireAuth();let n=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return xt(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>xt(n)).filter(n=>n!==null)}}async createAllowance(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:wr(n.allowance)}}async revokeAllowance(e){return this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}}),{ok:!0}}};function xt(t){if(!t)return null;let e={id:t.id??"",consumer_uid:t.consumer_uid??t.consumerUid??"",playbook_id:t.playbook_id??t.playbookId??"",amount:t.amount??0,used:t.used??0,remaining:t.remaining??0},n=$n(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=$n(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),i!==void 0&&(e.updated_at_ms=i),e}s(xt,"normalizeAllowance");function wr(t){let e=xt(t);if(!e)throw new Error("allowance response missing allowance");return e}s(wr,"requireAllowance");function $n(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let o=Number(t);if(Number.isFinite(o))return o;let r=Date.parse(t);return Number.isNaN(r)?void 0:r}if(typeof t!="object")return;let e=t,n=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,i=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}s($n,"timestampMs");function Pr(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}s(Pr,"parseResultPayload");var _r=`
93
93
  query ToolkitCreditWallet {
94
94
  viewer {
95
95
  creditWallet {
@@ -99,7 +99,7 @@ query ToolkitCreditWallet {
99
99
  }
100
100
  }
101
101
  }
102
- `.trim(),Qi=`
102
+ `.trim(),Tr=`
103
103
  query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
104
104
  viewer {
105
105
  creditWallet {
@@ -131,7 +131,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
131
131
  }
132
132
  }
133
133
  }
134
- `.trim();function Vi(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}s(Vi,"graphQLErrorMessage");var ot=class{constructor(e){this.client=e}client;static{s(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(Bi)).viewer?.creditWallet;if(!n)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return n}async items(e){this.client._requireAuth();let i=(await this.graphql(Qi,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return i}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Vi(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var Hi=["Q1","Q2","Q3","Q4"],Yi=["latest-completed","next-confirmed"],Wi=`
134
+ `.trim();function Rr(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}s(Rr,"graphQLErrorMessage");var dt=class{constructor(e){this.client=e}client;static{s(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(_r)).viewer?.creditWallet;if(!n)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return n}async items(e){this.client._requireAuth();let i=(await this.graphql(Tr,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return i}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Rr(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var Sr=["Q1","Q2","Q3","Q4"],kr=["latest-completed","next-confirmed"],Er=`
135
135
  query ToolkitCompanyNarrative($ticker: String!) {
136
136
  market {
137
137
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -157,7 +157,7 @@ query ToolkitCompanyNarrative($ticker: String!) {
157
157
  }
158
158
  }
159
159
  }
160
- `.trim(),Ki=`
160
+ `.trim(),Ar=`
161
161
  query ToolkitCompanyEarningsCatalog($ticker: String!) {
162
162
  market {
163
163
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -188,7 +188,7 @@ query ToolkitCompanyEarningsCatalog($ticker: String!) {
188
188
  }
189
189
  }
190
190
  }
191
- `.trim(),Xi=`
191
+ `.trim(),vr=`
192
192
  query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
193
193
  market {
194
194
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -258,7 +258,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
258
258
  }
259
259
  }
260
260
  }
261
- `.trim();function zi(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}s(zi,"graphQLErrorMessage");function St(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}s(St,"normalizedTicker");var ne=class{constructor(e){this.client=e}client;static{s(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=St(e),o=(await this.graphql(Wi,{ticker:n})).market?.entity;if(!o)throw this.notFound(n);return{ticker:o.ticker,current:o.companyInsight,history:o.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let n=St(e),o=(await this.graphql(Ki,{ticker:n})).market?.entity;if(!o)throw this.notFound(n);if(!o.earningsPeriods)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${o.ticker}`,404,{ticker:o.ticker});return o.earningsPeriods}async earnings(e){this.client._requireAuth();let n=St(e.ticker),i=e.event,o=e.fiscalYear,r=e.fiscalQuarter;if(i!==void 0&&(o!==void 0||r!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(o===void 0!=(r===void 0))throw new l("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(i!==void 0&&!Yi.includes(i))throw new l("INVALID_ARGUMENT",`Unknown earnings event selector: ${i}`,400);if(o!==void 0&&(!Number.isInteger(o)||o<1900||o>9999))throw new l("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(r!==void 0&&!Hi.includes(r))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let u,c;if(o!==void 0&&r!==void 0)u=o,c=r;else{let g=i??"latest-completed",v=await this.earningsPeriods(n),F=this.selectPeriod(v,g,n);u=F.fiscalYear,c=F.fiscalQuarter}let y=(await this.graphql(Xi,{ticker:n,input:{fiscalYear:u,fiscalQuarter:c}})).market?.entity;if(!y)throw this.notFound(n);if(!y.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${y.ticker} FY${u} ${c}`,404,{ticker:y.ticker,fiscalYear:u,fiscalQuarter:c});return{ticker:y.ticker,...y.earnings}}selectPeriod(e,n,i){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let o=e.periods.filter(r=>r.status==="UPCOMING").sort((r,a)=>r.earningsDate.localeCompare(a.earningsDate));if(o.length>0)return o[0]}throw new l("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${n} earnings event is available for ${i}`,404,{ticker:i,event:n})}notFound(e){return new l("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",zi(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var at=`
261
+ `.trim();function Ir(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}s(Ir,"graphQLErrorMessage");function qt(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}s(qt,"normalizedTicker");var ae=class{constructor(e){this.client=e}client;static{s(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=qt(e),o=(await this.graphql(Er,{ticker:n})).market?.entity;if(!o)throw this.notFound(n);return{ticker:o.ticker,current:o.companyInsight,history:o.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let n=qt(e),o=(await this.graphql(Ar,{ticker:n})).market?.entity;if(!o)throw this.notFound(n);if(!o.earningsPeriods)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${o.ticker}`,404,{ticker:o.ticker});return o.earningsPeriods}async earnings(e){this.client._requireAuth();let n=qt(e.ticker),i=e.event,o=e.fiscalYear,r=e.fiscalQuarter;if(i!==void 0&&(o!==void 0||r!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(o===void 0!=(r===void 0))throw new l("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(i!==void 0&&!kr.includes(i))throw new l("INVALID_ARGUMENT",`Unknown earnings event selector: ${i}`,400);if(o!==void 0&&(!Number.isInteger(o)||o<1900||o>9999))throw new l("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(r!==void 0&&!Sr.includes(r))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let u,c;if(o!==void 0&&r!==void 0)u=o,c=r;else{let y=i??"latest-completed",w=await this.earningsPeriods(n),_=this.selectPeriod(w,y,n);u=_.fiscalYear,c=_.fiscalQuarter}let p=(await this.graphql(vr,{ticker:n,input:{fiscalYear:u,fiscalQuarter:c}})).market?.entity;if(!p)throw this.notFound(n);if(!p.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${p.ticker} FY${u} ${c}`,404,{ticker:p.ticker,fiscalYear:u,fiscalQuarter:c});return{ticker:p.ticker,...p.earnings}}selectPeriod(e,n,i){if(n==="latest-completed"){let o=e.periods.filter(r=>r.status==="COMPLETED").sort((r,a)=>a.earningsDate.localeCompare(r.earningsDate));if(o.length>0)return o[0]}else{let o=e.periods.filter(r=>r.status==="UPCOMING").sort((r,a)=>r.earningsDate.localeCompare(a.earningsDate));if(o.length>0)return o[0]}throw new l("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${n} earnings event is available for ${i}`,404,{ticker:i,event:n})}notFound(e){return new l("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Ir(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var pt=`
262
262
  id
263
263
  name
264
264
  rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
@@ -271,45 +271,45 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
271
271
  nextFireAtMs
272
272
  createdAtMs
273
273
  updatedAtMs
274
- `,Ji=`
274
+ `,Cr=`
275
275
  query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
276
276
  viewer { channel(id: $channelId) {
277
277
  schedules(input: { first: 64, after: $after }) {
278
- edges { node { channel { id } ${at} } }
278
+ edges { node { channel { id } ${pt} } }
279
279
  pageInfo { hasNextPage endCursor }
280
280
  }
281
281
  } }
282
- }`.trim(),Zi=`
282
+ }`.trim(),xr=`
283
283
  mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
284
284
  updateChannelSchedule(input: $input) {
285
- schedule { channel { id } ${at} }
285
+ schedule { channel { id } ${pt} }
286
286
  deleted
287
287
  }
288
- }`.trim(),es=`
288
+ }`.trim(),qr=`
289
289
  query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
290
290
  viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
291
- edges { node { ${at} } }
291
+ edges { node { ${pt} } }
292
292
  pageInfo { hasNextPage endCursor }
293
293
  } }
294
- }`.trim(),ts=`
294
+ }`.trim(),Nr=`
295
295
  mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
296
296
  updateSessionSchedule(input: $input) {
297
- schedule { ${at} }
297
+ schedule { ${pt} }
298
298
  deleted
299
299
  }
300
- }`.trim(),ns=`
300
+ }`.trim(),Dr=`
301
301
  query ToolkitAgentChannel {
302
302
  viewer { channels { id kind } }
303
- }`.trim(),is=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,ss=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,rs=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,os=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,as={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},ie=class{constructor(e){this.client=e}client;static{s(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Et(e),i="inboxPath"in n,o=[],r=null,a=new Set;for(;;){let u=await this.graphql(i?es:Ji,{...n,after:r}),c=i?u.viewer?.sessionSchedules:u.viewer?.channel?.schedules;if(!c?.edges)throw _n();for(let y of c.edges){if(!y?.node)throw R();o.push(kt(y.node))}if(c.pageInfo?.hasNextPage!==!0)return o;let d=c.pageInfo.endCursor;if(!d||a.has(d))throw R();a.add(d),r=d}}async put(e){this.client._requireAuth();let n={...Et(e),name:Pn(e.name),definition:{...us(e.rule,e.bounds),message:{text:ps(e.text)}}},i=(await this.update(n))?.schedule;if(!i)throw R();return kt(i)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.update({...bn(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw R()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(ns)).viewer?.channels?.find(i=>i.kind==="AGENT")?.id;if(!n)throw _n();return n}async manage(e,n){this.client._requireAuth();let i=(await this.update({...bn(n),lifecycle:e}))?.schedule;if(!i)throw R();return kt(i)}async update(e){let n="inboxPath"in e,i=await this.graphql(n?ts:Zi,{input:e});return n?i.updateSessionSchedule:i.updateChannelSchedule}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors?.length){let o=i.errors.map(d=>d.extensions?.code),a=new Set(o).size===1&&typeof o[0]=="string"?o[0]:void 0,u=a?as[a]:void 0,c=a!==void 0&&u!==void 0?a:"GRAPHQL_ERROR";throw new l(c,i.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",u??502,{errors:i.errors})}if(!i.data)throw R();return i.data}};function us(t,e){let n=cs(e);switch(t.kind){case"after":if(n)throw _("after does not accept recurring bounds");let i=Date.now()+wn(t.duration,1),o=Math.ceil(i/1e3)*1e3;if(!Number.isSafeInteger(o)||Number.isNaN(new Date(o).getTime()))throw _("after is out of range");return{rule:{kind:"AT",atMs:o}};case"at":if(n)throw _("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:At(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:ms(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw _("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}s(us,"ruleInput");function cs(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=At(t.startsAt)),t.until!==void 0&&(e.untilMs=At(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw _("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}s(cs,"boundsInput");function kt(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw R();let i=t.bounds??{},o=t.message??{},r={name:t.name,rule:ls(t.rule),bounds:{...i.startsAtMs!=null?{startsAt:V(i.startsAtMs,!0)}:{},...i.untilMs!=null?{until:V(i.untilMs,!0)}:{},...i.maxOccurrences!=null?{maxOccurrences:vt(i.maxOccurrences,"maxOccurrences")}:{}},text:o.text??"",status:n,occurrencesUsed:vt(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:V(t.nextFireAtMs,!0)}:{},createdAt:V(t.createdAtMs),updatedAt:V(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw R();let u={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!u)throw R();r.failure={code:u,...t.failureAtMs!=null?{at:V(t.failureAtMs)}:{}}}return r}s(kt,"fromWireSchedule");function ls(t){switch(t.kind){case"AT":if(t.atMs==null)throw R();return{kind:"at",timestamp:V(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw R();return{kind:"every",interval:`PT${vt(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw R();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw R()}s(ls,"fromWireRule");function bn(t){return{...Et(t),name:Pn(t.name)}}s(bn,"managementInput");function Et(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw _("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:ds(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?Tn(e):void 0;if(typeof e!="string"||n===void 0||n>2048||!e.startsWith("/")||e.includes("\0")||e.slice(1).split("/").some(o=>o===""||o==="."||o===".."))throw _("inboxPath must be a canonical absolute ALFS Inbox path");let i=e.endsWith(".inbox.jsonl")?e.slice(0,-12)+".jsonl":e.endsWith(".inbox")&&!e.endsWith(".jsonl.inbox")?e.slice(0,-6):void 0;if(i===void 0||/\.inbox(?:\.jsonl)?$/.test(i)||/\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(i)||i.endsWith("/.jsonl"))throw _("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}s(Et,"targetInput");function ds(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw _("numeric channelId must be a positive safe integer; use a decimal string for larger IDs");let e=String(t);if(!/^[1-9]\d*$/.test(e))throw _("channelId must be a positive integer");return e}s(ds,"channelID");function Pn(t){if(!is.test(t))throw _("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}s(Pn,"requireName");function ps(t){let e=Tn(t);if(e===void 0||!t.trim()||e>16*1024)throw _("text must be 1..16384 UTF-8 bytes");return t}s(ps,"requireText");function ms(t){let e=wn(t,60);if(e%1e3!==0)throw _("duration must resolve to whole seconds");return e/1e3}s(ms,"durationSeconds");function wn(t,e){let n=os.exec(t);if(!n||n.slice(1,5).every(d=>d===void 0)||t.includes("T")&&n.slice(2,5).every(d=>d===void 0))throw _("duration must be a positive ISO 8601 day/time duration");let[i,o,r,a]=n.slice(1,5).map(d=>BigInt(d??"0")),u=((i*24n+o)*60n+r)*60n+a;if(u<BigInt(e))throw _(`duration must be at least ${e} whole seconds`);let c=Number(u*1000n);if(!Number.isSafeInteger(c))throw _("duration is out of range");return c}s(wn,"durationMilliseconds");function At(t,e=!1){let n=(e?rs:ss).exec(t);if(!n)throw _("timestamp must be RFC3339 with a timezone");let[i,o,r,a,u,c]=n.slice(1,7).map(Number),d=Number(n[8]??0),y=Number(n[9]??0),g=new Date(Date.UTC(i,o,0)).getUTCDate(),v=Date.parse(t);if(!Number.isFinite(v)||i<1||i>9999||o<1||o>12||r<1||r>g||a>23||u>59||c>59||d>23||y>59)throw _("timestamp must be RFC3339 with a timezone");return v}s(At,"timestampMilliseconds");function V(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw R();let n=new Date(t);if(Number.isNaN(n.getTime()))throw R();return n.toISOString()}s(V,"timestampString");function vt(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw _(`${e} exceeds JavaScript safe integer range`);return n}s(vt,"safeInteger");function _(t){return new l("INVALID_ARGUMENT",t,400)}s(_,"invalid");function Tn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}s(Tn,"utf8Size");function _n(){return new l("NOT_FOUND","channel schedule target not found",404)}s(_n,"scheduleNotFound");function R(){return new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}s(R,"scheduleEmptyResponse");var hs={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},fs=`
303
+ }`.trim(),Ur=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Fr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Lr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,Or=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,Gr={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},ue=class{constructor(e){this.client=e}client;static{s(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Dt(e),i="inboxPath"in n,o=[],r=null,a=new Set;for(;;){let u=await this.graphql(i?qr:Cr,{...n,after:r}),c=i?u.viewer?.sessionSchedules:u.viewer?.channel?.schedules;if(!c?.edges)throw Bn();for(let p of c.edges){if(!p?.node)throw v();o.push(Nt(p.node))}if(c.pageInfo?.hasNextPage!==!0)return o;let d=c.pageInfo.endCursor;if(!d||a.has(d))throw v();a.add(d),r=d}}async put(e){this.client._requireAuth();let n={...Dt(e),name:Qn(e.name),definition:{...Mr(e.rule,e.bounds),message:{text:Qr(e.text)}}},i=(await this.update(n))?.schedule;if(!i)throw v();return Nt(i)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.update({...jn(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw v()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Dr)).viewer?.channels?.find(i=>i.kind==="AGENT")?.id;if(!n)throw Bn();return n}async manage(e,n){this.client._requireAuth();let i=(await this.update({...jn(n),lifecycle:e}))?.schedule;if(!i)throw v();return Nt(i)}async update(e){let n="inboxPath"in e,i=await this.graphql(n?Nr:xr,{input:e});return n?i.updateSessionSchedule:i.updateChannelSchedule}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors?.length){let o=i.errors.map(d=>d.extensions?.code),a=new Set(o).size===1&&typeof o[0]=="string"?o[0]:void 0,u=a?Gr[a]:void 0,c=a!==void 0&&u!==void 0?a:"GRAPHQL_ERROR";throw new l(c,i.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",u??502,{errors:i.errors})}if(!i.data)throw v();return i.data}};function Mr(t,e){let n=$r(e);switch(t.kind){case"after":if(n)throw T("after does not accept recurring bounds");let i=Date.now()+Wn(t.duration,1),o=Math.ceil(i/1e3)*1e3;if(!Number.isSafeInteger(o)||Number.isNaN(new Date(o).getTime()))throw T("after is out of range");return{rule:{kind:"AT",atMs:o}};case"at":if(n)throw T("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:Ut(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Wr(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw T("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}s(Mr,"ruleInput");function $r(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=Ut(t.startsAt)),t.until!==void 0&&(e.untilMs=Ut(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw T("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}s($r,"boundsInput");function Nt(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw v();let i=t.bounds??{},o=t.message??{},r={name:t.name,rule:jr(t.rule),bounds:{...i.startsAtMs!=null?{startsAt:K(i.startsAtMs,!0)}:{},...i.untilMs!=null?{until:K(i.untilMs,!0)}:{},...i.maxOccurrences!=null?{maxOccurrences:Ft(i.maxOccurrences,"maxOccurrences")}:{}},text:o.text??"",status:n,occurrencesUsed:Ft(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:K(t.nextFireAtMs,!0)}:{},createdAt:K(t.createdAtMs),updatedAt:K(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw v();let u={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!u)throw v();r.failure={code:u,...t.failureAtMs!=null?{at:K(t.failureAtMs)}:{}}}return r}s(Nt,"fromWireSchedule");function jr(t){switch(t.kind){case"AT":if(t.atMs==null)throw v();return{kind:"at",timestamp:K(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw v();return{kind:"every",interval:`PT${Ft(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw v();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw v()}s(jr,"fromWireRule");function jn(t){return{...Dt(t),name:Qn(t.name)}}s(jn,"managementInput");function Dt(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw T("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:Br(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?Vn(e):void 0;if(typeof e!="string"||n===void 0||n>2048||!e.startsWith("/")||e.includes("\0")||e.slice(1).split("/").some(o=>o===""||o==="."||o===".."))throw T("inboxPath must be a canonical absolute ALFS Inbox path");let i=e.endsWith(".inbox.jsonl")?e.slice(0,-12)+".jsonl":e.endsWith(".inbox")&&!e.endsWith(".jsonl.inbox")?e.slice(0,-6):void 0;if(i===void 0||/\.inbox(?:\.jsonl)?$/.test(i)||/\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(i)||i.endsWith("/.jsonl"))throw T("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}s(Dt,"targetInput");function Br(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw T("numeric channelId must be a positive safe integer; use a decimal string for larger IDs");let e=String(t);if(!/^[1-9]\d*$/.test(e))throw T("channelId must be a positive integer");return e}s(Br,"channelID");function Qn(t){if(!Ur.test(t))throw T("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}s(Qn,"requireName");function Qr(t){let e=Vn(t);if(e===void 0||!t.trim()||e>16*1024)throw T("text must be 1..16384 UTF-8 bytes");return t}s(Qr,"requireText");function Wr(t){let e=Wn(t,60);if(e%1e3!==0)throw T("duration must resolve to whole seconds");return e/1e3}s(Wr,"durationSeconds");function Wn(t,e){let n=Or.exec(t);if(!n||n.slice(1,5).every(d=>d===void 0)||t.includes("T")&&n.slice(2,5).every(d=>d===void 0))throw T("duration must be a positive ISO 8601 day/time duration");let[i,o,r,a]=n.slice(1,5).map(d=>BigInt(d??"0")),u=((i*24n+o)*60n+r)*60n+a;if(u<BigInt(e))throw T(`duration must be at least ${e} whole seconds`);let c=Number(u*1000n);if(!Number.isSafeInteger(c))throw T("duration is out of range");return c}s(Wn,"durationMilliseconds");function Ut(t,e=!1){let n=(e?Lr:Fr).exec(t);if(!n)throw T("timestamp must be RFC3339 with a timezone");let[i,o,r,a,u,c]=n.slice(1,7).map(Number),d=Number(n[8]??0),p=Number(n[9]??0),y=new Date(Date.UTC(i,o,0)).getUTCDate(),w=Date.parse(t);if(!Number.isFinite(w)||i<1||i>9999||o<1||o>12||r<1||r>y||a>23||u>59||c>59||d>23||p>59)throw T("timestamp must be RFC3339 with a timezone");return w}s(Ut,"timestampMilliseconds");function K(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw v();let n=new Date(t);if(Number.isNaN(n.getTime()))throw v();return n.toISOString()}s(K,"timestampString");function Ft(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw T(`${e} exceeds JavaScript safe integer range`);return n}s(Ft,"safeInteger");function T(t){return new l("INVALID_ARGUMENT",t,400)}s(T,"invalid");function Vn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}s(Vn,"utf8Size");function Bn(){return new l("NOT_FOUND","channel schedule target not found",404)}s(Bn,"scheduleNotFound");function v(){return new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}s(v,"scheduleEmptyResponse");var Vr={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},Hr=`
304
304
  mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
305
305
  updateStewardDelivery(input: $input) { delivery { deliveryId state } }
306
- }`.trim(),ys=`
306
+ }`.trim(),Yr=`
307
307
  mutation ToolkitStewardForward($input: UpdateStewardDeliveryInput!) {
308
308
  updateStewardDelivery(input: $input) { delivery { deliveryId state channelMessageId } }
309
- }`.trim(),gs=`
309
+ }`.trim(),Kr=`
310
310
  mutation ToolkitStewardSend($input: PostStewardMessageInput!) {
311
311
  postStewardMessage(input: $input) { message { channelMessageId requestId } }
312
- }`.trim(),bs=`
312
+ }`.trim(),Xr=`
313
313
  query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInput) {
314
314
  viewer {
315
315
  stewardDigestPending(inboxPath: $inboxPath, input: $input) {
@@ -322,50 +322,70 @@ query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInp
322
322
  windowUntilMs
323
323
  }
324
324
  }
325
- }`.trim(),_s=`
325
+ }`.trim(),zr=`
326
326
  mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
327
327
  completeStewardBrief(input: $input) { ok }
328
- }`.trim(),Ps=new Set(["immediate","digest","suppress"]),ws=/^[1-9][0-9]{0,18}$/;function C(t){return new l("INVALID_ARGUMENT",t,400)}s(C,"invalid");function Se(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw C("steward commands require the steward Session Inbox path");return t.inboxPath}s(Se,"requireInboxPath");function It(t,e="delivery id"){if(!ws.test(t))throw C(`${e} must be a positive integer`);return t}s(It,"requireDeliveryId");function Sn(t){let e=new Set;for(let n of t){if(It(n),e.has(n))throw C(`duplicate delivery id ${n}`);e.add(n)}return[...e]}s(Sn,"normalizeDeliveryIds");function Ts(t){if(t.length===0)throw C("at least one delivery id is required");return Sn(t)}s(Ts,"requireDeliveryIds");function Rs(t){if(!Ps.has(t))throw C("decision must be one of immediate, digest, suppress");return t}s(Rs,"requireDecision");function Ss(){let t=globalThis.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();let e=new Uint8Array(16);if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let i=0;i<e.length;i+=1)e[i]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}s(Ss,"generateRequestId");function Rn(t){if(t===void 0)return Ss();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw C("request id must be a UUID");return t}s(Rn,"requireRequestId");function j(){return new l("EMPTY_RESPONSE","steward response was empty",502)}s(j,"emptyResponse");var se=class{constructor(e){this.client=e}client;static{s(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw C("a decision reason is required");let o=(await this.graphql(fs,{input:{inboxPath:Se(e),deliveryId:It(e.deliveryId),decision:{decision:Rs(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!o)throw j();return{state:o.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(ys,{input:{inboxPath:Se(e),deliveryId:It(e.deliveryId),forward:{requestId:Rn(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw j();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw C("a message body is required");let i=(await this.graphql(gs,{input:{inboxPath:Se(e),requestId:Rn(e.requestId),body:e.body,deliveryIds:Sn(e.deliveryIds??[])}})).postStewardMessage?.message;if(!i)throw j();return i}async pending(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw C("first must be an integer between 1 and 100");let i={first:n};if(e.after!==void 0&&e.after!=="")i.after=e.after;else{for(let[y,g]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(g!==void 0&&(!Number.isSafeInteger(g)||g<=0))throw C(`${y} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw C("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let r=(await this.graphql(bs,{inboxPath:Se(e),input:i})).viewer?.stewardDigestPending;if(!r||!Array.isArray(r.edges))throw j();let a=r.windowSinceMs??0,u=r.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u)||a<=0||u<=a)throw j();let c=r.edges.map(y=>y.node),d=r.pageInfo?.hasNextPage===!0&&r.pageInfo.endCursor?r.pageInfo.endCursor:null;return{items:c,nextCursor:d,windowSinceMs:a,windowUntilMs:u}}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw C("a digest run id is required");if((await this.graphql(_s,{input:{inboxPath:Se(e),deliveryIds:Ts(e.deliveryIds),digestRunId:n}})).completeStewardBrief?.ok!==!0)throw j();return{ok:!0}}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i||typeof i!="object")throw j();if(i.errors?.length){let o=i.errors.map(u=>u.extensions?.code),r=new Set(o).size===1&&typeof o[0]=="string"?o[0]:void 0,a=r?hs[r]:void 0;throw new l(r!==void 0&&a!==void 0?r:"GRAPHQL_ERROR",i.errors.map(u=>u.message).filter(u=>typeof u=="string").join("; ")||"GraphQL request failed",a??502,{errors:i.errors})}if(!i.data)throw j();return i.data}};function B(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(B,"isRecord");function P(t){return typeof t=="string"&&t.trim()!==""?t:void 0}s(P,"stringValue");function ut(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}s(ut,"numberValue");function lt(t){return t===void 0?void 0:t.trim().toUpperCase()}s(lt,"upper");function En(t){return t.split("_")}s(En,"pairParts");function ks(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":En(e)[1]?.toLowerCase()??""}s(ks,"inferInstrumentType");function Es(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}s(Es,"inferUnderlyingType");function kn(t,e){let n=P(t.trading_pair)??P(t.tradingPair)??P(t.symbol);if(n===void 0)return;let i=P(t.type),o=En(n),r=P(t.base)??e??(o.length>=4?o.slice(2,-1).join("_"):o.length===3?o[2]:n),a=P(t.market)??P(t.exchange)??o[0]??"",u=P(t.quote)??o[o.length-1]??"",c=P(t.instrument_type)??P(t.instrumentType)??ks(i,n),d=P(t.underlying_type)??P(t.underlyingType)??Es(i);return{symbol:r,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:u,...i===void 0?{}:{type:i},...P(t.description)===void 0?{}:{description:P(t.description)},...ut(t.fee_rate)===void 0?ut(t.feeRate)===void 0?{}:{feeRate:ut(t.feeRate)}:{feeRate:ut(t.fee_rate)},...P(t.symbol_icon_url)===void 0?P(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:P(t.symbolIconUrl)}:{symbolIconUrl:P(t.symbol_icon_url)}}}s(kn,"normalizeCandidate");function As(t){if(!B(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(o=>B(o)?[kn(o)].filter(r=>r!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let o of n){if(!B(o))continue;let r=P(o.symbol),a=o.trading_pairs;if(Array.isArray(a)){for(let u of a)if(!(!B(u)||!Array.isArray(u.pairs)))for(let c of u.pairs){if(!B(c))continue;let d=kn({...c,instrument_type:c.instrument_type??u.instrument_type},r);d!==void 0&&i.push(d)}}}return i}s(As,"flattenResponse");function vs(t,e){let n=e.trim();return t.tradingPair===n?!0:lt(t.symbol)===lt(n)}s(vs,"matchesQuery");function ct(t,e){return e===void 0||lt(t)===lt(e)}s(ct,"matchesFilter");function Is(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}s(Is,"dedupe");function Cs(t){let e=B(t)?t:{};return{market:typeof e.market=="string"?e.market:void 0,instrumentType:typeof e.instrumentType=="string"?e.instrumentType:void 0,underlyingType:typeof e.underlyingType=="string"?e.underlyingType:void 0,quote:typeof e.quote=="string"?e.quote:void 0}}s(Cs,"resolveFilters");function xs(t,e){let n=t.split("_"),i=n[0],o=n[1],r=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!o||!r||!a?{symbol:t,...e}:{symbol:r,market:e.market??i,instrumentType:e.instrumentType??o,underlyingType:e.underlyingType,quote:e.quote??a}}s(xs,"pairSearchParams");var re=class{constructor(e){this.client=e}client;static{s(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=B(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new l("INVALID_ARGUMENT","symbol is required",400);let o=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),r=Is(As(o)).filter(u=>vs(u,i)).filter(u=>ct(u.market,e.market)).filter(u=>ct(u.instrumentType,e.instrumentType)).filter(u=>ct(u.underlyingType,e.underlyingType)).filter(u=>ct(u.quote,e.quote)),a=e.limit;return a!==void 0&&r.length>a?{query:i,candidates:r.slice(0,a),truncated:!0}:{query:i,candidates:r}}async resolve(e){let n=B(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,o=Cs(e),r=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...o}:xs(i,o),a=await this.search(r),u=i===void 0?a.candidates:a.candidates.filter(c=>c.tradingPair===i);if(u.length!==1)throw new l(u.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",u.length===0?`no canonical trading pair matched "${i??r.symbol}"`:`multiple canonical trading pairs matched "${r.symbol}"`,u.length===0?404:409,{query:i??r.symbol,candidateCount:u.length,candidates:u.slice(0,50),...u.length>50?{truncated:!0}:{}});return u[0]}};var In="pageInfo { endCursor hasNextPage }",Cn="__typename id slug displayName bio",qs="__typename id username displayName bio",xn="__typename id ticker name kind assetClass venue { id name }",qn=`theses(input: $input) {
329
- edges { cursor node { id latestRelease { thesisPublication { ${z} } } } }
330
- ${In}
331
- }`,Ns=`query ToolkitPersonTheses($slug: String!, $input: ProfileThesisConnectionInput) {
332
- scope: person(slug: $slug) { ${Cn} ${qn} }
333
- }`,Ds=`query ToolkitUserTheses($username: String!, $input: ProfileThesisConnectionInput) {
334
- scope: publicUser(username: $username) { ${qs} ${qn} }
335
- }`,Us=`query ToolkitEntityTheses($id: ID!, $input: EntityThesisConnectionInput) {
336
- market { scope: entity(input: { id: $id }) { ${xn}
337
- theses(input: $input) { edges { cursor node { ${z} } } ${In} }
328
+ }`.trim(),Yn=`
329
+ digestRunId state scheduleId scheduleVersion occurrenceIndex
330
+ windowSinceMs windowUntilMs scanCompletedAtMs bodySha256 coverageSha256
331
+ channelMessageId attempts lastError startedAtMs completedAtMs sendUncertainAtMs
332
+ `.trim(),Jr=`
333
+ query ToolkitStewardDigestRun($inboxPath: String!, $digestRunId: String!) {
334
+ viewer { stewardDigestRun(inboxPath: $inboxPath, digestRunId: $digestRunId) { ${Yn} } }
335
+ }`.trim(),Zr=`
336
+ query ToolkitStewardDigestRunPending($inboxPath: String!, $digestRunId: String!, $input: StewardDigestRunPendingInput) {
337
+ viewer {
338
+ stewardDigestRunPending(inboxPath: $inboxPath, digestRunId: $digestRunId, input: $input) {
339
+ edges {
340
+ node { deliveryId feedEntryId source { kind id } decisionReason consumedAtMs alertSnapshot }
341
+ }
342
+ pageInfo { hasNextPage endCursor }
343
+ }
344
+ }
345
+ }`.trim(),es=`
346
+ mutation ToolkitStewardPublishDailyBrief($input: PublishStewardDailyBriefInput!) {
347
+ publishStewardDailyBrief(input: $input) { run { ${Yn} } }
348
+ }`.trim(),ts=new Set(["immediate","digest","suppress"]),ns=/^[1-9][0-9]{0,18}$/,is=100,rs=1e4,ss=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,os=3,as=new Set(["NETWORK_ERROR","NETWORK_TIMEOUT","UNAVAILABLE","DEADLINE_EXCEEDED"]),us=new Set([502,503,504]);function I(t){return new l("INVALID_ARGUMENT",t,400)}s(I,"invalid");function V(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw I("steward commands require the steward Session Inbox path");return t.inboxPath}s(V,"requireInboxPath");function Ot(t,e="delivery id"){if(!ns.test(t))throw I(`${e} must be a positive integer`);return t}s(Ot,"requireDeliveryId");function Gt(t){let e=new Set;for(let n of t){if(Ot(n),e.has(n))throw I(`duplicate delivery id ${n}`);e.add(n)}return[...e]}s(Gt,"normalizeDeliveryIds");function cs(t){if(t.length===0)throw I("at least one delivery id is required");return Gt(t)}s(cs,"requireDeliveryIds");function ls(t){if(!ts.has(t))throw I("decision must be one of immediate, digest, suppress");return t}s(ls,"requireDecision");function ds(){let t=globalThis.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();let e=new Uint8Array(16);if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let i=0;i<e.length;i+=1)e[i]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}s(ds,"generateRequestId");function Hn(t){if(t===void 0)return ds();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw I("request id must be a UUID");return t}s(Hn,"requireRequestId");function Lt(t){if(!ss.test(t))throw I("digest run id must be a UUID");return t.toLowerCase()}s(Lt,"requireDigestRunId");function ps(t){return t instanceof l&&(as.has(t.code)||us.has(t.status))}s(ps,"isTransientStewardError");function E(){return new l("EMPTY_RESPONSE","steward response was empty",502)}s(E,"emptyResponse");var ce=class{constructor(e){this.client=e}client;static{s(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw I("a decision reason is required");let o=(await this.graphql(Hr,{input:{inboxPath:V(e),deliveryId:Ot(e.deliveryId),decision:{decision:ls(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!o)throw E();return{state:o.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(Yr,{input:{inboxPath:V(e),deliveryId:Ot(e.deliveryId),forward:{requestId:Hn(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw E();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw I("a message body is required");let i=(await this.graphql(Kr,{input:{inboxPath:V(e),requestId:Hn(e.requestId),body:e.body,deliveryIds:Gt(e.deliveryIds??[])}})).postStewardMessage?.message;if(!i)throw E();return i}async pending(e){if(e.after!==void 0)return this.pendingPage(e);let n=[],i=new Set,o=new Set,r,a,u;do{let c=await this.pendingPageWithRetry({...e,after:r,sinceMs:r===void 0?e.sinceMs:void 0,untilMs:r===void 0?e.untilMs:void 0});if(a===void 0)a=c.windowSinceMs,u=c.windowUntilMs;else if(c.windowSinceMs!==a||c.windowUntilMs!==u)throw new l("ABORTED","steward pending window changed during pagination",409);for(let d of c.items)i.has(d.deliveryId)||(i.add(d.deliveryId),n.push(d));if(r=c.nextCursor??void 0,r!==void 0){if(o.has(r))throw new l("INTERNAL","steward pending pagination loop detected",500);o.add(r)}}while(r!==void 0);if(a===void 0||u===void 0)throw E();return{items:n,windowSinceMs:a,windowUntilMs:u}}async pendingPage(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw I("first must be an integer between 1 and 100");let i={first:n};if(e.after!==void 0&&e.after!=="")i.after=e.after;else{for(let[w,_]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(_!==void 0&&(!Number.isSafeInteger(_)||_<=0))throw I(`${w} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw I("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let r=(await this.graphql(Xr,{inboxPath:V(e),input:i})).viewer?.stewardDigestPending;if(!r||!Array.isArray(r.edges))throw E();let a=r.windowSinceMs??0,u=r.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u)||a<=0||u<=a)throw E();let c=r.edges.map(w=>w.node),d=r.pageInfo;if(!d||typeof d.hasNextPage!="boolean")throw E();let p=d.endCursor;if(p!=null&&typeof p!="string"||d.hasNextPage&&!p)throw E();let y=d.hasNextPage?p:null;return{items:c,nextCursor:y,windowSinceMs:a,windowUntilMs:u}}async pendingPageWithRetry(e){for(let n=1;n<os;n+=1)try{return await this.pendingPage(e)}catch(i){if(!ps(i))throw i}return this.pendingPage(e)}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw I("a digest run id is required");let i=V(e),o=cs(e.deliveryIds);if(o.length>is)throw I("legacy briefed accepts at most 100 delivery ids");if((await this.graphql(zr,{input:{inboxPath:i,deliveryIds:o,digestRunId:n}})).completeStewardBrief?.ok!==!0)throw E();return{ok:!0}}async digestRun(e){this.client._requireAuth();let i=(await this.graphql(Jr,{inboxPath:V(e),digestRunId:Lt(e.digestRunId)})).viewer?.stewardDigestRun;if(!i)throw E();return i}async digestRunPending(e){this.client._requireAuth();let n=V(e),i=Lt(e.digestRunId),o=[],r=new Set,a;for(;;){let c=(await this.graphql(Zr,{inboxPath:n,digestRunId:i,input:{first:100,...a===void 0?{}:{after:a}}})).viewer?.stewardDigestRunPending;if(!c||!Array.isArray(c.edges))throw E();let d=c.pageInfo;if(!d||typeof d.hasNextPage!="boolean")throw E();for(let y of c.edges){if(!y?.node)throw E();o.push(y.node)}if(!d.hasNextPage)break;let p=d.endCursor;if(typeof p!="string"||p===""||r.has(p))throw E();r.add(p),a=p}return o}async sendDigestRun(e){this.client._requireAuth();let n=Gt(e.deliveryIds??[]);if(n.length>rs)throw I("durable Daily Brief accepts at most 10000 delivery ids");if(e.body!==void 0&&e.body.trim()==="")throw I("a message body must be non-blank when provided");let o=(await this.graphql(es,{input:{inboxPath:V(e),digestRunId:Lt(e.digestRunId),deliveryIds:n,...e.body===void 0?{}:{body:e.body}}})).publishStewardDailyBrief?.run;if(!o)throw E();return o}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i||typeof i!="object")throw E();if(i.errors?.length){let o=i.errors.map(u=>u.extensions?.code),r=new Set(o).size===1&&typeof o[0]=="string"?o[0]:void 0,a=r?Vr[r]:void 0;throw new l(r!==void 0&&a!==void 0?r:"GRAPHQL_ERROR",i.errors.map(u=>u.message).filter(u=>typeof u=="string").join("; ")||"GraphQL request failed",a??502,{errors:i.errors})}if(!i.data)throw E();return i.data}};function H(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(H,"isRecord");function R(t){return typeof t=="string"&&t.trim()!==""?t:void 0}s(R,"stringValue");function mt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}s(mt,"numberValue");function ft(t){return t===void 0?void 0:t.trim().toUpperCase()}s(ft,"upper");function Xn(t){return t.split("_")}s(Xn,"pairParts");function ms(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Xn(e)[1]?.toLowerCase()??""}s(ms,"inferInstrumentType");function hs(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}s(hs,"inferUnderlyingType");function Kn(t,e){let n=R(t.trading_pair)??R(t.tradingPair)??R(t.symbol);if(n===void 0)return;let i=R(t.type),o=Xn(n),r=R(t.base)??e??(o.length>=4?o.slice(2,-1).join("_"):o.length===3?o[2]:n),a=R(t.market)??R(t.exchange)??o[0]??"",u=R(t.quote)??o[o.length-1]??"",c=R(t.instrument_type)??R(t.instrumentType)??ms(i,n),d=R(t.underlying_type)??R(t.underlyingType)??hs(i);return{symbol:r,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:u,...i===void 0?{}:{type:i},...R(t.description)===void 0?{}:{description:R(t.description)},...mt(t.fee_rate)===void 0?mt(t.feeRate)===void 0?{}:{feeRate:mt(t.feeRate)}:{feeRate:mt(t.fee_rate)},...R(t.symbol_icon_url)===void 0?R(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:R(t.symbolIconUrl)}:{symbolIconUrl:R(t.symbol_icon_url)}}}s(Kn,"normalizeCandidate");function fs(t){if(!H(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(o=>H(o)?[Kn(o)].filter(r=>r!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let o of n){if(!H(o))continue;let r=R(o.symbol),a=o.trading_pairs;if(Array.isArray(a)){for(let u of a)if(!(!H(u)||!Array.isArray(u.pairs)))for(let c of u.pairs){if(!H(c))continue;let d=Kn({...c,instrument_type:c.instrument_type??u.instrument_type},r);d!==void 0&&i.push(d)}}}return i}s(fs,"flattenResponse");function gs(t,e){let n=e.trim();return t.tradingPair===n?!0:ft(t.symbol)===ft(n)}s(gs,"matchesQuery");function ht(t,e){return e===void 0||ft(t)===ft(e)}s(ht,"matchesFilter");function ys(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}s(ys,"dedupe");function bs(t){let e=H(t)?t:{};return{market:typeof e.market=="string"?e.market:void 0,instrumentType:typeof e.instrumentType=="string"?e.instrumentType:void 0,underlyingType:typeof e.underlyingType=="string"?e.underlyingType:void 0,quote:typeof e.quote=="string"?e.quote:void 0}}s(bs,"resolveFilters");function ws(t,e){let n=t.split("_"),i=n[0],o=n[1],r=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!o||!r||!a?{symbol:t,...e}:{symbol:r,market:e.market??i,instrumentType:e.instrumentType??o,underlyingType:e.underlyingType,quote:e.quote??a}}s(ws,"pairSearchParams");var le=class{constructor(e){this.client=e}client;static{s(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=H(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new l("INVALID_ARGUMENT","symbol is required",400);let o=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),r=ys(fs(o)).filter(u=>gs(u,i)).filter(u=>ht(u.market,e.market)).filter(u=>ht(u.instrumentType,e.instrumentType)).filter(u=>ht(u.underlyingType,e.underlyingType)).filter(u=>ht(u.quote,e.quote)),a=e.limit;return a!==void 0&&r.length>a?{query:i,candidates:r.slice(0,a),truncated:!0}:{query:i,candidates:r}}async resolve(e){let n=H(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,o=bs(e),r=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...o}:ws(i,o),a=await this.search(r),u=i===void 0?a.candidates:a.candidates.filter(c=>c.tradingPair===i);if(u.length!==1)throw new l(u.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",u.length===0?`no canonical trading pair matched "${i??r.symbol}"`:`multiple canonical trading pairs matched "${r.symbol}"`,u.length===0?404:409,{query:i??r.symbol,candidateCount:u.length,candidates:u.slice(0,50),...u.length>50?{truncated:!0}:{}});return u[0]}};var Zn="pageInfo { endCursor hasNextPage }",ei="__typename id slug displayName bio",Ps="__typename id username displayName bio",ti="__typename id ticker name kind assetClass venue { id name }",ni=`theses(input: $input) {
349
+ edges { cursor node { id latestRelease { thesisPublication { ${te} } } } }
350
+ ${Zn}
351
+ }`,_s=`query ToolkitPersonTheses($slug: String!, $input: ProfileThesisConnectionInput) {
352
+ scope: person(slug: $slug) { ${ei} ${ni} }
353
+ }`,Ts=`query ToolkitUserTheses($username: String!, $input: ProfileThesisConnectionInput) {
354
+ scope: publicUser(username: $username) { ${Ps} ${ni} }
355
+ }`,Rs=`query ToolkitEntityTheses($id: ID!, $input: EntityThesisConnectionInput) {
356
+ market { scope: entity(input: { id: $id }) { ${ti}
357
+ theses(input: $input) { edges { cursor node { ${te} } } ${Zn} }
338
358
  } }
339
- }`,Ls=`query ToolkitThesisPeople($query: String!) {
359
+ }`,Ss=`query ToolkitThesisPeople($query: String!) {
340
360
  search: people(input: { query: $query, first: 50 }) {
341
- edges { node { ${Cn} } } pageInfo { hasNextPage }
361
+ edges { node { ${ei} } } pageInfo { hasNextPage }
342
362
  }
343
- }`,Fs=`query ToolkitThesisEntities($query: String!) {
363
+ }`,ks=`query ToolkitThesisEntities($query: String!) {
344
364
  market { search: entities(input: { query: $query, first: 50, byPrefix: false }) {
345
- edges { node { ${xn} } } pageInfo { hasNextPage }
365
+ edges { node { ${ti} } } pageInfo { hasNextPage }
346
366
  } }
347
- }`,Os=`query ToolkitRelatedTheses($id: ID!, $input: RelatedThesisInput) {
367
+ }`,Es=`query ToolkitRelatedTheses($id: ID!, $input: RelatedThesisInput) {
348
368
  node(id: $id) { ... on Playbook { relatedTheses(input: $input) {
349
369
  state nextCursor
350
- edges { cursor node { itemKey score publication { ${z} } } }
370
+ edges { cursor node { itemKey score publication { ${te} } } }
351
371
  } } }
352
- }`,Gs=["person","personName","user","ticker","entityId"];function Nn(t){if(!m(t))throw O("Thesis parameters must be an object");let e=t.first===void 0?10:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw O("first must be an integer between 1 and 50");if(t.cursor!==void 0&&!L(t.cursor))throw O("cursor must be non-empty")}s(Nn,"validateThesisPageParams");function Ms(t){Nn(t);let e=Gs.filter(n=>t[n]!==void 0);if(e.length!==1)throw O("Choose exactly one of person, personName, user, ticker or entityId");if(!L(t[e[0]]))throw O(`${e[0]} must be non-empty`);if(t.entityId!==void 0&&!k(t.entityId))throw O("entityId must be a positive int64 string");if(t.status!==void 0&&t.status!=="ACTIVE"&&t.status!=="ARCHIVED")throw O("status must be ACTIVE or ARCHIVED");if(t.status!==void 0&&(t.ticker!==void 0||t.entityId!==void 0))throw O("status applies only to author lists")}s(Ms,"validateListThesesParams");async function Dn(t,e){Ms(e),t._requireAuth();let n={first:e.first??10,after:e.cursor},i=e.ticker===void 0?e.entityId:(await vn(t,Fs,e.ticker,"Entity")).id;if(i!==void 0){let u=await ke(t,Us,{id:i,input:n});if(!m(u.market))throw S();return An(u.market.scope,c=>J(c)?{playbookId:c.playbookId,publication:c}:void 0)}let o={...n,status:e.status},r=e.personName===void 0?e.person:(await vn(t,Ls,e.personName,"Person")).slug,a=r===void 0?await ke(t,Ds,{username:e.user,input:o}):await ke(t,Ns,{slug:r,input:o});return An(a.scope,u=>{if(!k(u.id))return;let c=u.latestRelease;if(c===null)return{playbookId:u.id,publication:null};if(!m(c))return;let d=c.thesisPublication;if(!(d!==null&&!J(d)))return{playbookId:u.id,publication:d}})}s(Dn,"listTheses");async function Un(t,e,n={}){if(Nn(n),!k(e))throw O("id must be an internal positive int64 Playbook ID");t._requireAuth();let i=await ke(t,Os,{id:`Playbook:${e}`,input:{first:n.first??10,after:n.cursor}});if(i.node===null)throw Ct();if(!m(i.node))throw S();let o=i.node.relatedTheses;if(!m(o)||!["GENERATING","READY","FAILED"].includes(o.state)||o.nextCursor!==null&&!L(o.nextCursor))throw S();for(let r of Fn(o))if(!L(r.node.itemKey)||typeof r.node.score!="number"||!J(r.node.publication))throw S();return{state:o.state,edges:o.edges,nextCursor:o.nextCursor}}s(Un,"relatedTheses");function An(t,e){if(t===null)throw Ct();let n=Ln(t);if(!m(t)||!m(t.theses))throw S();let i=t.theses,o=Fn(i).map(r=>{let a=e(r.node);if(a===void 0)throw S();return{cursor:r.cursor,node:a}});return{scope:n,edges:o,nextCursor:$s(i)}}s(An,"thesisPage");async function vn(t,e,n,i){let o=await ke(t,e,{query:n}),r=m(o.market)?o.market.search:o.search;if(!m(r)||!Array.isArray(r.edges)||!m(r.pageInfo))throw S();let a=r.edges.map(c=>Ln(m(c)?c.node:void 0));if(!a.every(c=>c.__typename===i))throw S();let u=r.pageInfo.hasNextPage===!0;if(a.length===1&&!u)return a[0];throw a.length===0&&!u?Ct():new l("AMBIGUOUS_IDENTITY",`Choose an exact identity before reading theses. Candidates: ${JSON.stringify(a)}${u?" More matches exist; refine the name or ticker.":""}`,400,{candidates:a,more:u})}s(vn,"resolveUnique");function Ln(t){if(!m(t)||!L(t.id))throw S();if(t.__typename==="Entity"){if(!["ticker","name","kind","assetClass"].every(n=>typeof t[n]=="string")||t.venue!==null&&(!m(t.venue)||!L(t.venue.id)||typeof t.venue.name!="string"))throw S()}else if(typeof t.displayName!="string"||typeof t.bio!="string"||!(t.__typename==="Person"&&L(t.slug)||t.__typename==="PublicUser"&&L(t.username)))throw S();let e={...t};return delete e.theses,e}s(Ln,"readScope");function Fn(t){if(!Array.isArray(t.edges)||!t.edges.every(e=>m(e)&&L(e.cursor)&&m(e.node)))throw S();return t.edges}s(Fn,"edges");function $s(t){let e=t.pageInfo;if(!m(e)||typeof e.hasNextPage!="boolean"||e.hasNextPage&&!L(e.endCursor))throw S();return e.hasNextPage?e.endCursor:null}s($s,"nextCursor");async function ke(t,e,n){let i=await t._request("POST","/query",{body:{query:e,variables:n}});if(!m(i))throw S();if(i.errors!==void 0){if(!Array.isArray(i.errors))throw S();if(i.errors.length){let o=i.errors.flatMap(c=>m(c)&&typeof c.message=="string"?[c.message]:[]),r=new Set(i.errors.map(c=>m(c)&&m(c.extensions)?c.extensions.code:void 0)),[a]=r,u=r.size===1&&typeof a=="string"?js.get(a):void 0;throw new l(u===void 0?"GRAPHQL_ERROR":String(a),o.join("; ")||"GraphQL request failed",u??400,{errors:i.errors})}}if(!m(i.data))throw S();return i.data}s(ke,"graphql");var js=new Map([["NOT_FOUND",404],["PERMISSION_DENIED",403],["UNAUTHENTICATED",401]]);function L(t){return typeof t=="string"&&t.trim().length>0}s(L,"nonempty");function O(t){return new l("INVALID_ARGUMENT",t,400)}s(O,"argument");function S(){return new l("GRAPHQL_INVALID_RESPONSE","Invalid Thesis read response",502)}s(S,"invalid");function Ct(){return new l("NOT_FOUND","No visible matching identity or Thesis found",404)}s(Ct,"notFound");var Bs=`mutation SetThesisStarred($input: SetThesisStarredInput!) {
372
+ }`,As=["person","personName","user","ticker","entityId"];function ii(t){if(!h(t))throw j("Thesis parameters must be an object");let e=t.first===void 0?10:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw j("first must be an integer between 1 and 50");if(t.cursor!==void 0&&!M(t.cursor))throw j("cursor must be non-empty")}s(ii,"validateThesisPageParams");function vs(t){ii(t);let e=As.filter(n=>t[n]!==void 0);if(e.length!==1)throw j("Choose exactly one of person, personName, user, ticker or entityId");if(!M(t[e[0]]))throw j(`${e[0]} must be non-empty`);if(t.entityId!==void 0&&!x(t.entityId))throw j("entityId must be a positive int64 string");if(t.status!==void 0&&t.status!=="ACTIVE"&&t.status!=="ARCHIVED")throw j("status must be ACTIVE or ARCHIVED");if(t.status!==void 0&&(t.ticker!==void 0||t.entityId!==void 0))throw j("status applies only to author lists")}s(vs,"validateListThesesParams");async function ri(t,e){vs(e),t._requireAuth();let n={first:e.first??10,after:e.cursor},i=e.ticker===void 0?e.entityId:(await Jn(t,ks,e.ticker,"Entity")).id;if(i!==void 0){let u=await Ie(t,Rs,{id:i,input:n});if(!h(u.market))throw C();return zn(u.market.scope,c=>ne(c)?{playbookId:c.playbookId,publication:c}:void 0)}let o={...n,status:e.status},r=e.personName===void 0?e.person:(await Jn(t,Ss,e.personName,"Person")).slug,a=r===void 0?await Ie(t,Ts,{username:e.user,input:o}):await Ie(t,_s,{slug:r,input:o});return zn(a.scope,u=>{if(!x(u.id))return;let c=u.latestRelease;if(c===null)return{playbookId:u.id,publication:null};if(!h(c))return;let d=c.thesisPublication;if(!(d!==null&&!ne(d)))return{playbookId:u.id,publication:d}})}s(ri,"listTheses");async function si(t,e,n={}){if(ii(n),!x(e))throw j("id must be an internal positive int64 Playbook ID");t._requireAuth();let i=await Ie(t,Es,{id:`Playbook:${e}`,input:{first:n.first??10,after:n.cursor}});if(i.node===null)throw Mt();if(!h(i.node))throw C();let o=i.node.relatedTheses;if(!h(o)||!["GENERATING","READY","FAILED"].includes(o.state)||o.nextCursor!==null&&!M(o.nextCursor))throw C();for(let r of ai(o))if(!M(r.node.itemKey)||typeof r.node.score!="number"||!ne(r.node.publication))throw C();return{state:o.state,edges:o.edges,nextCursor:o.nextCursor}}s(si,"relatedTheses");function zn(t,e){if(t===null)throw Mt();let n=oi(t);if(!h(t)||!h(t.theses))throw C();let i=t.theses,o=ai(i).map(r=>{let a=e(r.node);if(a===void 0)throw C();return{cursor:r.cursor,node:a}});return{scope:n,edges:o,nextCursor:Is(i)}}s(zn,"thesisPage");async function Jn(t,e,n,i){let o=await Ie(t,e,{query:n}),r=h(o.market)?o.market.search:o.search;if(!h(r)||!Array.isArray(r.edges)||!h(r.pageInfo))throw C();let a=r.edges.map(c=>oi(h(c)?c.node:void 0));if(!a.every(c=>c.__typename===i))throw C();let u=r.pageInfo.hasNextPage===!0;if(a.length===1&&!u)return a[0];throw a.length===0&&!u?Mt():new l("AMBIGUOUS_IDENTITY",`Choose an exact identity before reading theses. Candidates: ${JSON.stringify(a)}${u?" More matches exist; refine the name or ticker.":""}`,400,{candidates:a,more:u})}s(Jn,"resolveUnique");function oi(t){if(!h(t)||!M(t.id))throw C();if(t.__typename==="Entity"){if(!["ticker","name","kind","assetClass"].every(n=>typeof t[n]=="string")||t.venue!==null&&(!h(t.venue)||!M(t.venue.id)||typeof t.venue.name!="string"))throw C()}else if(typeof t.displayName!="string"||typeof t.bio!="string"||!(t.__typename==="Person"&&M(t.slug)||t.__typename==="PublicUser"&&M(t.username)))throw C();let e={...t};return delete e.theses,e}s(oi,"readScope");function ai(t){if(!Array.isArray(t.edges)||!t.edges.every(e=>h(e)&&M(e.cursor)&&h(e.node)))throw C();return t.edges}s(ai,"edges");function Is(t){let e=t.pageInfo;if(!h(e)||typeof e.hasNextPage!="boolean"||e.hasNextPage&&!M(e.endCursor))throw C();return e.hasNextPage?e.endCursor:null}s(Is,"nextCursor");async function Ie(t,e,n){let i=await t._request("POST","/query",{body:{query:e,variables:n}});if(!h(i))throw C();if(i.errors!==void 0){if(!Array.isArray(i.errors))throw C();if(i.errors.length){let o=i.errors.flatMap(c=>h(c)&&typeof c.message=="string"?[c.message]:[]),r=new Set(i.errors.map(c=>h(c)&&h(c.extensions)?c.extensions.code:void 0)),[a]=r,u=r.size===1&&typeof a=="string"?Cs.get(a):void 0;throw new l(u===void 0?"GRAPHQL_ERROR":String(a),o.join("; ")||"GraphQL request failed",u??400,{errors:i.errors})}}if(!h(i.data))throw C();return i.data}s(Ie,"graphql");var Cs=new Map([["NOT_FOUND",404],["PERMISSION_DENIED",403],["UNAUTHENTICATED",401]]);function M(t){return typeof t=="string"&&t.trim().length>0}s(M,"nonempty");function j(t){return new l("INVALID_ARGUMENT",t,400)}s(j,"argument");function C(){return new l("GRAPHQL_INVALID_RESPONSE","Invalid Thesis read response",502)}s(C,"invalid");function Mt(){return new l("NOT_FOUND","No visible matching identity or Thesis found",404)}s(Mt,"notFound");var xs=`mutation SetThesisStarred($input: SetThesisStarredInput!) {
353
373
  setThesisStarred(input: $input) {
354
374
  thesisId
355
375
  stats { starCount }
356
376
  viewerState { isStarred }
357
377
  }
358
- }`,Qs=`mutation SetThesisSignalEnabled($input: SetThesisSignalEnabledInput!) {
378
+ }`,qs=`mutation SetThesisSignalEnabled($input: SetThesisSignalEnabledInput!) {
359
379
  setThesisSignalEnabled(input: $input) {
360
380
  publication { playbookId authorVersionId archived researchPaused }
361
381
  }
362
- }`,Vs=9223372036854775807n,Hs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ys=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,Gn=new TextEncoder,oe=class{constructor(e){this.client=e}client;static{s(this,"ThesesResource")}list(e){return Dn(this.client,e)}related(e,n={}){return Un(this.client,e,n)}async assetCandidates(e){this.client._requireAuth();let n=Ae(e),i=await this.client._request("POST","/query",{body:{query:`query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
382
+ }`,Ns=9223372036854775807n,Ds=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Us=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,ci=new TextEncoder,de=class{constructor(e){this.client=e}client;static{s(this,"ThesesResource")}list(e){return ri(this.client,e)}related(e,n={}){return si(this.client,e,n)}async assetCandidates(e){this.client._requireAuth();let n=xe(e),i=await this.client._request("POST","/query",{body:{query:`query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
363
383
  viewer { thesisAssetCandidates(input: $input) {
364
384
  mentions { quote ticker resolution stance candidates { entityId ticker name kind } }
365
385
  } }
366
- }`,variables:{input:{text:n}}}});if(Array.isArray(i?.errors)&&i.errors.length>0)throw new l("GRAPHQL_ERROR","Asset extraction failed",400,{errors:i.errors});let o=i?.data,r=f(o)?o.viewer:void 0,a=f(r)?r.thesisAssetCandidates:void 0;if(!f(a)||!Array.isArray(a.mentions))throw p("asset candidates response must contain mentions");return{mentions:a.mentions.map((c,d)=>{if(!f(c)||typeof c.quote!="string"||typeof c.ticker!="string"||!["RESOLVED","AMBIGUOUS","UNRESOLVED"].includes(c.resolution)||!["UNKNOWN","BULLISH","BEARISH"].includes(c.stance)||!Array.isArray(c.candidates))throw p(`asset mention ${d} is invalid`);let y=c.candidates.map(g=>{if(!f(g)||typeof g.ticker!="string"||typeof g.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(g.kind))throw p(`asset mention ${d} has invalid candidate`);return{entityId:E(g.entityId,`asset mention ${d} candidate.entityId`),ticker:g.ticker,name:g.name,kind:g.kind}});return{...c,candidates:y}})}}async create(e){this.client._requireAuth();let n=Ws(e);return Q(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){this.client._requireAuth();let n=b(e,"id"),i=Xs(await this.client._request("GET",`/api/v1/theses/${n}`));if(i.thesis.id!==n)throw p("get response must match the requested thesis");return i}async getVersion(e,n){this.client._requireAuth();let i=b(e,"id"),o=b(n,"author_version_id"),r=Q(await this.client._request("GET",`/api/v1/theses/${i}/versions/${o}`));if(r.thesis.id!==i||r.thesis.author_version_id!==o)throw p("version response must match the requested thesis and author version");return r}async listUpdates(e,n={}){this.client._requireAuth();let i=b(e,"id"),o=n.first??10;if(!Number.isInteger(o)||o<1||o>100)throw h("first must be between 1 and 100");if(n.cursor!==void 0&&typeof n.cursor!="string")throw h("cursor must be a string");let r=await this.client._request("GET",`/api/v1/theses/${i}/versions`,{query:{first:o,cursor:n.cursor,updates_only:!0}});if(!f(r)||!Array.isArray(r.versions)||typeof r.next_cursor!="string")throw p("invalid Update list");let a=r.versions.map(u=>Q({thesis:u}).thesis);if(a.some(u=>u.id!==i))throw p("Update list must match requested Thesis");return{versions:a,next_cursor:r.next_cursor}}async deleteUpdate(e,n,i){this.client._requireAuth();let o=b(e,"id"),r=b(n,"author_version_id"),a=b(i,"expected_author_version_id"),u=Q(await this.client._request("DELETE",`/api/v1/theses/${o}/versions/${r}`,{query:{expected_author_version_id:a}}));if(u.thesis.id!==o)throw p("delete Update response must match requested Thesis");return u}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw h("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw h("cursor must be a string");return zs(await this.client._request("GET",`/api/v1/theses/${b(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=Ks(n),o=b(e,"id"),r=Q(await this.client._request("PUT",`/api/v1/theses/${o}`,{body:i}));if(r.thesis.id!==o)throw p("update response must match the requested thesis");return r}async setArchived(e,n){if(this.client._requireAuth(),!f(n))throw h("params is required");let i=b(e,"id"),o=Nt(n.request_id);if(typeof n.archived!="boolean")throw h("archived must be a boolean");n.note!==void 0&&q(n.note,"note");let r=await this.get(i);if(r.thesis.archived===n.archived&&n.note===void 0)return{thesis:r.thesis};if(!sr(r.thesis.entity_ids,r.thesis.entity_stances))throw p("archive requires one entity_stance for every Thesis entity");let a=await this.update(i,{request_id:o,expected_author_version_id:r.thesis.author_version_id,body:r.thesis.body,title:r.thesis.title,entity_ids:r.thesis.entity_ids,entity_stances:r.thesis.entity_stances,visibility:r.thesis.visibility,archived:n.archived,medias:r.thesis.medias,note:n.note});if(a.thesis.id!==i||a.thesis.archived!==n.archived)throw p("archive response must match the requested state");return a}async setStarred(e,n){this.client._requireAuth();let i=b(e,"id");if(typeof n!="boolean")throw h("isStarred must be a boolean");let r=(await On(this.client,Bs,{input:{thesisId:i,isStarred:n}})).setThesisStarred;if(!f(r)||!f(r.stats)||!f(r.viewerState))throw p("star response must contain stats and viewerState");let a=E(r.thesisId,"thesisId");if(a!==i)throw p("star response must match the requested thesis");let u=r.stats.starCount;if(typeof u!="number"||!Number.isInteger(u)||u<0)throw p("star response must contain a nonnegative star count");let c=G(r.viewerState.isStarred,"viewerState.isStarred");if(c!==n)throw p("star response did not apply the requested state");return{thesis_id:a,star_count:u,is_starred:c}}async setSignalEnabled(e,n){this.client._requireAuth();let i=b(e,"id");if(typeof n!="boolean")throw h("enabled must be a boolean");let r=(await On(this.client,Qs,{input:{thesisId:i,enabled:n}})).setThesisSignalEnabled;if(!f(r)||!f(r.publication))throw p("Signal response must contain publication");let a=r.publication,u=E(a.playbookId,"publication.playbookId");if(u!==i)throw p("Signal response must match the requested thesis");let c=G(a.researchPaused,"publication.researchPaused");if(c===n)throw p("Signal response did not apply the requested state");return{thesis_id:u,author_version_id:E(a.authorVersionId,"publication.authorVersionId"),archived:G(a.archived,"publication.archived"),research_paused:c,enabled:!c}}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw h("params is required");let i=b(e,"id"),o=Bn(n.visibility),r=Q(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:o}}));if(r.thesis.id!==i||r.thesis.visibility!==o)throw p("visibility response must match the requested thesis and visibility");return r}async close(e,n){this.client._requireAuth();let i={expected_author_version_id:b(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(i.note=q(n.note,"note")),Q(await this.client._request("POST",`/api/v1/theses/${b(e,"id")}/close`,{body:i}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${b(e,"id")}`);if(n===void 0)return{};if(!f(n)||Object.keys(n).length!==0)throw p("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=Ae(e.body),i=e.mode===void 0?"reformat":Zs(e.mode),o=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:i}});if(!f(o)||typeof o.body!="string")throw p("rewrite response must contain a string body");return{body:Qn(o.body)}}};function Ws(t){let e={request_id:Nt(t.request_id),body:Ae(t.body),title:Dt(t.title??""),entity_ids:$n(t.entity_ids??[],"entity_ids"),visibility:Bn(t.visibility??"public")};if(t.images!==void 0){if(!Array.isArray(t.images)||t.images.length>20)throw h("images must contain at most 20 URLs");if(t.images.length&&e.visibility!=="public")throw h("image publication currently requires public visibility");e.medias=t.images.map(n=>{if(!qt(n)||!n.startsWith("https://"))throw h("images must contain HTTPS URLs returned by the upload tool");return{type:"image",cover_url:n,url:n}})}return t.tickers!==void 0&&(e.tickers=Js(t.tickers)),t.entity_stances!==void 0&&(e.entity_stances=Mn(t.entity_stances,e.entity_ids)),e}s(Ws,"createBody");function Mn(t,e){if(!Array.isArray(t)||t.length>Ee)throw h("entity_stances must contain at most 100 values");let n=new Set(e),i=new Set;return t.map((o,r)=>{if(!f(o))throw h(`entity_stances[${r}] must be an object`);let a=b(o.entity_id,`entity_stances[${r}].entity_id`);if(!n.has(a)||i.has(a))throw h("entity stance must reference one unique entity_id");if(i.add(a),!["unknown","bullish","bearish"].includes(o.stance))throw h(`entity_stances[${r}].stance is invalid`);return{entity_id:a,stance:o.stance}})}s(Mn,"requireEntityStances");function Ks(t){let e={request_id:Nt(t.request_id),expected_author_version_id:b(t.expected_author_version_id,"expected_author_version_id"),body:Ae(t.body),title:Dt(t.title??""),entity_ids:$n(t.entity_ids??[],"entity_ids"),visibility:jn(t.visibility),editorial:t.editorial??!1};if(t.medias!==void 0){if(!Array.isArray(t.medias)||t.medias.length>20)throw h("medias must be an array of at most 20 items");if(!t.medias.every(Vn))throw h("medias contains invalid media");e.medias=t.medias}if(t.archived!==void 0){if(typeof t.archived!="boolean")throw h("archived must be a boolean");e.archived=t.archived}return t.note!==void 0&&(e.note=q(t.note,"note")),t.entity_stances!==void 0&&(e.entity_stances=Mn(t.entity_stances,e.entity_ids)),e}s(Ks,"updateBody");function Q(t){if(!f(t)||!f(t.thesis))throw p("response must contain thesis");let e=t.thesis,n={id:E(e.id,"thesis.id"),author_version_id:E(e.author_version_id,"thesis.author_version_id"),material_version_id:E(e.material_version_id,"thesis.material_version_id"),title:ir(e.title),body:Qn(e.body),entity_ids:er(e.entity_ids,"thesis.entity_ids"),visibility:nr(e.visibility),closed:G(e.closed,"thesis.closed"),archived:G(e.archived,"thesis.archived"),closing_note:tr(e.closing_note),author_kind:w(e.author_kind,"thesis.author_kind"),author_ref:w(e.author_ref,"thesis.author_ref")};if(e.medias!==void 0){if(!Array.isArray(e.medias)||e.medias.length>20)throw p("thesis.medias must contain at most 20 items");n.medias=e.medias.map(i=>{if(!Vn(i))throw p("thesis.medias contains invalid media");return{type:i.type,cover_url:i.cover_url,...i.url===void 0?{}:{url:i.url}}})}if(e.version_archived!==void 0&&(n.version_archived=G(e.version_archived,"thesis.version_archived")),e.note!==void 0&&(n.note=w(e.note,"thesis.note")),e.entity_stances!==void 0){if(!Array.isArray(e.entity_stances))throw p("thesis.entity_stances must be an array");n.entity_stances=e.entity_stances.map(i=>{if(!f(i))throw p("thesis.entity_stances contains invalid entry");let o=E(i.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(o))throw p("entity stance must reference a thesis entity");if(!["unknown","bullish","bearish"].includes(i.stance))throw p("thesis.entity_stances contains invalid stance");return{entity_id:o,stance:i.stance}})}return{thesis:n}}s(Q,"thesisResponse");function Xs(t){let e=Q(t);if(!f(t)||!f(t.author))throw p("response must contain author");let n=t.author,i={id:E(n.id,"author.id"),kind:w(n.kind,"author.kind"),display_name:w(n.display_name,"author.display_name"),avatar_url:w(n.avatar_url,"author.avatar_url"),username:w(n.username,"author.username")};if(!Array.isArray(t.entities))throw p("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw p("entities must match thesis.entity_ids");let o=t.entities.map((r,a)=>{if(!f(r))throw p(`entities[${a}] must be an object`);let u={id:E(r.id,`entities[${a}].id`),ticker:w(r.ticker,`entities[${a}].ticker`),name:w(r.name,`entities[${a}].name`),icon_url:w(r.icon_url,`entities[${a}].icon_url`),kind:w(r.kind,`entities[${a}].kind`)};if(u.id!==e.thesis.entity_ids[a])throw p("entities must preserve thesis.entity_ids order");return u});return{thesis:e.thesis,author:i,entities:o}}s(Xs,"thesisGetResponse");function zs(t,e,n){if(!f(t)||!f(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw p("invalid Signal history response");let i=t.research,o={state:w(i.state,"research.state"),pending_work:dt(i.pending_work,"research.pending_work"),read_complete:G(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(o.last_attempt_ms=dt(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(o.last_completed_ms=dt(i.last_completed_ms,"research.last_completed_ms"));let r=t.entries.map(u=>{if(!f(u)||!f(u.signal)||!f(u.signal.source))throw p("entry must include a Signal and source");let c=u.signal,d=c.source,y=E(c.thesis_id,"signal.thesis_id");if(y!==e)throw p("Signal belongs to another Thesis");let g=xt(u.cursor,"entry.cursor"),v={title:w(d.title,"source.title")};d.url!==void 0&&(v.url=w(d.url,"source.url")),d.published_at_ms!==void 0&&(v.published_at_ms=dt(d.published_at_ms,"source.published_at_ms"));let F={id:E(c.id,"signal.id"),thesis_id:y,author_version_id:E(c.author_version_id,"signal.author_version_id"),statement_snapshot:xt(c.statement_snapshot,"signal.statement_snapshot"),stance:w(c.stance,"signal.stance"),explanation:w(c.explanation,"signal.explanation"),information_kind:w(c.information_kind,"signal.information_kind"),source:v};if(c.evidence_excerpt!==void 0){if(!f(c.evidence_excerpt))throw p("invalid evidence excerpt");F.evidence_excerpt={text:xt(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:G(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:G(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:E(u.feed_entry_id,"feed_entry_id"),cursor:g,signal:F}}),a=w(t.next_cursor,"next_cursor");if(a&&a!==r[r.length-1]?.cursor)throw p("next_cursor must match the final entry");return{research:o,entries:r,next_cursor:a}}s(zs,"thesisSignalsResponse");function dt(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw p(e+" must be a nonnegative safe integer");return t}s(dt,"responseNonnegativeInteger");function xt(t,e){let n=w(t,e);if(!n.trim())throw p(e+" must be nonempty");return n}s(xt,"responseNonemptyText");function Nt(t){if(!Hs.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw h("request_id must be a non-zero RFC 4122 UUID");return t}s(Nt,"requireRequestID");function b(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw h(`${e} must be a positive int64 decimal string`);if(BigInt(t)>Vs)throw h(`${e} must be a positive int64 decimal string`);return t}s(b,"requireID");var Ee=100;function $n(t,e){if(!Array.isArray(t))throw h(`${e} must be an array`);if(t.length>Ee)throw h(`${e} must contain at most ${Ee} IDs`);return t.map((n,i)=>b(n,`${e}[${i}]`))}s($n,"requireIDs");function Js(t){if(!Array.isArray(t))throw h("tickers must be an array");if(t.length>100)throw h("tickers must contain at most 100 values");return t.map((e,n)=>{let i=q(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw h(`tickers[${n}] must be non-empty`);return i})}s(Js,"requireTickers");function Ae(t){let e=q(t,"body");if(e.trim().length===0)throw h("body must not be blank");if(Gn.encode(e).byteLength>65536)throw h("body must be at most 65536 UTF-8 bytes");return e}s(Ae,"requireBody");function Dt(t){let e=q(t,"title");if(Gn.encode(e).byteLength>500)throw h("title must be at most 500 UTF-8 bytes");return e}s(Dt,"requireTitle");function jn(t){let e=q(t,"visibility");if(e!=="public"&&e!=="private"&&e!=="paid")throw h("visibility must be public, private or paid");return e}s(jn,"requireVisibility");function Bn(t){let e=q(t,"visibility");if(e!=="public"&&e!=="private")throw h("visibility must be public or private");return e}s(Bn,"requirePublicVisibility");function Zs(t){let e=q(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw h("mode must be reformat, shorten, or enrich")}s(Zs,"requireRewriteMode");function q(t,e){if(typeof t!="string")throw h(`${e} must be a string`);if(Ys.test(t))throw h(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw h(`${e} must not contain NUL`);return t}s(q,"requireText");function E(t,e){if(typeof t=="number")throw p(`${e} must be a decimal string; numeric IDs are unsafe`);try{return b(t,e)}catch{throw p(`${e} must be a positive int64 decimal string`)}}s(E,"responseID");function er(t,e){if(!Array.isArray(t))throw p(`${e} must be an array`);if(t.length>Ee)throw p(`${e} must contain at most ${Ee} IDs`);return t.map((n,i)=>E(n,`${e}[${i}]`))}s(er,"responseIDs");function w(t,e){try{return q(t,e)}catch{throw p(`${e} must be valid text`)}}s(w,"responseText");function tr(t){try{return q(t,"note")}catch{throw p("thesis.closing_note must be valid text")}}s(tr,"responseClosingNote");function G(t,e){if(typeof t!="boolean")throw p(`${e} must be boolean`);return t}s(G,"responseBoolean");function nr(t){try{return jn(t)}catch{throw p("thesis.visibility must be public, private or paid")}}s(nr,"responseVisibility");function Qn(t){try{return Ae(t)}catch{throw p("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}s(Qn,"responseBody");function ir(t){try{return Dt(t)}catch{throw p("response title must be valid text at most 500 UTF-8 bytes")}}s(ir,"responseTitle");function f(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(f,"isRecord");function sr(t,e){if(t.length===0)return!e||e.length===0;if(!e||e.length!==t.length)return!1;let n=new Set(t),i=new Set;return e.every(o=>n.has(o.entity_id)&&!i.has(o.entity_id)&&i.add(o.entity_id))}s(sr,"completeEntityStances");function h(t){return new l("INVALID_ARGUMENT",t,400)}s(h,"invalidArgument");function p(t){return new l("INVALID_RESPONSE",t,502)}s(p,"invalidResponse");function Vn(t){return f(t)&&["image","price_chart","audio","video"].includes(t.type)&&qt(t.cover_url)&&(t.url==null||qt(t.url))}s(Vn,"validMedia");function qt(t){if(typeof t!="string"||t.length>2048||/[\s\u0000]/.test(t))return!1;try{let e=new URL(t);return["http:","https:"].includes(e.protocol)&&!!e.hostname&&!e.username&&!e.password}catch{return!1}}s(qt,"validMediaURL");async function On(t,e,n){let i=await t._request("POST","/query",{body:{query:e,variables:n}});if(!f(i))throw p("GraphQL response must be an object");if(i.errors!==void 0){if(!Array.isArray(i.errors))throw p("GraphQL errors must be an array");if(i.errors.length>0){let o=i.errors.flatMap(d=>f(d)&&typeof d.message=="string"?[d.message]:[]),r=new Set(i.errors.map(d=>f(d)&&f(d.extensions)?d.extensions.code:void 0)),[a]=r,u=r.size===1&&(a==="NOT_FOUND"||a==="PERMISSION_DENIED"||a==="UNAUTHENTICATED")?a:void 0,c=u==="NOT_FOUND"?404:u==="PERMISSION_DENIED"?403:u==="UNAUTHENTICATED"?401:400;throw new l(u??"GRAPHQL_ERROR",o.join("; ")||"GraphQL request failed",c,{errors:i.errors})}}if(!f(i.data))throw p("GraphQL response must contain data");return i.data}s(On,"thesisGraphql");var rr=`mutation CreateCompanyNews($input: CompanyNewsFeedInput!) {
386
+ }`,variables:{input:{text:n}}}});if(Array.isArray(i?.errors)&&i.errors.length>0)throw new l("GRAPHQL_ERROR","Asset extraction failed",400,{errors:i.errors});let o=i?.data,r=g(o)?o.viewer:void 0,a=g(r)?r.thesisAssetCandidates:void 0;if(!g(a)||!Array.isArray(a.mentions))throw m("asset candidates response must contain mentions");return{mentions:a.mentions.map((c,d)=>{if(!g(c)||typeof c.quote!="string"||typeof c.ticker!="string"||!["RESOLVED","AMBIGUOUS","UNRESOLVED"].includes(c.resolution)||!["UNKNOWN","BULLISH","BEARISH"].includes(c.stance)||!Array.isArray(c.candidates))throw m(`asset mention ${d} is invalid`);let p=c.candidates.map(y=>{if(!g(y)||typeof y.ticker!="string"||typeof y.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(y.kind))throw m(`asset mention ${d} has invalid candidate`);return{entityId:q(y.entityId,`asset mention ${d} candidate.entityId`),ticker:y.ticker,name:y.name,kind:y.kind}});return{...c,candidates:p}})}}async create(e){this.client._requireAuth();let n=Fs(e);return Y(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){this.client._requireAuth();let n=P(e,"id"),i=Os(await this.client._request("GET",`/api/v1/theses/${n}`));if(i.thesis.id!==n)throw m("get response must match the requested thesis");return i}async getVersion(e,n){this.client._requireAuth();let i=P(e,"id"),o=P(n,"author_version_id"),r=Y(await this.client._request("GET",`/api/v1/theses/${i}/versions/${o}`));if(r.thesis.id!==i||r.thesis.author_version_id!==o)throw m("version response must match the requested thesis and author version");return r}async listUpdates(e,n={}){this.client._requireAuth();let i=P(e,"id"),o=n.first??10;if(!Number.isInteger(o)||o<1||o>100)throw f("first must be between 1 and 100");if(n.cursor!==void 0&&typeof n.cursor!="string")throw f("cursor must be a string");let r=await this.client._request("GET",`/api/v1/theses/${i}/versions`,{query:{first:o,cursor:n.cursor,updates_only:!0}});if(!g(r)||!Array.isArray(r.versions)||typeof r.next_cursor!="string")throw m("invalid Update list");let a=r.versions.map(u=>Y({thesis:u}).thesis);if(a.some(u=>u.id!==i))throw m("Update list must match requested Thesis");return{versions:a,next_cursor:r.next_cursor}}async deleteUpdate(e,n,i){this.client._requireAuth();let o=P(e,"id"),r=P(n,"author_version_id"),a=P(i,"expected_author_version_id"),u=Y(await this.client._request("DELETE",`/api/v1/theses/${o}/versions/${r}`,{query:{expected_author_version_id:a}}));if(u.thesis.id!==o)throw m("delete Update response must match requested Thesis");return u}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw f("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw f("cursor must be a string");return Gs(await this.client._request("GET",`/api/v1/theses/${P(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=Ls(n),o=P(e,"id"),r=Y(await this.client._request("PUT",`/api/v1/theses/${o}`,{body:i}));if(r.thesis.id!==o)throw m("update response must match the requested thesis");return r}async setArchived(e,n){if(this.client._requireAuth(),!g(n))throw f("params is required");let i=P(e,"id"),o=Bt(n.request_id);if(typeof n.archived!="boolean")throw f("archived must be a boolean");n.note!==void 0&&F(n.note,"note");let r=await this.get(i);if(r.thesis.archived===n.archived&&n.note===void 0)return{thesis:r.thesis};if(!Vs(r.thesis.entity_ids,r.thesis.entity_stances))throw m("archive requires one entity_stance for every Thesis entity");let a=await this.update(i,{request_id:o,expected_author_version_id:r.thesis.author_version_id,body:r.thesis.body,title:r.thesis.title,entity_ids:r.thesis.entity_ids,entity_stances:r.thesis.entity_stances,visibility:r.thesis.visibility,archived:n.archived,medias:r.thesis.medias,note:n.note});if(a.thesis.id!==i||a.thesis.archived!==n.archived)throw m("archive response must match the requested state");return a}async setStarred(e,n){this.client._requireAuth();let i=P(e,"id");if(typeof n!="boolean")throw f("isStarred must be a boolean");let r=(await ui(this.client,xs,{input:{thesisId:i,isStarred:n}})).setThesisStarred;if(!g(r)||!g(r.stats)||!g(r.viewerState))throw m("star response must contain stats and viewerState");let a=q(r.thesisId,"thesisId");if(a!==i)throw m("star response must match the requested thesis");let u=r.stats.starCount;if(typeof u!="number"||!Number.isInteger(u)||u<0)throw m("star response must contain a nonnegative star count");let c=B(r.viewerState.isStarred,"viewerState.isStarred");if(c!==n)throw m("star response did not apply the requested state");return{thesis_id:a,star_count:u,is_starred:c}}async setSignalEnabled(e,n){this.client._requireAuth();let i=P(e,"id");if(typeof n!="boolean")throw f("enabled must be a boolean");let r=(await ui(this.client,qs,{input:{thesisId:i,enabled:n}})).setThesisSignalEnabled;if(!g(r)||!g(r.publication))throw m("Signal response must contain publication");let a=r.publication,u=q(a.playbookId,"publication.playbookId");if(u!==i)throw m("Signal response must match the requested thesis");let c=B(a.researchPaused,"publication.researchPaused");if(c===n)throw m("Signal response did not apply the requested state");return{thesis_id:u,author_version_id:q(a.authorVersionId,"publication.authorVersionId"),archived:B(a.archived,"publication.archived"),research_paused:c,enabled:!c}}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw f("params is required");let i=P(e,"id"),o=mi(n.visibility),r=Y(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:o}}));if(r.thesis.id!==i||r.thesis.visibility!==o)throw m("visibility response must match the requested thesis and visibility");return r}async close(e,n){this.client._requireAuth();let i={expected_author_version_id:P(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(i.note=F(n.note,"note")),Y(await this.client._request("POST",`/api/v1/theses/${P(e,"id")}/close`,{body:i}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${P(e,"id")}`);if(n===void 0)return{};if(!g(n)||Object.keys(n).length!==0)throw m("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=xe(e.body),i=e.mode===void 0?"reformat":$s(e.mode),o=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:i}});if(!g(o)||typeof o.body!="string")throw m("rewrite response must contain a string body");return{body:hi(o.body)}}};function Fs(t){let e={request_id:Bt(t.request_id),body:xe(t.body),title:Qt(t.title??""),entity_ids:di(t.entity_ids??[],"entity_ids"),visibility:mi(t.visibility??"public")};if(t.images!==void 0){if(!Array.isArray(t.images)||t.images.length>20)throw f("images must contain at most 20 URLs");if(t.images.length&&e.visibility!=="public")throw f("image publication currently requires public visibility");e.medias=t.images.map(n=>{if(!jt(n)||!n.startsWith("https://"))throw f("images must contain HTTPS URLs returned by the upload tool");return{type:"image",cover_url:n,url:n}})}return t.tickers!==void 0&&(e.tickers=Ms(t.tickers)),t.entity_stances!==void 0&&(e.entity_stances=li(t.entity_stances,e.entity_ids)),e}s(Fs,"createBody");function li(t,e){if(!Array.isArray(t)||t.length>Ce)throw f("entity_stances must contain at most 100 values");let n=new Set(e),i=new Set;return t.map((o,r)=>{if(!g(o))throw f(`entity_stances[${r}] must be an object`);let a=P(o.entity_id,`entity_stances[${r}].entity_id`);if(!n.has(a)||i.has(a))throw f("entity stance must reference one unique entity_id");if(i.add(a),!["unknown","bullish","bearish"].includes(o.stance))throw f(`entity_stances[${r}].stance is invalid`);return{entity_id:a,stance:o.stance}})}s(li,"requireEntityStances");function Ls(t){let e={request_id:Bt(t.request_id),expected_author_version_id:P(t.expected_author_version_id,"expected_author_version_id"),body:xe(t.body),title:Qt(t.title??""),entity_ids:di(t.entity_ids??[],"entity_ids"),visibility:pi(t.visibility),editorial:t.editorial??!1};if(t.medias!==void 0){if(!Array.isArray(t.medias)||t.medias.length>20)throw f("medias must be an array of at most 20 items");if(!t.medias.every(fi))throw f("medias contains invalid media");e.medias=t.medias}if(t.archived!==void 0){if(typeof t.archived!="boolean")throw f("archived must be a boolean");e.archived=t.archived}return t.note!==void 0&&(e.note=F(t.note,"note")),t.entity_stances!==void 0&&(e.entity_stances=li(t.entity_stances,e.entity_ids)),e}s(Ls,"updateBody");function Y(t){if(!g(t)||!g(t.thesis))throw m("response must contain thesis");let e=t.thesis,n={id:q(e.id,"thesis.id"),author_version_id:q(e.author_version_id,"thesis.author_version_id"),material_version_id:q(e.material_version_id,"thesis.material_version_id"),title:Ws(e.title),body:hi(e.body),entity_ids:js(e.entity_ids,"thesis.entity_ids"),visibility:Qs(e.visibility),closed:B(e.closed,"thesis.closed"),archived:B(e.archived,"thesis.archived"),closing_note:Bs(e.closing_note),author_kind:S(e.author_kind,"thesis.author_kind"),author_ref:S(e.author_ref,"thesis.author_ref")};if(e.medias!==void 0){if(!Array.isArray(e.medias)||e.medias.length>20)throw m("thesis.medias must contain at most 20 items");n.medias=e.medias.map(i=>{if(!fi(i))throw m("thesis.medias contains invalid media");return{type:i.type,cover_url:i.cover_url,...i.url===void 0?{}:{url:i.url}}})}if(e.version_archived!==void 0&&(n.version_archived=B(e.version_archived,"thesis.version_archived")),e.note!==void 0&&(n.note=S(e.note,"thesis.note")),e.entity_stances!==void 0){if(!Array.isArray(e.entity_stances))throw m("thesis.entity_stances must be an array");n.entity_stances=e.entity_stances.map(i=>{if(!g(i))throw m("thesis.entity_stances contains invalid entry");let o=q(i.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(o))throw m("entity stance must reference a thesis entity");if(!["unknown","bullish","bearish"].includes(i.stance))throw m("thesis.entity_stances contains invalid stance");return{entity_id:o,stance:i.stance}})}return{thesis:n}}s(Y,"thesisResponse");function Os(t){let e=Y(t);if(!g(t)||!g(t.author))throw m("response must contain author");let n=t.author,i={id:q(n.id,"author.id"),kind:S(n.kind,"author.kind"),display_name:S(n.display_name,"author.display_name"),avatar_url:S(n.avatar_url,"author.avatar_url"),username:S(n.username,"author.username")};if(!Array.isArray(t.entities))throw m("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw m("entities must match thesis.entity_ids");let o=t.entities.map((r,a)=>{if(!g(r))throw m(`entities[${a}] must be an object`);let u={id:q(r.id,`entities[${a}].id`),ticker:S(r.ticker,`entities[${a}].ticker`),name:S(r.name,`entities[${a}].name`),icon_url:S(r.icon_url,`entities[${a}].icon_url`),kind:S(r.kind,`entities[${a}].kind`)};if(u.id!==e.thesis.entity_ids[a])throw m("entities must preserve thesis.entity_ids order");return u});return{thesis:e.thesis,author:i,entities:o}}s(Os,"thesisGetResponse");function Gs(t,e,n){if(!g(t)||!g(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw m("invalid Signal history response");let i=t.research,o={state:S(i.state,"research.state"),pending_work:gt(i.pending_work,"research.pending_work"),read_complete:B(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(o.last_attempt_ms=gt(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(o.last_completed_ms=gt(i.last_completed_ms,"research.last_completed_ms"));let r=t.entries.map(u=>{if(!g(u)||!g(u.signal)||!g(u.signal.source))throw m("entry must include a Signal and source");let c=u.signal,d=c.source,p=q(c.thesis_id,"signal.thesis_id");if(p!==e)throw m("Signal belongs to another Thesis");let y=$t(u.cursor,"entry.cursor"),w={title:S(d.title,"source.title")};d.url!==void 0&&(w.url=S(d.url,"source.url")),d.published_at_ms!==void 0&&(w.published_at_ms=gt(d.published_at_ms,"source.published_at_ms"));let _={id:q(c.id,"signal.id"),thesis_id:p,author_version_id:q(c.author_version_id,"signal.author_version_id"),statement_snapshot:$t(c.statement_snapshot,"signal.statement_snapshot"),stance:S(c.stance,"signal.stance"),explanation:S(c.explanation,"signal.explanation"),information_kind:S(c.information_kind,"signal.information_kind"),source:w};if(c.evidence_excerpt!==void 0){if(!g(c.evidence_excerpt))throw m("invalid evidence excerpt");_.evidence_excerpt={text:$t(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:B(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:B(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:q(u.feed_entry_id,"feed_entry_id"),cursor:y,signal:_}}),a=S(t.next_cursor,"next_cursor");if(a&&a!==r[r.length-1]?.cursor)throw m("next_cursor must match the final entry");return{research:o,entries:r,next_cursor:a}}s(Gs,"thesisSignalsResponse");function gt(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw m(e+" must be a nonnegative safe integer");return t}s(gt,"responseNonnegativeInteger");function $t(t,e){let n=S(t,e);if(!n.trim())throw m(e+" must be nonempty");return n}s($t,"responseNonemptyText");function Bt(t){if(!Ds.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw f("request_id must be a non-zero RFC 4122 UUID");return t}s(Bt,"requireRequestID");function P(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw f(`${e} must be a positive int64 decimal string`);if(BigInt(t)>Ns)throw f(`${e} must be a positive int64 decimal string`);return t}s(P,"requireID");var Ce=100;function di(t,e){if(!Array.isArray(t))throw f(`${e} must be an array`);if(t.length>Ce)throw f(`${e} must contain at most ${Ce} IDs`);return t.map((n,i)=>P(n,`${e}[${i}]`))}s(di,"requireIDs");function Ms(t){if(!Array.isArray(t))throw f("tickers must be an array");if(t.length>100)throw f("tickers must contain at most 100 values");return t.map((e,n)=>{let i=F(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw f(`tickers[${n}] must be non-empty`);return i})}s(Ms,"requireTickers");function xe(t){let e=F(t,"body");if(e.trim().length===0)throw f("body must not be blank");if(ci.encode(e).byteLength>65536)throw f("body must be at most 65536 UTF-8 bytes");return e}s(xe,"requireBody");function Qt(t){let e=F(t,"title");if(ci.encode(e).byteLength>500)throw f("title must be at most 500 UTF-8 bytes");return e}s(Qt,"requireTitle");function pi(t){let e=F(t,"visibility");if(e!=="public"&&e!=="private"&&e!=="paid")throw f("visibility must be public, private or paid");return e}s(pi,"requireVisibility");function mi(t){let e=F(t,"visibility");if(e!=="public"&&e!=="private")throw f("visibility must be public or private");return e}s(mi,"requirePublicVisibility");function $s(t){let e=F(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw f("mode must be reformat, shorten, or enrich")}s($s,"requireRewriteMode");function F(t,e){if(typeof t!="string")throw f(`${e} must be a string`);if(Us.test(t))throw f(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw f(`${e} must not contain NUL`);return t}s(F,"requireText");function q(t,e){if(typeof t=="number")throw m(`${e} must be a decimal string; numeric IDs are unsafe`);try{return P(t,e)}catch{throw m(`${e} must be a positive int64 decimal string`)}}s(q,"responseID");function js(t,e){if(!Array.isArray(t))throw m(`${e} must be an array`);if(t.length>Ce)throw m(`${e} must contain at most ${Ce} IDs`);return t.map((n,i)=>q(n,`${e}[${i}]`))}s(js,"responseIDs");function S(t,e){try{return F(t,e)}catch{throw m(`${e} must be valid text`)}}s(S,"responseText");function Bs(t){try{return F(t,"note")}catch{throw m("thesis.closing_note must be valid text")}}s(Bs,"responseClosingNote");function B(t,e){if(typeof t!="boolean")throw m(`${e} must be boolean`);return t}s(B,"responseBoolean");function Qs(t){try{return pi(t)}catch{throw m("thesis.visibility must be public, private or paid")}}s(Qs,"responseVisibility");function hi(t){try{return xe(t)}catch{throw m("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}s(hi,"responseBody");function Ws(t){try{return Qt(t)}catch{throw m("response title must be valid text at most 500 UTF-8 bytes")}}s(Ws,"responseTitle");function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}s(g,"isRecord");function Vs(t,e){if(t.length===0)return!e||e.length===0;if(!e||e.length!==t.length)return!1;let n=new Set(t),i=new Set;return e.every(o=>n.has(o.entity_id)&&!i.has(o.entity_id)&&i.add(o.entity_id))}s(Vs,"completeEntityStances");function f(t){return new l("INVALID_ARGUMENT",t,400)}s(f,"invalidArgument");function m(t){return new l("INVALID_RESPONSE",t,502)}s(m,"invalidResponse");function fi(t){return g(t)&&["image","price_chart","audio","video"].includes(t.type)&&jt(t.cover_url)&&(t.url==null||jt(t.url))}s(fi,"validMedia");function jt(t){if(typeof t!="string"||t.length>2048||/[\s\u0000]/.test(t))return!1;try{let e=new URL(t);return["http:","https:"].includes(e.protocol)&&!!e.hostname&&!e.username&&!e.password}catch{return!1}}s(jt,"validMediaURL");async function ui(t,e,n){let i=await t._request("POST","/query",{body:{query:e,variables:n}});if(!g(i))throw m("GraphQL response must be an object");if(i.errors!==void 0){if(!Array.isArray(i.errors))throw m("GraphQL errors must be an array");if(i.errors.length>0){let o=i.errors.flatMap(d=>g(d)&&typeof d.message=="string"?[d.message]:[]),r=new Set(i.errors.map(d=>g(d)&&g(d.extensions)?d.extensions.code:void 0)),[a]=r,u=r.size===1&&(a==="NOT_FOUND"||a==="PERMISSION_DENIED"||a==="UNAUTHENTICATED")?a:void 0,c=u==="NOT_FOUND"?404:u==="PERMISSION_DENIED"?403:u==="UNAUTHENTICATED"?401:400;throw new l(u??"GRAPHQL_ERROR",o.join("; ")||"GraphQL request failed",c,{errors:i.errors})}}if(!g(i.data))throw m("GraphQL response must contain data");return i.data}s(ui,"thesisGraphql");var Hs=`mutation CreateCompanyNews($input: CompanyNewsFeedInput!) {
367
387
  companyNews {
368
388
  createFeed(input: $input) { id producer { id } }
369
389
  }
370
- }`,or={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504};function ar(t){if(typeof t?.name!="string"||t.name.trim()!==t.name||!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/.test(t.name)||t.name==="news-lane")throw new l("INVALID_ARGUMENT","name must be 1-64 alphanumeric/hyphen characters and distinct from news-lane",400);if(!Array.isArray(t.tickers)||t.tickers.length<1||t.tickers.length>1e3||t.tickers.some(e=>typeof e!="string"||e.trim()!==e||!/^[A-Z0-9][A-Z0-9.-]{0,19}$/.test(e))||new Set(t.tickers).size!==t.tickers.length)throw new l("INVALID_ARGUMENT","tickers must contain 1-1000 unique uppercase symbols",400);for(let[e,n]of[["initial_lookback_hours",168],["page_size",100]]){let i=t[e];if(i!==void 0&&(!Number.isInteger(i)||i<0||i>n))throw new l("INVALID_ARGUMENT",`${e} must be an integer from 0 to ${n} (0 selects the default)`,400)}}s(ar,"validateCompanyNewsCreateParams");var ae=class{constructor(e){this.client=e}client;static{s(this,"CompanyNewsResource")}async create(e){this.client._requireAuth(),ar(e);let n={name:e.name,tickers:e.tickers,...e.initial_lookback_hours===void 0?{}:{initialLookbackHours:e.initial_lookback_hours},...e.page_size===void 0?{}:{pageSize:e.page_size}},i=await this.client._request("POST","/query",{body:{query:rr,variables:{input:n}}});if(Array.isArray(i?.errors)&&i.errors.length>0){let a=i.errors.map(c=>c?.extensions?.code),u=typeof a[0]=="string"&&a.every(c=>c===a[0])?a[0]:"GRAPHQL_ERROR";throw new l(u,i.errors.map(c=>c?.message).filter(Boolean).join("; ")||"Company News creation failed",or[u]??502,{errors:i.errors})}let o=i?.data?.companyNews?.createFeed,r={feed_id:o?.id,cronjob_id:o?.producer?.id};if(typeof r!="object"||r===null||!("feed_id"in r)||!Hn(r.feed_id)||!("cronjob_id"in r)||!Hn(r.cronjob_id))throw new l("INVALID_RESPONSE","company news response must contain decimal int64 feed_id and cronjob_id strings",502);return{feed_id:r.feed_id,cronjob_id:r.cronjob_id}}};function Hn(t){return typeof t=="string"&&t.trim()===t&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}s(Hn,"validID");var ur="https://api-llm.prd.alva.ai",cr="https://data-tools.prd.space.id";function Ut(t){return typeof t=="object"&&t!==null}s(Ut,"isRecord");function pt(t,e){if(!Ut(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}s(pt,"stringField");function lr(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let i=pt(t,"code");i&&(e.code=i)}else if(Ut(t)){let i=pt(t,"code"),o=pt(t,"name"),r=pt(t,"message");i&&(e.code=i),o&&(e.name=o),r&&(e.message=r)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(i=>!!i);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}s(lr,"describeCause");function dr(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",n={};t instanceof Error?(n.name=t.name,n.message=t.message):n.message=String(t);let{message:i,details:o}=lr(Ut(t)?t.cause:void 0);return o&&(n.cause=o),{message:i?`${e}; cause: ${i}`:e,details:n}}s(dr,"describeFetchFailure");var mt=class{static{s(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_x;_forYou;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_steward;_tradingPairs;_theses;_companyNews;constructor(e){this.baseUrl=e.baseUrl??ur,this.arraysBaseUrl=e.arraysBaseUrl??cr,this.viewer_token=e.viewer_token,this.pbsvToken=e.pbsvToken,this.apiKey=e.apiKey,this.gaClientId=e.gaClientId,this.gaSessionId=e.gaSessionId,this.utmParams=e.utmParams,this.signal=e.signal,this.originSessionId=e.originSessionId,this.originSessionKind=e.originSessionKind,this.originInboxPath=e.originInboxPath}get fs(){return this._fs??=new Ne(this)}get run(){return this._run??=new De(this)}get deploy(){return this._deploy??=new Ue(this)}get serviceAccount(){return this._serviceAccount??=new Le(this)}get release(){return this._release??=new Fe(this)}get feed(){return this._feed??=new Ge(this)}get automation(){return this._automation??=new ee(this)}get playbooks(){return this._playbooks??=new je(this)}get secrets(){return this._secrets??=new Be(this)}get sdk(){return this._sdk??=new Qe(this)}get dataSkills(){return this._dataSkills??=new Ve(this)}get playbookSkills(){return this._playbookSkills??=new He(this)}get comments(){return this._comments??=new Ye(this)}get remix(){return this._remix??=new We(this)}get screenshot(){return this._screenshot??=new Ke(this)}get user(){return this._user??=new Xe(this)}get trading(){return this._trading??=new ze(this)}get portfolio(){return this._portfolio??=new Je(this)}get arraysJwt(){return this._arraysJwt??=new Ze(this)}get notifications(){return this._notifications??=new et(this)}get notificationPreferences(){return this._notificationPreferences??=new tt(this)}get subscriptions(){return this._subscriptions??=new nt(this)}get alerts(){return this._alerts??=new te(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new it(this)}get feedback(){return this._feedback??=new st(this)}get functions(){return this._functions??=new rt(this)}get credits(){return this._credits??=new ot(this)}get markets(){return this._markets??=new ne(this)}get tradingPairs(){return this._tradingPairs??=new re(this)}get schedules(){return this._schedules??=new ie(this)}get steward(){return this._steward??=new se(this)}get theses(){return this._theses??=new oe(this)}get companyNews(){return this._companyNews??=new ae(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new l("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get x(){return this._x??=new X(this)}get forYou(){return this._forYou??=new Z(this)}async _request(e,n,i){let r=`${i?.baseUrl??this.baseUrl}${n}`;if(i?.query){let N=new URLSearchParams;for(let[M,ht]of Object.entries(i.query))ht!=null&&N.set(M,String(ht));let H=N.toString();H&&(r+=`?${H}`)}let a={};i?.noAuth||(this.pbsvToken?(a.Authorization=`Bearer ${this.pbsvToken}`,a["X-Pbsv"]="1"):this.viewer_token?a["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(a["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(a["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(a["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(a["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!i?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let u;i?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",u=i.rawBody):i?.jsonBody!==void 0?(a["Content-Type"]="application/json",u=i.jsonBody):i?.body!==void 0&&(a["Content-Type"]="application/json",u=JSON.stringify(i.body));let c,d=i?.timeoutMs,y=i?.signal??this.signal;if(y?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let g=d!==void 0?new AbortController:void 0,v=!1,F,ve;g&&d!==void 0&&(y&&(ve=s(()=>g.abort(y.reason),"abortListener"),y.addEventListener("abort",ve,{once:!0})),F=setTimeout(()=>{v=!0,g.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let Lt={method:e,headers:a,body:u,signal:g?.signal??y};d!==void 0&&(Lt.timeout=d);try{c=await fetch(r,Lt)}catch(N){if(y?.aborted&&!v)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(v)throw new l("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let H=dr(N);throw new l("NETWORK_ERROR",H.message,0,{method:e,path:n,...H.details})}finally{ve&&y&&y.removeEventListener("abort",ve),F!==void 0&&clearTimeout(F)}if(!c.ok){let N="";try{N=await Promise.resolve(c.text())}catch{N=""}if((c.headers.get("content-type")??"").includes("application/json")&&N)try{let M=JSON.parse(N);if(M.error)throw new l(M.error.code??"UNKNOWN",M.error.message??`HTTP ${c.status}`,c.status)}catch(M){if(M instanceof l)throw M}throw new l("UNKNOWN",`HTTP ${c.status}: ${N.slice(0,200)}`,c.status)}if(c.status===204)return;let Ft=(c.headers.get("content-type")??"").toLowerCase();return Ft.includes("application/json")||Ft.includes("+json")?c.json():c.arrayBuffer()}};var pr="0.34.0";Pt();return Jn(mr);})();
390
+ }`,Ys={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504};function Ks(t){if(typeof t?.name!="string"||t.name.trim()!==t.name||!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/.test(t.name)||t.name==="news-lane")throw new l("INVALID_ARGUMENT","name must be 1-64 alphanumeric/hyphen characters and distinct from news-lane",400);if(!Array.isArray(t.tickers)||t.tickers.length<1||t.tickers.length>1e3||t.tickers.some(e=>typeof e!="string"||e.trim()!==e||!/^[A-Z0-9][A-Z0-9.-]{0,19}$/.test(e))||new Set(t.tickers).size!==t.tickers.length)throw new l("INVALID_ARGUMENT","tickers must contain 1-1000 unique uppercase symbols",400);for(let[e,n]of[["initial_lookback_hours",168],["page_size",100]]){let i=t[e];if(i!==void 0&&(!Number.isInteger(i)||i<0||i>n))throw new l("INVALID_ARGUMENT",`${e} must be an integer from 0 to ${n} (0 selects the default)`,400)}}s(Ks,"validateCompanyNewsCreateParams");var pe=class{constructor(e){this.client=e}client;static{s(this,"CompanyNewsResource")}async create(e){this.client._requireAuth(),Ks(e);let n={name:e.name,tickers:e.tickers,...e.initial_lookback_hours===void 0?{}:{initialLookbackHours:e.initial_lookback_hours},...e.page_size===void 0?{}:{pageSize:e.page_size}},i=await this.client._request("POST","/query",{body:{query:Hs,variables:{input:n}}});if(Array.isArray(i?.errors)&&i.errors.length>0){let a=i.errors.map(c=>c?.extensions?.code),u=typeof a[0]=="string"&&a.every(c=>c===a[0])?a[0]:"GRAPHQL_ERROR";throw new l(u,i.errors.map(c=>c?.message).filter(Boolean).join("; ")||"Company News creation failed",Ys[u]??502,{errors:i.errors})}let o=i?.data?.companyNews?.createFeed,r={feed_id:o?.id,cronjob_id:o?.producer?.id};if(typeof r!="object"||r===null||!("feed_id"in r)||!gi(r.feed_id)||!("cronjob_id"in r)||!gi(r.cronjob_id))throw new l("INVALID_RESPONSE","company news response must contain decimal int64 feed_id and cronjob_id strings",502);return{feed_id:r.feed_id,cronjob_id:r.cronjob_id}}};function gi(t){return typeof t=="string"&&t.trim()===t&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}s(gi,"validID");var Xs="https://api-llm.prd.alva.ai",zs="https://data-tools.prd.space.id";function Wt(t){return typeof t=="object"&&t!==null}s(Wt,"isRecord");function yt(t,e){if(!Wt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}s(yt,"stringField");function Js(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let i=yt(t,"code");i&&(e.code=i)}else if(Wt(t)){let i=yt(t,"code"),o=yt(t,"name"),r=yt(t,"message");i&&(e.code=i),o&&(e.name=o),r&&(e.message=r)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(i=>!!i);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}s(Js,"describeCause");function Zs(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",n={};t instanceof Error?(n.name=t.name,n.message=t.message):n.message=String(t);let{message:i,details:o}=Js(Wt(t)?t.cause:void 0);return o&&(n.cause=o),{message:i?`${e}; cause: ${i}`:e,details:n}}s(Zs,"describeFetchFailure");var bt=class{static{s(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_x;_forYou;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_follows;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_steward;_tradingPairs;_theses;_companyNews;constructor(e){this.baseUrl=e.baseUrl??Xs,this.arraysBaseUrl=e.arraysBaseUrl??zs,this.viewer_token=e.viewer_token,this.pbsvToken=e.pbsvToken,this.apiKey=e.apiKey,this.gaClientId=e.gaClientId,this.gaSessionId=e.gaSessionId,this.utmParams=e.utmParams,this.signal=e.signal,this.originSessionId=e.originSessionId,this.originSessionKind=e.originSessionKind,this.originInboxPath=e.originInboxPath}get fs(){return this._fs??=new Le(this)}get run(){return this._run??=new Oe(this)}get deploy(){return this._deploy??=new Ge(this)}get serviceAccount(){return this._serviceAccount??=new Me(this)}get release(){return this._release??=new $e(this)}get feed(){return this._feed??=new Be(this)}get automation(){return this._automation??=new re(this)}get playbooks(){return this._playbooks??=new Ve(this)}get secrets(){return this._secrets??=new He(this)}get sdk(){return this._sdk??=new Ye(this)}get dataSkills(){return this._dataSkills??=new Ke(this)}get playbookSkills(){return this._playbookSkills??=new Xe(this)}get comments(){return this._comments??=new ze(this)}get remix(){return this._remix??=new Je(this)}get screenshot(){return this._screenshot??=new Ze(this)}get user(){return this._user??=new et(this)}get trading(){return this._trading??=new tt(this)}get portfolio(){return this._portfolio??=new nt(this)}get arraysJwt(){return this._arraysJwt??=new it(this)}get notifications(){return this._notifications??=new rt(this)}get notificationPreferences(){return this._notificationPreferences??=new st(this)}get subscriptions(){return this._subscriptions??=new ot(this)}get follows(){return this._follows??=new se(this)}get alerts(){return this._alerts??=new oe(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new ut(this)}get feedback(){return this._feedback??=new ct(this)}get functions(){return this._functions??=new lt(this)}get credits(){return this._credits??=new dt(this)}get markets(){return this._markets??=new ae(this)}get tradingPairs(){return this._tradingPairs??=new le(this)}get schedules(){return this._schedules??=new ue(this)}get steward(){return this._steward??=new ce(this)}get theses(){return this._theses??=new de(this)}get companyNews(){return this._companyNews??=new pe(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new l("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get x(){return this._x??=new ee(this)}get forYou(){return this._forYou??=new ie(this)}async _request(e,n,i){let r=`${i?.baseUrl??this.baseUrl}${n}`;if(i?.query){let L=new URLSearchParams;for(let[Q,wt]of Object.entries(i.query))wt!=null&&L.set(Q,String(wt));let X=L.toString();X&&(r+=`?${X}`)}let a={};i?.noAuth||(this.pbsvToken?(a.Authorization=`Bearer ${this.pbsvToken}`,a["X-Pbsv"]="1"):this.viewer_token?a["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(a["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(a["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(a["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(a["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!i?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let u;i?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",u=i.rawBody):i?.jsonBody!==void 0?(a["Content-Type"]="application/json",u=i.jsonBody):i?.body!==void 0&&(a["Content-Type"]="application/json",u=JSON.stringify(i.body));let c,d=i?.timeoutMs,p=i?.signal??this.signal;if(p?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let y=d!==void 0?new AbortController:void 0,w=!1,_,qe;y&&d!==void 0&&(p&&(qe=s(()=>y.abort(p.reason),"abortListener"),p.addEventListener("abort",qe,{once:!0})),_=setTimeout(()=>{w=!0,y.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let Vt={method:e,headers:a,body:u,signal:y?.signal??p};d!==void 0&&(Vt.timeout=d);try{c=await fetch(r,Vt)}catch(L){if(p?.aborted&&!w)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(w)throw new l("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let X=Zs(L);throw new l("NETWORK_ERROR",X.message,0,{method:e,path:n,...X.details})}finally{qe&&p&&p.removeEventListener("abort",qe),_!==void 0&&clearTimeout(_)}if(!c.ok){let L="";try{L=await Promise.resolve(c.text())}catch{L=""}if((c.headers.get("content-type")??"").includes("application/json")&&L)try{let Q=JSON.parse(L);if(Q.error)throw new l(Q.error.code??"UNKNOWN",Q.error.message??`HTTP ${c.status}`,c.status)}catch(Q){if(Q instanceof l)throw Q}throw new l("UNKNOWN",`HTTP ${c.status}: ${L.slice(0,200)}`,c.status)}if(c.status===204)return;let Ht=(c.headers.get("content-type")??"").toLowerCase();return Ht.includes("application/json")||Ht.includes("+json")?c.json():c.arrayBuffer()}};var eo="0.35.0";kt();return Ti(to);})();
371
391
  //# sourceMappingURL=browser.global.js.map