@alva-ai/toolkit 0.31.0 → 0.32.0-beta.1

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,25 @@
1
- "use strict";var AlvaToolkit=(()=>{var be=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var bn=Object.getOwnPropertyNames;var _n=Object.prototype.hasOwnProperty;var r=(t,e)=>be(t,"name",{value:e,configurable:!0});var Pn=(t,e)=>{for(var n in e)be(t,n,{get:e[n],enumerable:!0})},Rn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bn(e))!_n.call(t,s)&&s!==n&&be(t,s,{get:()=>e[s],enumerable:!(i=gn(e,s))||i.enumerable});return t};var kn=t=>Rn(be({},"__esModule",{value:!0}),t);var Pr={};Pn(Pr,{AlertsResource:()=>V,AlvaClient:()=>rt,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>me,AutomationResource:()=>Q,CliUsageError:()=>Re,ForYouResource:()=>B,MarketsResource:()=>W,PBSV_UPDATE_MESSAGE:()=>vt,SUBSCRIBE_MANAGE_MESSAGE:()=>Nt,SUBSCRIBE_PROPOSE_MESSAGE:()=>qt,SUBSCRIBE_RESULT_MESSAGE:()=>xt,SchedulesResource:()=>Y,StewardResource:()=>H,ThesesResource:()=>J,TradingPairsResource:()=>K,UDF_AUTH_REQUIRED_MESSAGE:()=>It,UDF_CONSENT_REQUEST_MESSAGE:()=>Et,UDF_CONSENT_RESPONSE_MESSAGE:()=>Ct,UdfAuthRequiredError:()=>$,UdfConsentDeniedError:()=>ne,UdfConsentRequiredError:()=>te,UdfConsentTimeoutError:()=>ie,UdfError:()=>R,UdfExecutionError:()=>ce,UdfFunctionDisabledError:()=>oe,UdfFunctionNotFoundError:()=>se,UdfInsufficientCredits:()=>re,UdfPidMismatchError:()=>D,UdfRateLimitedError:()=>ae,UdfTokenExpiredError:()=>Z,UdfTokenInvalidError:()=>ee,UdfTransportError:()=>j,VERSION:()=>_r,getViewerToken:()=>ue,installPlaybookRuntime:()=>dt,mapUdfErrorResponse:()=>ut,playbookIdFromToken:()=>ct,subscribe:()=>Ot,udf:()=>Mt});var R=class extends Error{static{r(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:i={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=i,this.status=s}},$=class extends R{static{r(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},Z=class extends R{static{r(this,"UdfTokenExpiredError")}},ee=class extends R{static{r(this,"UdfTokenInvalidError")}},D=class extends R{static{r(this,"UdfPidMismatchError")}},te=class extends R{static{r(this,"UdfConsentRequiredError")}},ne=class extends R{static{r(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},ie=class extends R{static{r(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},re=class extends R{static{r(this,"UdfInsufficientCredits")}},se=class extends R{static{r(this,"UdfFunctionNotFoundError")}},oe=class extends R{static{r(this,"UdfFunctionDisabledError")}},ae=class extends R{static{r(this,"UdfRateLimitedError")}},ce=class extends R{static{r(this,"UdfExecutionError")}},j=class extends R{static{r(this,"UdfTransportError")}},vt="alva:pbsv:update",Et="alva:udf:consent-request",Ct="alva:udf:consent-response",It="alva:udf:auth-required",qt="alva:subscribe:propose",xt="alva:subscribe:result",Nt="alva:subscribe:manage",Dt="https://api-llm.prd.alva.ai",Ut=300*1e3,X=null,E=null,at=Dt,I=null,w=null,At=!1,_e=new Map,Pe=new Map,wn=r(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Sn=r(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),ct=r(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Sn(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),ue=r(()=>X,"getViewerToken"),M=r(()=>!!ue(),"isAuthenticated"),Tn=r(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),An=r(t=>{let e=new URLSearchParams(t.location.search);X=e.get("_pbsv"),E=e.get("parent_origin"),at=(e.get("api_origin")||Dt).replace(/\/$/,""),I=ct(X),X&&Tn(t)},"parseBootParams"),Ft=r(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),vn=r(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),En=r(t=>{let e=t;return{...e,result:vn(e.result)}},"normalizeInvokeResponse"),Gt=r(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),ut=r((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,s=Gt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new Z(i,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new ee(i,o);case"PBSV_PID_MISMATCH":return new D(i,o);case"CONSENT_REQUIRED":return new te(i,o);case"INSUFFICIENT_CREDITS":return new re(i,o);case"FUNCTION_NOT_FOUND":return new se(i,o);case"FUNCTION_DISABLED":return new oe(i,o);case"RESOURCE_EXHAUSTED":return new ae(i,o);case"EXECUTION_FAILED":return new ce(i,o);default:return new j(i,o)}},"mapUdfErrorResponse"),Cn=r(t=>{if(!w||!E||t.origin!==E||t.source!==w.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===vt){typeof e.token=="string"&&e.token.length>0&&(X=e.token,I=ct(e.token));return}if(e.type===xt){if(typeof e.request_id!="string")return;let i=Pe.get(e.request_id);if(!i)return;clearTimeout(i.timer),Pe.delete(e.request_id),i.resolve(wn(e.status));return}if(e.type!==Ct||typeof e.request_id!="string")return;let n=_e.get(e.request_id);n&&(clearTimeout(n.timer),_e.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Lt=r(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),In=r(()=>{if(!I)return null;let t=Number(I);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),qn=r(async(t,e)=>{if(!w||!E)return"denied";let n=E,i=Lt();return new Promise(s=>{let o=setTimeout(()=>{_e.delete(i),s("timeout")},Ut);_e.set(i,{resolve:s,timer:o}),w?.parent.postMessage({type:Et,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),xn=r(async t=>{if(!w||!E)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=E,s=Lt();return new Promise(o=>{let a=setTimeout(()=>{Pe.delete(s),o("timeout")},Ut);Pe.set(s,{resolve:o,timer:a}),w?.parent.postMessage({type:qt,request_id:s,playbook_id:I,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Nn=r(()=>{!w||!E||w.parent.postMessage({type:Nt,playbook_id:I},E)},"manageSubscriptions"),Ot={propose:xn,manage:Nn},Dn=r(t=>{!w||!E||w.parent.postMessage({type:It,function_name:t},E)},"requestAuthentication"),lt=r(async(t,e,n=!1)=>{let i=ue();if(!i)throw new $;if(!I)throw new D("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=In();if(!s)throw new D("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${at}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new j("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Ft(o);if(o.ok)return En(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let c=Gt(a),u=typeof c.playbook_id=="string"?c.playbook_id:I,d=typeof c.min_allowance_suggested=="number"?c.min_allowance_suggested:1,m=await qn(u,d);if(m==="granted")return lt(t,e,!0);throw m==="timeout"?new ie:new ne}throw ut(a,o.status)},"call"),Un=r(async()=>{let t=ue();if(!t)throw new $;if(!I)throw new D("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${at}/api/v1/service/functions`);e.searchParams.set("playbook_id",I);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await Ft(n);if(!n.ok)throw ut(i,n.status);let s=i.functions;return Array.isArray(s)?s:[]},"list"),ot=r((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),Fn=r(t=>{if(typeof t!="string")return t;let n=w?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),Gn=r((t,e)=>{if(!w)throw new Error("Playbook runtime is not installed.");let n=Fn(t),i=w.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=M()?s:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),M()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!M()){Dn(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=o,ot(i,"alva:udf-button:loading",{functionName:e.functionName});try{let c=await lt(e.functionName,e.params??{});ot(i,"alva:udf-button:result",{functionName:e.functionName,result:c})}catch(c){ot(i,"alva:udf-button:error",{functionName:e.functionName,error:c})}finally{i.disabled=!1,i.textContent=M()?s:a,M()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),Mt={call:lt,list:Un,getViewerToken:ue,isAuthenticated:M,renderButton:Gn,UdfError:R,UdfAuthRequiredError:$,UdfTokenExpiredError:Z,UdfTokenInvalidError:ee,UdfPidMismatchError:D,UdfConsentRequiredError:te,UdfConsentDeniedError:ne,UdfConsentTimeoutError:ie,UdfInsufficientCredits:re,UdfFunctionNotFoundError:se,UdfFunctionDisabledError:oe,UdfRateLimitedError:ae,UdfExecutionError:ce,UdfTransportError:j},dt=r(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||At)return;w=e,At=!0,An(e),e.addEventListener("message",Cn);let n=e,i=n.alva||{};n.alva={...i,udf:Mt,subscribe:Ot}},"installPlaybookRuntime");var l=class extends Error{static{r(this,"AlvaError")}code;status;details;constructor(e,n,i,s){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=s}},Re=class extends Error{static{r(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function $t(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}r($t,"isArrayBuffer");var jt=1;function Ln(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,s=0,o=0;if(n>=194&&n<=223)i=1,s=128,o=n&31;else if(n>=224&&n<=239)i=2,s=2048,o=n&15;else if(n>=240&&n<=244)i=3,s=65536,o=n&7;else return!1;if(e+i>=t.length)return!1;for(let a=1;a<=i;a+=1){let c=t[e+a];if((c&192)!==128)return!1;o=o<<6|c&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=i+1}return!0}r(Ln,"isValidUtf8");var ke=class{constructor(e){this.client=e}client;static{r(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(!$t(n)||!Ln(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:jt}:{}}})}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:jt}:{}},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 Bt="9007199254740991";function Qt(t,e,n,i){let s=t.length+e,o=n.length+i;if(s!==o)return s>o;for(let a=0;a<s;a++){let c=a<t.length?t[a]:"0",u=a<n.length?n[a]:"0";if(c!==u)return c>u}return!1}r(Qt,"scaledIntegerGreater");function On(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??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+i).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=s-i.length;return a>=0?Qt(o,a,Bt,0):Qt(o,0,Bt,-a)}r(On,"numberOutsideSafeRange");function Mn(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(On(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++}}r(Mn,"validateJSONNumberTokens");function pt(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,s)=>pt(i,`${e}[${s}]`,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[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);pt(o.value,`${e}.${s}`,n)}}n.delete(t)}}r(pt,"assertPlainJSONData");function le(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");pt(t,"args",new Set);let e=JSON.stringify(t);return Vt(e),e}r(le,"serializeStructuredArgs");function Vt(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Mn(t)}r(Vt,"validateSerializedArgs");function de(t,e,n){let i=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Vt(n),i.push([e,n])),`{${i.map(([s,o])=>{let a=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}r(de,"objectWithRawJSONField");var we=class{constructor(e){this.client=e}client;static{r(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,le(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:de(i,"args",n)},timeoutMs:e.timeout_ms})}};var Se=class{constructor(e){this.client=e}client;static{r(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,le(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:de(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,le(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:i,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...n===void 0?{body:s}:{jsonBody:de(s,"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 Te=class{constructor(e){this.client=e}client;static{r(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 Ae=class{constructor(e){this.client=e}client;static{r(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 Ee=class{constructor(e){this.client=e}client;static{r(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=ve(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=ve(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=ve(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=ve(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 ve(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}r(ve,"requireFeedID");var $n=`
1
+ "use strict";var AlvaToolkit=(()=>{var Se=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var On=Object.prototype.hasOwnProperty;var r=(t,e)=>Se(t,"name",{value:e,configurable:!0});var Mn=(t,e)=>{for(var n in e)Se(t,n,{get:e[n],enumerable:!0})},$n=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Gn(e))!On.call(t,s)&&s!==n&&Se(t,s,{get:()=>e[s],enumerable:!(i=Fn(e,s))||i.enumerable});return t};var jn=t=>$n(Se({},"__esModule",{value:!0}),t);var Zr={};Mn(Zr,{AlertsResource:()=>z,AlvaClient:()=>dt,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>_e,AutomationResource:()=>K,CliUsageError:()=>ve,CompanyNewsResource:()=>ie,ForYouResource:()=>W,MarketsResource:()=>J,PBSV_UPDATE_MESSAGE:()=>Ut,SUBSCRIBE_MANAGE_MESSAGE:()=>$t,SUBSCRIBE_PROPOSE_MESSAGE:()=>Ot,SUBSCRIBE_RESULT_MESSAGE:()=>Mt,SchedulesResource:()=>X,StewardResource:()=>Z,ThesesResource:()=>ne,TradingPairsResource:()=>ee,UDF_AUTH_REQUIRED_MESSAGE:()=>Gt,UDF_CONSENT_REQUEST_MESSAGE:()=>Lt,UDF_CONSENT_RESPONSE_MESSAGE:()=>Ft,UdfAuthRequiredError:()=>Q,UdfConsentDeniedError:()=>ue,UdfConsentRequiredError:()=>ae,UdfConsentTimeoutError:()=>ce,UdfError:()=>R,UdfExecutionError:()=>he,UdfFunctionDisabledError:()=>pe,UdfFunctionNotFoundError:()=>de,UdfInsufficientCredits:()=>le,UdfPidMismatchError:()=>F,UdfRateLimitedError:()=>me,UdfTokenExpiredError:()=>se,UdfTokenInvalidError:()=>oe,UdfTransportError:()=>V,VERSION:()=>Xr,getViewerToken:()=>fe,installPlaybookRuntime:()=>bt,mapUdfErrorResponse:()=>yt,playbookIdFromToken:()=>ft,subscribe:()=>Ht,udf:()=>Wt});var R=class extends Error{static{r(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:i={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=i,this.status=s}},Q=class extends R{static{r(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},se=class extends R{static{r(this,"UdfTokenExpiredError")}},oe=class extends R{static{r(this,"UdfTokenInvalidError")}},F=class extends R{static{r(this,"UdfPidMismatchError")}},ae=class extends R{static{r(this,"UdfConsentRequiredError")}},ue=class extends R{static{r(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},ce=class extends R{static{r(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},le=class extends R{static{r(this,"UdfInsufficientCredits")}},de=class extends R{static{r(this,"UdfFunctionNotFoundError")}},pe=class extends R{static{r(this,"UdfFunctionDisabledError")}},me=class extends R{static{r(this,"UdfRateLimitedError")}},he=class extends R{static{r(this,"UdfExecutionError")}},V=class extends R{static{r(this,"UdfTransportError")}},Ut="alva:pbsv:update",Lt="alva:udf:consent-request",Ft="alva:udf:consent-response",Gt="alva:udf:auth-required",Ot="alva:subscribe:propose",Mt="alva:subscribe:result",$t="alva:subscribe:manage",jt="https://api-llm.prd.alva.ai",Bt=300*1e3,re=null,C=null,ht=jt,q=null,S=null,Dt=!1,Ee=new Map,Ae=new Map,Bn=r(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Qn=r(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),ft=r(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Qn(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),fe=r(()=>re,"getViewerToken"),B=r(()=>!!fe(),"isAuthenticated"),Vn=r(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),Yn=r(t=>{let e=new URLSearchParams(t.location.search);re=e.get("_pbsv"),C=e.get("parent_origin"),ht=(e.get("api_origin")||jt).replace(/\/$/,""),q=ft(re),re&&Vn(t)},"parseBootParams"),Qt=r(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Hn=r(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),Wn=r(t=>{let e=t;return{...e,result:Hn(e.result)}},"normalizeInvokeResponse"),Vt=r(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),yt=r((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,s=Vt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new se(i,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new oe(i,o);case"PBSV_PID_MISMATCH":return new F(i,o);case"CONSENT_REQUIRED":return new ae(i,o);case"INSUFFICIENT_CREDITS":return new le(i,o);case"FUNCTION_NOT_FOUND":return new de(i,o);case"FUNCTION_DISABLED":return new pe(i,o);case"RESOURCE_EXHAUSTED":return new me(i,o);case"EXECUTION_FAILED":return new he(i,o);default:return new V(i,o)}},"mapUdfErrorResponse"),Kn=r(t=>{if(!S||!C||t.origin!==C||t.source!==S.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===Ut){typeof e.token=="string"&&e.token.length>0&&(re=e.token,q=ft(e.token));return}if(e.type===Mt){if(typeof e.request_id!="string")return;let i=Ae.get(e.request_id);if(!i)return;clearTimeout(i.timer),Ae.delete(e.request_id),i.resolve(Bn(e.status));return}if(e.type!==Ft||typeof e.request_id!="string")return;let n=Ee.get(e.request_id);n&&(clearTimeout(n.timer),Ee.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Yt=r(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),zn=r(()=>{if(!q)return null;let t=Number(q);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),Jn=r(async(t,e)=>{if(!S||!C)return"denied";let n=C,i=Yt();return new Promise(s=>{let o=setTimeout(()=>{Ee.delete(i),s("timeout")},Bt);Ee.set(i,{resolve:s,timer:o}),S?.parent.postMessage({type:Lt,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),Xn=r(async t=>{if(!S||!C)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=C,s=Yt();return new Promise(o=>{let a=setTimeout(()=>{Ae.delete(s),o("timeout")},Bt);Ae.set(s,{resolve:o,timer:a}),S?.parent.postMessage({type:Ot,request_id:s,playbook_id:q,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Zn=r(()=>{!S||!C||S.parent.postMessage({type:$t,playbook_id:q},C)},"manageSubscriptions"),Ht={propose:Xn,manage:Zn},ei=r(t=>{!S||!C||S.parent.postMessage({type:Gt,function_name:t},C)},"requestAuthentication"),gt=r(async(t,e,n=!1)=>{let i=fe();if(!i)throw new Q;if(!q)throw new F("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=zn();if(!s)throw new F("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${ht}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new V("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Qt(o);if(o.ok)return Wn(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let u=Vt(a),c=typeof u.playbook_id=="string"?u.playbook_id:q,d=typeof u.min_allowance_suggested=="number"?u.min_allowance_suggested:1,h=await Jn(c,d);if(h==="granted")return gt(t,e,!0);throw h==="timeout"?new ce:new ue}throw yt(a,o.status)},"call"),ti=r(async()=>{let t=fe();if(!t)throw new Q;if(!q)throw new F("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${ht}/api/v1/service/functions`);e.searchParams.set("playbook_id",q);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await Qt(n);if(!n.ok)throw yt(i,n.status);let s=i.functions;return Array.isArray(s)?s:[]},"list"),mt=r((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),ni=r(t=>{if(typeof t!="string")return t;let n=S?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),ii=r((t,e)=>{if(!S)throw new Error("Playbook runtime is not installed.");let n=ni(t),i=S.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=B()?s:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),B()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!B()){ei(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=o,mt(i,"alva:udf-button:loading",{functionName:e.functionName});try{let u=await gt(e.functionName,e.params??{});mt(i,"alva:udf-button:result",{functionName:e.functionName,result:u})}catch(u){mt(i,"alva:udf-button:error",{functionName:e.functionName,error:u})}finally{i.disabled=!1,i.textContent=B()?s:a,B()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),Wt={call:gt,list:ti,getViewerToken:fe,isAuthenticated:B,renderButton:ii,UdfError:R,UdfAuthRequiredError:Q,UdfTokenExpiredError:se,UdfTokenInvalidError:oe,UdfPidMismatchError:F,UdfConsentRequiredError:ae,UdfConsentDeniedError:ue,UdfConsentTimeoutError:ce,UdfInsufficientCredits:le,UdfFunctionNotFoundError:de,UdfFunctionDisabledError:pe,UdfRateLimitedError:me,UdfExecutionError:he,UdfTransportError:V},bt=r(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||Dt)return;S=e,Dt=!0,Yn(e),e.addEventListener("message",Kn);let n=e,i=n.alva||{};n.alva={...i,udf:Wt,subscribe:Ht}},"installPlaybookRuntime");var l=class extends Error{static{r(this,"AlvaError")}code;status;details;constructor(e,n,i,s){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=s}},ve=class extends Error{static{r(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function Kt(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}r(Kt,"isArrayBuffer");var zt=1;function ri(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,s=0,o=0;if(n>=194&&n<=223)i=1,s=128,o=n&31;else if(n>=224&&n<=239)i=2,s=2048,o=n&15;else if(n>=240&&n<=244)i=3,s=65536,o=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;o=o<<6|u&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=i+1}return!0}r(ri,"isValidUtf8");var Ie=class{constructor(e){this.client=e}client;static{r(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(!Kt(n)||!ri(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:zt}:{}}})}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:zt}:{}},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 Jt="9007199254740991";function Xt(t,e,n,i){let s=t.length+e,o=n.length+i;if(s!==o)return s>o;for(let a=0;a<s;a++){let u=a<t.length?t[a]:"0",c=a<n.length?n[a]:"0";if(u!==c)return u>c}return!1}r(Xt,"scaledIntegerGreater");function si(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??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+i).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=s-i.length;return a>=0?Xt(o,a,Jt,0):Xt(o,0,Jt,-a)}r(si,"numberOutsideSafeRange");function oi(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(si(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++}}r(oi,"validateJSONNumberTokens");function _t(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,s)=>_t(i,`${e}[${s}]`,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[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);_t(o.value,`${e}.${s}`,n)}}n.delete(t)}}r(_t,"assertPlainJSONData");function ye(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");_t(t,"args",new Set);let e=JSON.stringify(t);return Zt(e),e}r(ye,"serializeStructuredArgs");function Zt(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");oi(t)}r(Zt,"validateSerializedArgs");function ge(t,e,n){let i=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Zt(n),i.push([e,n])),`{${i.map(([s,o])=>{let a=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}r(ge,"objectWithRawJSONField");var Ce=class{constructor(e){this.client=e}client;static{r(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,ye(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:ge(i,"args",n)},timeoutMs:e.timeout_ms})}};var xe=class{constructor(e){this.client=e}client;static{r(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,ye(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:ge(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,ye(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:i,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...n===void 0?{body:s}:{jsonBody:ge(s,"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 qe=class{constructor(e){this.client=e}client;static{r(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 Ne=class{constructor(e){this.client=e}client;static{r(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 Ue=class{constructor(e){this.client=e}client;static{r(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=De(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=De(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=De(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=De(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 De(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}r(De,"requireFeedID");function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(p,"record");function k(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}r(k,"isPositiveInt64");var Y=`
2
+ thesisId playbookId authorVersionId materialVersionId itemKey
3
+ title body publishedAtMs changeKind visibility
4
+ closed archived note closingNote researchPaused
5
+ entityIds categoryIds
6
+ entityStances { entityId stance }
7
+ entities { id ticker name }
8
+ publisher {
9
+ __typename id displayName avatarUrl bio followersCount
10
+ viewerState { following }
11
+ ... on Person { slug }
12
+ ... on PublicUser { username }
13
+ }
14
+ medias { type coverUrl url }
15
+ signalFeed { id }
16
+ snapshotRelease {
17
+ versionId materialVersionId publishedAtMs changeKind
18
+ sourceRefs {
19
+ title sourceKind sourceContentId publicUrl sourceTimeMs locator
20
+ }
21
+ }
22
+ `;function en(t){return Array.isArray(t)&&t.every(k)}r(en,"positiveInt64List");function ai(t){return Array.isArray(t)&&t.every(e=>p(e)&&k(e.entityId)&&typeof e.stance=="string"&&e.stance.trim()!=="")}r(ai,"stanceList");function ui(t){return Array.isArray(t)&&t.every(e=>p(e)&&typeof e.id=="string"&&e.id.trim()!==""&&typeof e.ticker=="string"&&typeof e.name=="string")}r(ui,"entityList");function ci(t){return Array.isArray(t)&&t.every(e=>p(e)&&typeof e.type=="string"&&e.type.trim()!==""&&typeof e.coverUrl=="string"&&(e.url===null||typeof e.url=="string"))}r(ci,"mediaList");function li(t){return Array.isArray(t)&&t.every(e=>p(e)&&(e.title===null||typeof e.title=="string")&&typeof e.sourceKind=="string"&&typeof e.sourceContentId=="string"&&typeof e.publicUrl=="string"&&di(e.sourceTimeMs)&&typeof e.locator=="string")}r(li,"sourceRefList");function di(t){return t===null||typeof t=="number"&&Number.isFinite(t)}r(di,"nullableMs");function pi(t){return p(t)&&k(t.versionId)&&k(t.materialVersionId)&&typeof t.publishedAtMs=="number"&&Number.isFinite(t.publishedAtMs)&&typeof t.changeKind=="string"&&t.changeKind.trim()!==""&&li(t.sourceRefs)}r(pi,"snapshot");function mi(t){return p(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)&&p(t.viewerState)&&(t.viewerState.following===null||typeof t.viewerState.following=="boolean")}r(mi,"publisher");function H(t){if(!p(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!en(t.entityIds)||!en(t.categoryIds)||!ai(t.entityStances)||!ui(t.entities)||!ci(t.medias)||!mi(t.publisher)||!pi(t.snapshotRelease)?!1:t.signalFeed===null||p(t.signalFeed)&&k(t.signalFeed.id)}r(H,"isThesisPublication");var hi=`
2
23
  query ToolkitForYou($input: FeedEntryConnectionInput) {
3
24
  viewer {
4
25
  forYou(input: $input) {
@@ -25,7 +46,7 @@ query ToolkitForYou($input: FeedEntryConnectionInput) {
25
46
  }
26
47
  }
27
48
  }
28
- `.trim();function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(h,"record");function jn(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&&!q(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}r(jn,"validateForYouListParams");function q(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}r(q,"isPositiveInt64");function pe(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}r(pe,"invalidResponse");function Bn(t){if(!h(t)||!Array.isArray(t.edges)||!h(t.pageInfo))return pe();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return pe();for(let s of t.edges){if(!h(s)||typeof s.cursor!="string"||!s.cursor.trim()||!h(s.node))return pe();let o=s.node;if(typeof o.id!="string"||!o.id.startsWith("FeedEntry:")||!q(o.id.slice(10))||!h(o.feed)||!q(o.feed.id)||!h(o.major)||typeof o.major.id!="string"||!q(o.major.feedId)||typeof o.title!="string"||typeof o.body!="string")return pe()}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?pe():t}r(Bn,"connection");var Qn=`
49
+ `.trim();function fi(t){if(!p(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")}r(fi,"validateForYouListParams");function be(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}r(be,"invalidResponse");function yi(t){if(!p(t)||!Array.isArray(t.edges)||!p(t.pageInfo))return be();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return be();for(let s of t.edges){if(!p(s)||typeof s.cursor!="string"||!s.cursor.trim()||!p(s.node))return be();let o=s.node;if(typeof o.id!="string"||!o.id.startsWith("FeedEntry:")||!k(o.id.slice(10))||!p(o.feed)||!k(o.feed.id)||!p(o.major)||typeof o.major.id!="string"||!k(o.major.feedId)||typeof o.title!="string"||typeof o.body!="string")return be()}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?be():t}r(yi,"connection");var gi=`
29
50
  query ToolkitForYouTheses($input: ThesisRecommendationInput) {
30
51
  viewer {
31
52
  thesisRecommendations(input: $input) {
@@ -36,31 +57,14 @@ query ToolkitForYouTheses($input: ThesisRecommendationInput) {
36
57
  node {
37
58
  itemKey
38
59
  publication {
39
- thesisId playbookId authorVersionId materialVersionId itemKey
40
- title body publishedAtMs changeKind visibility
41
- closed archived note closingNote researchPaused
42
- entityIds categoryIds
43
- entityStances { entityId stance }
44
- entities { id ticker name }
45
- publisher {
46
- id displayName avatarUrl bio followersCount
47
- viewerState { following }
48
- }
49
- medias { type coverUrl url }
50
- signalFeed { id }
51
- snapshotRelease {
52
- versionId materialVersionId publishedAtMs changeKind
53
- sourceRefs {
54
- title sourceKind sourceContentId publicUrl sourceTimeMs locator
55
- }
56
- }
60
+ ${Y}
57
61
  }
58
62
  }
59
63
  }
60
64
  }
61
65
  }
62
66
  }
63
- `.trim();function Vn(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")}r(Vn,"validateForYouThesesParams");function Wt(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]}r(Wt,"graphqlViewerField");function Ce(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid Thesis recommendation page",502)}r(Ce,"invalidPage");function Yt(t){return Array.isArray(t)&&t.every(q)}r(Yt,"positiveInt64List");function Wn(t){return Array.isArray(t)&&t.every(e=>h(e)&&q(e.entityId)&&typeof e.stance=="string"&&e.stance.trim()!=="")}r(Wn,"stanceList");function Yn(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")}r(Yn,"entityList");function Hn(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"))}r(Hn,"mediaList");function Kn(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"&&zn(e.sourceTimeMs)&&typeof e.locator=="string")}r(Kn,"sourceRefList");function zn(t){return t===null||typeof t=="number"&&Number.isFinite(t)}r(zn,"nullableMs");function Jn(t){return h(t)&&q(t.versionId)&&q(t.materialVersionId)&&typeof t.publishedAtMs=="number"&&Number.isFinite(t.publishedAtMs)&&typeof t.changeKind=="string"&&t.changeKind.trim()!==""&&Kn(t.sourceRefs)}r(Jn,"snapshot");function Xn(t){return h(t)&&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")}r(Xn,"publisher");function Zn(t){if(!h(t))return!1;for(let e of["thesisId","playbookId","authorVersionId","materialVersionId"])if(!q(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!Yt(t.entityIds)||!Yt(t.categoryIds)||!Wn(t.entityStances)||!Yn(t.entities)||!Hn(t.medias)||!Xn(t.publisher)||!Jn(t.snapshotRelease)?!1:t.signalFeed===null||h(t.signalFeed)&&q(t.signalFeed.id)}r(Zn,"publication");function ei(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 Ce();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 Ce();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()||!Zn(i.node.publication))return Ce();let n=t.edges[0];return e.startCursor!==(n?.cursor??"")?Ce():t}r(ei,"recommendationPage");var B=class{constructor(e){this.client=e}client;static{r(this,"ForYouResource")}async list(e={}){jn(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:$n,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});return Bn(Wt(n,"forYou"))}async theses(e={}){Vn(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Qn,variables:{input:{first:e.first??10,after:e.after}}}}),i=Wt(n,"thesisRecommendations");return ei(i)}};var ti=`
67
+ `.trim();function bi(t){if(!p(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")}r(bi,"validateForYouThesesParams");function tn(t,e){if(!p(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=>p(i)&&typeof i.message=="string"?[i.message]:[]);throw new l("GRAPHQL_ERROR",n.join("; ")||"GraphQL request failed",400,{errors:t.errors})}}if(!p(t.data)||!p(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]}r(tn,"graphqlViewerField");function Le(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid Thesis recommendation page",502)}r(Le,"invalidPage");function _i(t){if(!p(t)||!Array.isArray(t.edges)||!p(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 Le();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 Le();for(let i of t.edges)if(!p(i)||typeof i.cursor!="string"||!i.cursor.trim()||!p(i.node)||typeof i.node.itemKey!="string"||!i.node.itemKey.trim()||!H(i.node.publication))return Le();let n=t.edges[0];return e.startCursor!==(n?.cursor??"")?Le():t}r(_i,"recommendationPage");var W=class{constructor(e){this.client=e}client;static{r(this,"ForYouResource")}async list(e={}){fi(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:hi,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});return yi(tn(n,"forYou"))}async theses(e={}){bi(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:gi,variables:{input:{first:e.first??10,after:e.after}}}}),i=tn(n,"thesisRecommendations");return _i(i)}};var Pi=`
64
68
  query ToolkitAutomationAlertDelivery($automationId: ID!) {
65
69
  automation(id: $automationId) {
66
70
  alertDelivery {
@@ -70,7 +74,7 @@ query ToolkitAutomationAlertDelivery($automationId: ID!) {
70
74
  }
71
75
  }
72
76
  }
73
- `.trim(),ni=`
77
+ `.trim(),Ri=`
74
78
  mutation ToolkitUpdateAutomationAlertDelivery(
75
79
  $input: UpdateAutomationAlertDeliveryInput!
76
80
  $includeAlvaChannels: Boolean!
@@ -85,7 +89,7 @@ mutation ToolkitUpdateAutomationAlertDelivery(
85
89
  }
86
90
  }
87
91
  }
88
- `.trim(),Q=class{constructor(e){this.client=e;this.delivery=new me(e)}client;static{r(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=ii(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Ie(e.id);if(!ri(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)}},me=class{constructor(e){this.client=e}client;static{r(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Ie(e.id),s=(await this.graphql(ti,{automationId:n})).automation?.alertDelivery;if(!s)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=Ie(e.id),i=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!i&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=i?si(e.alvaChannelIds??[]):void 0,c=(await this.graphql(ni,{input:{automationId:n,...i?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,includeEmail:s})).updateAutomationAlertDelivery;if(!c)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return c}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",oi(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 ii(t){if(typeof t=="string")return Ie(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}r(ii,"requireAutomationID");function Ie(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}r(Ie,"requireAutomationIDString");function ri(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}r(ri,"hasAutomationUpdate");function si(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}r(si,"uniqueAlvaChannelIDs");function oi(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"}r(oi,"graphQLErrorMessage");var Ht=["public","private","paid"];var qe=class{constructor(e){this.client=e}client;static{r(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),s=e.ref.slice(n+1),o;for(;;){let a=await this.listByOwner({owner:i,cursor:o,limit:100}),c=a.items.find(u=>u.name===s);if(c)return c;if(!a.has_next||!a.next_cursor)return null;o=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}),s=ai(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(o=>ci(o,s)),has_next:i.has_next??!1}}async setVisibility(e){if(!Ht.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${Ht.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function ai(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"}r(ai,"webOriginFromApiBase");function ci(t,e){let n=t.creator?.name??"",i=t.name??"",s=n&&i?`${n}/${i}`:i,o=n&&i?`/u/${n}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}r(ci,"toAgentPlaybook");var xe=class{constructor(e){this.client=e}client;static{r(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 Ne=class{constructor(e){this.client=e}client;static{r(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 Kt=[{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 zt(t,e){return Kt.find(n=>n.skill===t&&n.file===e)}r(zt,"getSkillEndpointMetadata");function mt(t){return Kt.filter(e=>e.skill===t)}r(mt,"listSkillEndpointMetadata");var De=class{constructor(e){this.client=e}client;static{r(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...Jt(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!s)throw new Error(`empty skills summary response for "${e.name}"`);let o=mt(e.name);return{...s,...Jt(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!s)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=zt(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function Jt(t){let e=mt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}r(Jt,"metadataSummaryForSkill");function Xt(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}}r(Xt,"normalizePlaybookSkillSummary");function Zt(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]}}r(Zt,"parsePlaybookSkillId");var Ue=class{constructor(e){this.client=e}client;static{r(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(Xt)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=Zt(e),s=encodeURIComponent(n),o=encodeURIComponent(i),c=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!c)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...Xt(c),files:c.files??[]}}async file(e,n){let{username:i,name:s}=Zt(e),o=encodeURIComponent(i),a=encodeURIComponent(s),c=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${a}/files/${c}`)).data?.[0];if(!d)throw new l("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var Fe=class{constructor(e){this.client=e}client;static{r(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 Ge=class{constructor(e){this.client=e}client;static{r(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var Le=class{constructor(e){this.client=e}client;static{r(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 Oe=class{constructor(e){this.client=e}client;static{r(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var Me=class{constructor(e){this.client=e}client;static{r(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 $e=class{constructor(e){this.client=e}client;static{r(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 je=class{constructor(e){this.client=e}client;static{r(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 Be=class{constructor(e){this.client=e}client;static{r(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:ui(e)})}};function ui(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}r(ui,"buildQuery");var Qe=class{constructor(e){this.client=e}client;static{r(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 Ve=class{constructor(e){this.client=e}client;static{r(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 V=class{constructor(e){this.client=e}client;static{r(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 We=class{constructor(e){this.client=e}client;static{r(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:en(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:en(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 en(t){return`{"session_id":${tn(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${tn(t.target_id)}}`}r(en,"mutationBody");function tn(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}r(tn,"idLiteral");var Ye=class{constructor(e){this.client=e}client;static{r(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var He=class{constructor(e){this.client=e}client;static{r(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:di(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 ht(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>ht(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:li(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 ht(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=nn(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=nn(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}r(ht,"normalizeAllowance");function li(t){let e=ht(t);if(!e)throw new Error("allowance response missing allowance");return e}r(li,"requireAllowance");function nn(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}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)}r(nn,"timestampMs");function di(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}r(di,"parseResultPayload");var pi=`
92
+ `.trim(),K=class{constructor(e){this.client=e;this.delivery=new _e(e)}client;static{r(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=wi(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Fe(e.id);if(!Ti(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)}},_e=class{constructor(e){this.client=e}client;static{r(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Fe(e.id),s=(await this.graphql(Pi,{automationId:n})).automation?.alertDelivery;if(!s)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=Fe(e.id),i=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!i&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=i?ki(e.alvaChannelIds??[]):void 0,u=(await this.graphql(Ri,{input:{automationId:n,...i?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,includeEmail:s})).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",Si(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 wi(t){if(typeof t=="string")return Fe(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}r(wi,"requireAutomationID");function Fe(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}r(Fe,"requireAutomationIDString");function Ti(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}r(Ti,"hasAutomationUpdate");function ki(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}r(ki,"uniqueAlvaChannelIDs");function Si(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"}r(Si,"graphQLErrorMessage");var nn=["public","private","paid"];var Ge=class{constructor(e){this.client=e}client;static{r(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),s=e.ref.slice(n+1),o;for(;;){let a=await this.listByOwner({owner:i,cursor:o,limit:100}),u=a.items.find(c=>c.name===s);if(u)return u;if(!a.has_next||!a.next_cursor)return null;o=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}),s=Ei(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(o=>Ai(o,s)),has_next:i.has_next??!1}}async setVisibility(e){if(!nn.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${nn.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Ei(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"}r(Ei,"webOriginFromApiBase");function Ai(t,e){let n=t.creator?.name??"",i=t.name??"",s=n&&i?`${n}/${i}`:i,o=n&&i?`/u/${n}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}r(Ai,"toAgentPlaybook");var Oe=class{constructor(e){this.client=e}client;static{r(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 Me=class{constructor(e){this.client=e}client;static{r(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 rn=[{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 sn(t,e){return rn.find(n=>n.skill===t&&n.file===e)}r(sn,"getSkillEndpointMetadata");function Pt(t){return rn.filter(e=>e.skill===t)}r(Pt,"listSkillEndpointMetadata");var $e=class{constructor(e){this.client=e}client;static{r(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...on(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!s)throw new Error(`empty skills summary response for "${e.name}"`);let o=Pt(e.name);return{...s,...on(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!s)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=sn(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function on(t){let e=Pt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}r(on,"metadataSummaryForSkill");function an(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}}r(an,"normalizePlaybookSkillSummary");function un(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]}}r(un,"parsePlaybookSkillId");var je=class{constructor(e){this.client=e}client;static{r(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(an)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=un(e),s=encodeURIComponent(n),o=encodeURIComponent(i),u=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!u)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...an(u),files:u.files??[]}}async file(e,n){let{username:i,name:s}=un(e),o=encodeURIComponent(i),a=encodeURIComponent(s),u=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${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 Be=class{constructor(e){this.client=e}client;static{r(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 Qe=class{constructor(e){this.client=e}client;static{r(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var Ve=class{constructor(e){this.client=e}client;static{r(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 Ye=class{constructor(e){this.client=e}client;static{r(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var He=class{constructor(e){this.client=e}client;static{r(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 We=class{constructor(e){this.client=e}client;static{r(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 Ke=class{constructor(e){this.client=e}client;static{r(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 ze=class{constructor(e){this.client=e}client;static{r(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:vi(e)})}};function vi(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}r(vi,"buildQuery");var Je=class{constructor(e){this.client=e}client;static{r(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 Xe=class{constructor(e){this.client=e}client;static{r(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 z=class{constructor(e){this.client=e}client;static{r(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 Ze=class{constructor(e){this.client=e}client;static{r(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:cn(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:cn(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 cn(t){return`{"session_id":${ln(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${ln(t.target_id)}}`}r(cn,"mutationBody");function ln(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}r(ln,"idLiteral");var et=class{constructor(e){this.client=e}client;static{r(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var tt=class{constructor(e){this.client=e}client;static{r(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:Ci(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:Ii(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=dn(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=dn(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}r(Rt,"normalizeAllowance");function Ii(t){let e=Rt(t);if(!e)throw new Error("allowance response missing allowance");return e}r(Ii,"requireAllowance");function dn(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}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)}r(dn,"timestampMs");function Ci(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}r(Ci,"parseResultPayload");var xi=`
89
93
  query ToolkitCreditWallet {
90
94
  viewer {
91
95
  creditWallet {
@@ -95,7 +99,7 @@ query ToolkitCreditWallet {
95
99
  }
96
100
  }
97
101
  }
98
- `.trim(),mi=`
102
+ `.trim(),qi=`
99
103
  query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
100
104
  viewer {
101
105
  creditWallet {
@@ -127,7 +131,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
127
131
  }
128
132
  }
129
133
  }
130
- `.trim();function hi(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"}r(hi,"graphQLErrorMessage");var Ke=class{constructor(e){this.client=e}client;static{r(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(pi)).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(mi,{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",hi(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 fi=["Q1","Q2","Q3","Q4"],yi=["latest-completed","next-confirmed"],gi=`
134
+ `.trim();function Ni(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"}r(Ni,"graphQLErrorMessage");var nt=class{constructor(e){this.client=e}client;static{r(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(xi)).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",Ni(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 Di=["Q1","Q2","Q3","Q4"],Ui=["latest-completed","next-confirmed"],Li=`
131
135
  query ToolkitCompanyNarrative($ticker: String!) {
132
136
  market {
133
137
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -153,7 +157,7 @@ query ToolkitCompanyNarrative($ticker: String!) {
153
157
  }
154
158
  }
155
159
  }
156
- `.trim(),bi=`
160
+ `.trim(),Fi=`
157
161
  query ToolkitCompanyEarningsCatalog($ticker: String!) {
158
162
  market {
159
163
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -184,7 +188,7 @@ query ToolkitCompanyEarningsCatalog($ticker: String!) {
184
188
  }
185
189
  }
186
190
  }
187
- `.trim(),_i=`
191
+ `.trim(),Gi=`
188
192
  query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
189
193
  market {
190
194
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -254,7 +258,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
254
258
  }
255
259
  }
256
260
  }
257
- `.trim();function Pi(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"}r(Pi,"graphQLErrorMessage");function ft(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}r(ft,"normalizedTicker");var W=class{constructor(e){this.client=e}client;static{r(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=ft(e),s=(await this.graphql(gi,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);return{ticker:s.ticker,current:s.companyInsight,history:s.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let n=ft(e),s=(await this.graphql(bi,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);if(!s.earningsPeriods)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${s.ticker}`,404,{ticker:s.ticker});return s.earningsPeriods}async earnings(e){this.client._requireAuth();let n=ft(e.ticker),i=e.event,s=e.fiscalYear,o=e.fiscalQuarter;if(i!==void 0&&(s!==void 0||o!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(s===void 0!=(o===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(s!==void 0&&(!Number.isInteger(s)||s<1900||s>9999))throw new l("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!fi.includes(o))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let c,u;if(s!==void 0&&o!==void 0)c=s,u=o;else{let f=i??"latest-completed",T=await this.earningsPeriods(n),x=this.selectPeriod(T,f,n);c=x.fiscalYear,u=x.fiscalQuarter}let m=(await this.graphql(_i,{ticker:n,input:{fiscalYear:c,fiscalQuarter:u}})).market?.entity;if(!m)throw this.notFound(n);if(!m.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${m.ticker} FY${c} ${u}`,404,{ticker:m.ticker,fiscalYear:c,fiscalQuarter:u});return{ticker:m.ticker,...m.earnings}}selectPeriod(e,n,i){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let s=e.periods.filter(o=>o.status==="UPCOMING").sort((o,a)=>o.earningsDate.localeCompare(a.earningsDate));if(s.length>0)return s[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",Pi(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 ze=`
261
+ `.trim();function Oi(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"}r(Oi,"graphQLErrorMessage");function wt(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}r(wt,"normalizedTicker");var J=class{constructor(e){this.client=e}client;static{r(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=wt(e),s=(await this.graphql(Li,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);return{ticker:s.ticker,current:s.companyInsight,history:s.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let n=wt(e),s=(await this.graphql(Fi,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);if(!s.earningsPeriods)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${s.ticker}`,404,{ticker:s.ticker});return s.earningsPeriods}async earnings(e){this.client._requireAuth();let n=wt(e.ticker),i=e.event,s=e.fiscalYear,o=e.fiscalQuarter;if(i!==void 0&&(s!==void 0||o!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(s===void 0!=(o===void 0))throw new l("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(i!==void 0&&!Ui.includes(i))throw new l("INVALID_ARGUMENT",`Unknown earnings event selector: ${i}`,400);if(s!==void 0&&(!Number.isInteger(s)||s<1900||s>9999))throw new l("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!Di.includes(o))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let u,c;if(s!==void 0&&o!==void 0)u=s,c=o;else{let f=i??"latest-completed",A=await this.earningsPeriods(n),D=this.selectPeriod(A,f,n);u=D.fiscalYear,c=D.fiscalQuarter}let h=(await this.graphql(Gi,{ticker:n,input:{fiscalYear:u,fiscalQuarter:c}})).market?.entity;if(!h)throw this.notFound(n);if(!h.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${h.ticker} FY${u} ${c}`,404,{ticker:h.ticker,fiscalYear:u,fiscalQuarter:c});return{ticker:h.ticker,...h.earnings}}selectPeriod(e,n,i){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let s=e.periods.filter(o=>o.status==="UPCOMING").sort((o,a)=>o.earningsDate.localeCompare(a.earningsDate));if(s.length>0)return s[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",Oi(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 it=`
258
262
  id
259
263
  name
260
264
  rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
@@ -267,45 +271,45 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
267
271
  nextFireAtMs
268
272
  createdAtMs
269
273
  updatedAtMs
270
- `,Ri=`
274
+ `,Mi=`
271
275
  query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
272
276
  viewer { channel(id: $channelId) {
273
277
  schedules(input: { first: 64, after: $after }) {
274
- edges { node { channel { id } ${ze} } }
278
+ edges { node { channel { id } ${it} } }
275
279
  pageInfo { hasNextPage endCursor }
276
280
  }
277
281
  } }
278
- }`.trim(),ki=`
282
+ }`.trim(),$i=`
279
283
  mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
280
284
  updateChannelSchedule(input: $input) {
281
- schedule { channel { id } ${ze} }
285
+ schedule { channel { id } ${it} }
282
286
  deleted
283
287
  }
284
- }`.trim(),wi=`
288
+ }`.trim(),ji=`
285
289
  query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
286
290
  viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
287
- edges { node { ${ze} } }
291
+ edges { node { ${it} } }
288
292
  pageInfo { hasNextPage endCursor }
289
293
  } }
290
- }`.trim(),Si=`
294
+ }`.trim(),Bi=`
291
295
  mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
292
296
  updateSessionSchedule(input: $input) {
293
- schedule { ${ze} }
297
+ schedule { ${it} }
294
298
  deleted
295
299
  }
296
- }`.trim(),Ti=`
300
+ }`.trim(),Qi=`
297
301
  query ToolkitAgentChannel {
298
302
  viewer { channels { id kind } }
299
- }`.trim(),Ai=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,vi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Ei=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,Ci=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,Ii={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},Y=class{constructor(e){this.client=e}client;static{r(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=gt(e),i="inboxPath"in n,s=[],o=null,a=new Set;for(;;){let c=await this.graphql(i?wi:Ri,{...n,after:o}),u=i?c.viewer?.sessionSchedules:c.viewer?.channel?.schedules;if(!u?.edges)throw sn();for(let m of u.edges){if(!m?.node)throw k();s.push(yt(m.node))}if(u.pageInfo?.hasNextPage!==!0)return s;let d=u.pageInfo.endCursor;if(!d||a.has(d))throw k();a.add(d),o=d}}async put(e){this.client._requireAuth();let n={...gt(e),name:on(e.name),definition:{...qi(e.rule,e.bounds),message:{text:Ui(e.text)}}},i=(await this.update(n))?.schedule;if(!i)throw k();return yt(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({...rn(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw k()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Ti)).viewer?.channels?.find(i=>i.kind==="AGENT")?.id;if(!n)throw sn();return n}async manage(e,n){this.client._requireAuth();let i=(await this.update({...rn(n),lifecycle:e}))?.schedule;if(!i)throw k();return yt(i)}async update(e){let n="inboxPath"in e,i=await this.graphql(n?Si:ki,{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 s=i.errors.map(d=>d.extensions?.code),a=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,c=a?Ii[a]:void 0,u=a!==void 0&&c!==void 0?a:"GRAPHQL_ERROR";throw new l(u,i.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",c??502,{errors:i.errors})}if(!i.data)throw k();return i.data}};function qi(t,e){let n=xi(e);switch(t.kind){case"after":if(n)throw b("after does not accept recurring bounds");let i=Date.now()+an(t.duration,1),s=Math.ceil(i/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw b("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw b("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:bt(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Fi(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw b("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}r(qi,"ruleInput");function xi(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=bt(t.startsAt)),t.until!==void 0&&(e.untilMs=bt(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw b("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}r(xi,"boundsInput");function yt(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw k();let i=t.bounds??{},s=t.message??{},o={name:t.name,rule:Ni(t.rule),bounds:{...i.startsAtMs!=null?{startsAt:L(i.startsAtMs,!0)}:{},...i.untilMs!=null?{until:L(i.untilMs,!0)}:{},...i.maxOccurrences!=null?{maxOccurrences:_t(i.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:_t(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:L(t.nextFireAtMs,!0)}:{},createdAt:L(t.createdAtMs),updatedAt:L(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw k();let c={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!c)throw k();o.failure={code:c,...t.failureAtMs!=null?{at:L(t.failureAtMs)}:{}}}return o}r(yt,"fromWireSchedule");function Ni(t){switch(t.kind){case"AT":if(t.atMs==null)throw k();return{kind:"at",timestamp:L(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw k();return{kind:"every",interval:`PT${_t(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw k();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw k()}r(Ni,"fromWireRule");function rn(t){return{...gt(t),name:on(t.name)}}r(rn,"managementInput");function gt(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw b("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:Di(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?cn(e):void 0;if(typeof e!="string"||n===void 0||n>2048||!e.startsWith("/")||e.includes("\0")||e.slice(1).split("/").some(s=>s===""||s==="."||s===".."))throw b("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 b("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}r(gt,"targetInput");function Di(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw b("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 b("channelId must be a positive integer");return e}r(Di,"channelID");function on(t){if(!Ai.test(t))throw b("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}r(on,"requireName");function Ui(t){let e=cn(t);if(e===void 0||!t.trim()||e>16*1024)throw b("text must be 1..16384 UTF-8 bytes");return t}r(Ui,"requireText");function Fi(t){let e=an(t,60);if(e%1e3!==0)throw b("duration must resolve to whole seconds");return e/1e3}r(Fi,"durationSeconds");function an(t,e){let n=Ci.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 b("duration must be a positive ISO 8601 day/time duration");let[i,s,o,a]=n.slice(1,5).map(d=>BigInt(d??"0")),c=((i*24n+s)*60n+o)*60n+a;if(c<BigInt(e))throw b(`duration must be at least ${e} whole seconds`);let u=Number(c*1000n);if(!Number.isSafeInteger(u))throw b("duration is out of range");return u}r(an,"durationMilliseconds");function bt(t,e=!1){let n=(e?Ei:vi).exec(t);if(!n)throw b("timestamp must be RFC3339 with a timezone");let[i,s,o,a,c,u]=n.slice(1,7).map(Number),d=Number(n[8]??0),m=Number(n[9]??0),f=new Date(Date.UTC(i,s,0)).getUTCDate(),T=Date.parse(t);if(!Number.isFinite(T)||i<1||i>9999||s<1||s>12||o<1||o>f||a>23||c>59||u>59||d>23||m>59)throw b("timestamp must be RFC3339 with a timezone");return T}r(bt,"timestampMilliseconds");function L(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw k();let n=new Date(t);if(Number.isNaN(n.getTime()))throw k();return n.toISOString()}r(L,"timestampString");function _t(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw b(`${e} exceeds JavaScript safe integer range`);return n}r(_t,"safeInteger");function b(t){return new l("INVALID_ARGUMENT",t,400)}r(b,"invalid");function cn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}r(cn,"utf8Size");function sn(){return new l("NOT_FOUND","channel schedule target not found",404)}r(sn,"scheduleNotFound");function k(){return new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}r(k,"scheduleEmptyResponse");var Gi={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},Li=`
303
+ }`.trim(),Vi=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Yi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Hi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,Wi=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,Ki={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},X=class{constructor(e){this.client=e}client;static{r(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=kt(e),i="inboxPath"in n,s=[],o=null,a=new Set;for(;;){let u=await this.graphql(i?ji:Mi,{...n,after:o}),c=i?u.viewer?.sessionSchedules:u.viewer?.channel?.schedules;if(!c?.edges)throw mn();for(let h of c.edges){if(!h?.node)throw w();s.push(Tt(h.node))}if(c.pageInfo?.hasNextPage!==!0)return s;let d=c.pageInfo.endCursor;if(!d||a.has(d))throw w();a.add(d),o=d}}async put(e){this.client._requireAuth();let n={...kt(e),name:hn(e.name),definition:{...zi(e.rule,e.bounds),message:{text:er(e.text)}}},i=(await this.update(n))?.schedule;if(!i)throw w();return Tt(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({...pn(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw w()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Qi)).viewer?.channels?.find(i=>i.kind==="AGENT")?.id;if(!n)throw mn();return n}async manage(e,n){this.client._requireAuth();let i=(await this.update({...pn(n),lifecycle:e}))?.schedule;if(!i)throw w();return Tt(i)}async update(e){let n="inboxPath"in e,i=await this.graphql(n?Bi:$i,{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 s=i.errors.map(d=>d.extensions?.code),a=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,u=a?Ki[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 w();return i.data}};function zi(t,e){let n=Ji(e);switch(t.kind){case"after":if(n)throw b("after does not accept recurring bounds");let i=Date.now()+fn(t.duration,1),s=Math.ceil(i/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw b("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw b("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:St(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:tr(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw b("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}r(zi,"ruleInput");function Ji(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=St(t.startsAt)),t.until!==void 0&&(e.untilMs=St(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw b("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}r(Ji,"boundsInput");function Tt(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw w();let i=t.bounds??{},s=t.message??{},o={name:t.name,rule:Xi(t.rule),bounds:{...i.startsAtMs!=null?{startsAt:$(i.startsAtMs,!0)}:{},...i.untilMs!=null?{until:$(i.untilMs,!0)}:{},...i.maxOccurrences!=null?{maxOccurrences:Et(i.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:Et(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:$(t.nextFireAtMs,!0)}:{},createdAt:$(t.createdAtMs),updatedAt:$(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw w();let u={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!u)throw w();o.failure={code:u,...t.failureAtMs!=null?{at:$(t.failureAtMs)}:{}}}return o}r(Tt,"fromWireSchedule");function Xi(t){switch(t.kind){case"AT":if(t.atMs==null)throw w();return{kind:"at",timestamp:$(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw w();return{kind:"every",interval:`PT${Et(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw w();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw w()}r(Xi,"fromWireRule");function pn(t){return{...kt(t),name:hn(t.name)}}r(pn,"managementInput");function kt(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw b("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:Zi(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?yn(e):void 0;if(typeof e!="string"||n===void 0||n>2048||!e.startsWith("/")||e.includes("\0")||e.slice(1).split("/").some(s=>s===""||s==="."||s===".."))throw b("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 b("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}r(kt,"targetInput");function Zi(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw b("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 b("channelId must be a positive integer");return e}r(Zi,"channelID");function hn(t){if(!Vi.test(t))throw b("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}r(hn,"requireName");function er(t){let e=yn(t);if(e===void 0||!t.trim()||e>16*1024)throw b("text must be 1..16384 UTF-8 bytes");return t}r(er,"requireText");function tr(t){let e=fn(t,60);if(e%1e3!==0)throw b("duration must resolve to whole seconds");return e/1e3}r(tr,"durationSeconds");function fn(t,e){let n=Wi.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 b("duration must be a positive ISO 8601 day/time duration");let[i,s,o,a]=n.slice(1,5).map(d=>BigInt(d??"0")),u=((i*24n+s)*60n+o)*60n+a;if(u<BigInt(e))throw b(`duration must be at least ${e} whole seconds`);let c=Number(u*1000n);if(!Number.isSafeInteger(c))throw b("duration is out of range");return c}r(fn,"durationMilliseconds");function St(t,e=!1){let n=(e?Hi:Yi).exec(t);if(!n)throw b("timestamp must be RFC3339 with a timezone");let[i,s,o,a,u,c]=n.slice(1,7).map(Number),d=Number(n[8]??0),h=Number(n[9]??0),f=new Date(Date.UTC(i,s,0)).getUTCDate(),A=Date.parse(t);if(!Number.isFinite(A)||i<1||i>9999||s<1||s>12||o<1||o>f||a>23||u>59||c>59||d>23||h>59)throw b("timestamp must be RFC3339 with a timezone");return A}r(St,"timestampMilliseconds");function $(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw w();let n=new Date(t);if(Number.isNaN(n.getTime()))throw w();return n.toISOString()}r($,"timestampString");function Et(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw b(`${e} exceeds JavaScript safe integer range`);return n}r(Et,"safeInteger");function b(t){return new l("INVALID_ARGUMENT",t,400)}r(b,"invalid");function yn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}r(yn,"utf8Size");function mn(){return new l("NOT_FOUND","channel schedule target not found",404)}r(mn,"scheduleNotFound");function w(){return new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}r(w,"scheduleEmptyResponse");var nr={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},ir=`
300
304
  mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
301
305
  updateStewardDelivery(input: $input) { delivery { deliveryId state } }
302
- }`.trim(),Oi=`
306
+ }`.trim(),rr=`
303
307
  mutation ToolkitStewardForward($input: UpdateStewardDeliveryInput!) {
304
308
  updateStewardDelivery(input: $input) { delivery { deliveryId state channelMessageId } }
305
- }`.trim(),Mi=`
309
+ }`.trim(),sr=`
306
310
  mutation ToolkitStewardSend($input: PostStewardMessageInput!) {
307
311
  postStewardMessage(input: $input) { message { channelMessageId requestId } }
308
- }`.trim(),$i=`
312
+ }`.trim(),or=`
309
313
  query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInput) {
310
314
  viewer {
311
315
  stewardDigestPending(inboxPath: $inboxPath, input: $input) {
@@ -318,12 +322,40 @@ query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInp
318
322
  windowUntilMs
319
323
  }
320
324
  }
321
- }`.trim(),ji=`
325
+ }`.trim(),ar=`
322
326
  mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
323
327
  completeStewardBrief(input: $input) { ok }
324
- }`.trim(),Bi=new Set(["immediate","digest","suppress"]),Qi=/^[1-9][0-9]{0,18}$/;function A(t){return new l("INVALID_ARGUMENT",t,400)}r(A,"invalid");function he(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw A("steward commands require the steward Session Inbox path");return t.inboxPath}r(he,"requireInboxPath");function Pt(t,e="delivery id"){if(!Qi.test(t))throw A(`${e} must be a positive integer`);return t}r(Pt,"requireDeliveryId");function ln(t){let e=new Set;for(let n of t){if(Pt(n),e.has(n))throw A(`duplicate delivery id ${n}`);e.add(n)}return[...e]}r(ln,"normalizeDeliveryIds");function Vi(t){if(t.length===0)throw A("at least one delivery id is required");return ln(t)}r(Vi,"requireDeliveryIds");function Wi(t){if(!Bi.has(t))throw A("decision must be one of immediate, digest, suppress");return t}r(Wi,"requireDecision");function Yi(){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)}`}r(Yi,"generateRequestId");function un(t){if(t===void 0)return Yi();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 A("request id must be a UUID");return t}r(un,"requireRequestId");function U(){return new l("EMPTY_RESPONSE","steward response was empty",502)}r(U,"emptyResponse");var H=class{constructor(e){this.client=e}client;static{r(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw A("a decision reason is required");let s=(await this.graphql(Li,{input:{inboxPath:he(e),deliveryId:Pt(e.deliveryId),decision:{decision:Wi(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw U();return{state:s.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(Oi,{input:{inboxPath:he(e),deliveryId:Pt(e.deliveryId),forward:{requestId:un(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw U();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw A("a message body is required");let i=(await this.graphql(Mi,{input:{inboxPath:he(e),requestId:un(e.requestId),body:e.body,deliveryIds:ln(e.deliveryIds??[])}})).postStewardMessage?.message;if(!i)throw U();return i}async pending(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw A("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[m,f]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(f!==void 0&&(!Number.isSafeInteger(f)||f<=0))throw A(`${m} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw A("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let o=(await this.graphql($i,{inboxPath:he(e),input:i})).viewer?.stewardDigestPending;if(!o||!Array.isArray(o.edges))throw U();let a=o.windowSinceMs??0,c=o.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(c)||a<=0||c<=a)throw U();let u=o.edges.map(m=>m.node),d=o.pageInfo?.hasNextPage===!0&&o.pageInfo.endCursor?o.pageInfo.endCursor:null;return{items:u,nextCursor:d,windowSinceMs:a,windowUntilMs:c}}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw A("a digest run id is required");if((await this.graphql(ji,{input:{inboxPath:he(e),deliveryIds:Vi(e.deliveryIds),digestRunId:n}})).completeStewardBrief?.ok!==!0)throw U();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 U();if(i.errors?.length){let s=i.errors.map(c=>c.extensions?.code),o=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=o?Gi[o]:void 0;throw new l(o!==void 0&&a!==void 0?o:"GRAPHQL_ERROR",i.errors.map(c=>c.message).filter(c=>typeof c=="string").join("; ")||"GraphQL request failed",a??502,{errors:i.errors})}if(!i.data)throw U();return i.data}};function F(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(F,"isRecord");function _(t){return typeof t=="string"&&t.trim()!==""?t:void 0}r(_,"stringValue");function Je(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}r(Je,"numberValue");function Ze(t){return t===void 0?void 0:t.trim().toUpperCase()}r(Ze,"upper");function pn(t){return t.split("_")}r(pn,"pairParts");function Hi(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":pn(e)[1]?.toLowerCase()??""}r(Hi,"inferInstrumentType");function Ki(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}r(Ki,"inferUnderlyingType");function dn(t,e){let n=_(t.trading_pair)??_(t.tradingPair)??_(t.symbol);if(n===void 0)return;let i=_(t.type),s=pn(n),o=_(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=_(t.market)??_(t.exchange)??s[0]??"",c=_(t.quote)??s[s.length-1]??"",u=_(t.instrument_type)??_(t.instrumentType)??Hi(i,n),d=_(t.underlying_type)??_(t.underlyingType)??Ki(i);return{symbol:o,tradingPair:n,market:a,instrumentType:u,...d===void 0?{}:{underlyingType:d},quote:c,...i===void 0?{}:{type:i},..._(t.description)===void 0?{}:{description:_(t.description)},...Je(t.fee_rate)===void 0?Je(t.feeRate)===void 0?{}:{feeRate:Je(t.feeRate)}:{feeRate:Je(t.fee_rate)},..._(t.symbol_icon_url)===void 0?_(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:_(t.symbolIconUrl)}:{symbolIconUrl:_(t.symbol_icon_url)}}}r(dn,"normalizeCandidate");function zi(t){if(!F(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>F(s)?[dn(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let s of n){if(!F(s))continue;let o=_(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let c of a)if(!(!F(c)||!Array.isArray(c.pairs)))for(let u of c.pairs){if(!F(u))continue;let d=dn({...u,instrument_type:u.instrument_type??c.instrument_type},o);d!==void 0&&i.push(d)}}}return i}r(zi,"flattenResponse");function Ji(t,e){let n=e.trim();return t.tradingPair===n?!0:Ze(t.symbol)===Ze(n)}r(Ji,"matchesQuery");function Xe(t,e){return e===void 0||Ze(t)===Ze(e)}r(Xe,"matchesFilter");function Xi(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}r(Xi,"dedupe");function Zi(t){let e=F(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}}r(Zi,"resolveFilters");function er(t,e){let n=t.split("_"),i=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!s||!o||!a?{symbol:t,...e}:{symbol:o,market:e.market??i,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}r(er,"pairSearchParams");var K=class{constructor(e){this.client=e}client;static{r(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=F(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new l("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),o=Xi(zi(s)).filter(c=>Ji(c,i)).filter(c=>Xe(c.market,e.market)).filter(c=>Xe(c.instrumentType,e.instrumentType)).filter(c=>Xe(c.underlyingType,e.underlyingType)).filter(c=>Xe(c.quote,e.quote)),a=e.limit;return a!==void 0&&o.length>a?{query:i,candidates:o.slice(0,a),truncated:!0}:{query:i,candidates:o}}async resolve(e){let n=F(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,s=Zi(e),o=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:er(i,s),a=await this.search(o),c=i===void 0?a.candidates:a.candidates.filter(u=>u.tradingPair===i);if(c.length!==1)throw new l(c.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",c.length===0?`no canonical trading pair matched "${i??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,c.length===0?404:409,{query:i??o.symbol,candidateCount:c.length,candidates:c.slice(0,50),...c.length>50?{truncated:!0}:{}});return c[0]}};var tr=9223372036854775807n,nr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ir=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,mn=new TextEncoder,J=class{constructor(e){this.client=e}client;static{r(this,"ThesesResource")}async assetCandidates(e){this.client._requireAuth();let n=ye(e),i=await this.client._request("POST","/query",{body:{query:`query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
328
+ }`.trim(),ur=new Set(["immediate","digest","suppress"]),cr=/^[1-9][0-9]{0,18}$/;function v(t){return new l("INVALID_ARGUMENT",t,400)}r(v,"invalid");function Pe(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw v("steward commands require the steward Session Inbox path");return t.inboxPath}r(Pe,"requireInboxPath");function At(t,e="delivery id"){if(!cr.test(t))throw v(`${e} must be a positive integer`);return t}r(At,"requireDeliveryId");function bn(t){let e=new Set;for(let n of t){if(At(n),e.has(n))throw v(`duplicate delivery id ${n}`);e.add(n)}return[...e]}r(bn,"normalizeDeliveryIds");function lr(t){if(t.length===0)throw v("at least one delivery id is required");return bn(t)}r(lr,"requireDeliveryIds");function dr(t){if(!ur.has(t))throw v("decision must be one of immediate, digest, suppress");return t}r(dr,"requireDecision");function pr(){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)}`}r(pr,"generateRequestId");function gn(t){if(t===void 0)return pr();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 v("request id must be a UUID");return t}r(gn,"requireRequestId");function G(){return new l("EMPTY_RESPONSE","steward response was empty",502)}r(G,"emptyResponse");var Z=class{constructor(e){this.client=e}client;static{r(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw v("a decision reason is required");let s=(await this.graphql(ir,{input:{inboxPath:Pe(e),deliveryId:At(e.deliveryId),decision:{decision:dr(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw G();return{state:s.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(rr,{input:{inboxPath:Pe(e),deliveryId:At(e.deliveryId),forward:{requestId:gn(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw G();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw v("a message body is required");let i=(await this.graphql(sr,{input:{inboxPath:Pe(e),requestId:gn(e.requestId),body:e.body,deliveryIds:bn(e.deliveryIds??[])}})).postStewardMessage?.message;if(!i)throw G();return i}async pending(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw v("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[h,f]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(f!==void 0&&(!Number.isSafeInteger(f)||f<=0))throw v(`${h} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw v("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let o=(await this.graphql(or,{inboxPath:Pe(e),input:i})).viewer?.stewardDigestPending;if(!o||!Array.isArray(o.edges))throw G();let a=o.windowSinceMs??0,u=o.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u)||a<=0||u<=a)throw G();let c=o.edges.map(h=>h.node),d=o.pageInfo?.hasNextPage===!0&&o.pageInfo.endCursor?o.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 v("a digest run id is required");if((await this.graphql(ar,{input:{inboxPath:Pe(e),deliveryIds:lr(e.deliveryIds),digestRunId:n}})).completeStewardBrief?.ok!==!0)throw G();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 G();if(i.errors?.length){let s=i.errors.map(u=>u.extensions?.code),o=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=o?nr[o]:void 0;throw new l(o!==void 0&&a!==void 0?o:"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 G();return i.data}};function O(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(O,"isRecord");function _(t){return typeof t=="string"&&t.trim()!==""?t:void 0}r(_,"stringValue");function rt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}r(rt,"numberValue");function ot(t){return t===void 0?void 0:t.trim().toUpperCase()}r(ot,"upper");function Pn(t){return t.split("_")}r(Pn,"pairParts");function mr(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Pn(e)[1]?.toLowerCase()??""}r(mr,"inferInstrumentType");function hr(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}r(hr,"inferUnderlyingType");function _n(t,e){let n=_(t.trading_pair)??_(t.tradingPair)??_(t.symbol);if(n===void 0)return;let i=_(t.type),s=Pn(n),o=_(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=_(t.market)??_(t.exchange)??s[0]??"",u=_(t.quote)??s[s.length-1]??"",c=_(t.instrument_type)??_(t.instrumentType)??mr(i,n),d=_(t.underlying_type)??_(t.underlyingType)??hr(i);return{symbol:o,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:u,...i===void 0?{}:{type:i},..._(t.description)===void 0?{}:{description:_(t.description)},...rt(t.fee_rate)===void 0?rt(t.feeRate)===void 0?{}:{feeRate:rt(t.feeRate)}:{feeRate:rt(t.fee_rate)},..._(t.symbol_icon_url)===void 0?_(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:_(t.symbolIconUrl)}:{symbolIconUrl:_(t.symbol_icon_url)}}}r(_n,"normalizeCandidate");function fr(t){if(!O(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>O(s)?[_n(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let s of n){if(!O(s))continue;let o=_(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let u of a)if(!(!O(u)||!Array.isArray(u.pairs)))for(let c of u.pairs){if(!O(c))continue;let d=_n({...c,instrument_type:c.instrument_type??u.instrument_type},o);d!==void 0&&i.push(d)}}}return i}r(fr,"flattenResponse");function yr(t,e){let n=e.trim();return t.tradingPair===n?!0:ot(t.symbol)===ot(n)}r(yr,"matchesQuery");function st(t,e){return e===void 0||ot(t)===ot(e)}r(st,"matchesFilter");function gr(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}r(gr,"dedupe");function br(t){let e=O(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}}r(br,"resolveFilters");function _r(t,e){let n=t.split("_"),i=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!s||!o||!a?{symbol:t,...e}:{symbol:o,market:e.market??i,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}r(_r,"pairSearchParams");var ee=class{constructor(e){this.client=e}client;static{r(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=O(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new l("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),o=gr(fr(s)).filter(u=>yr(u,i)).filter(u=>st(u.market,e.market)).filter(u=>st(u.instrumentType,e.instrumentType)).filter(u=>st(u.underlyingType,e.underlyingType)).filter(u=>st(u.quote,e.quote)),a=e.limit;return a!==void 0&&o.length>a?{query:i,candidates:o.slice(0,a),truncated:!0}:{query:i,candidates:o}}async resolve(e){let n=O(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,s=br(e),o=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:_r(i,s),a=await this.search(o),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??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,u.length===0?404:409,{query:i??o.symbol,candidateCount:u.length,candidates:u.slice(0,50),...u.length>50?{truncated:!0}:{}});return u[0]}};var Tn="pageInfo { endCursor hasNextPage }",kn="__typename id slug displayName bio",Pr="__typename id username displayName bio",Sn="__typename id ticker name kind assetClass venue { id name }",En=`theses(input: $input) {
329
+ edges { cursor node { id latestRelease { thesisPublication { ${Y} } } } }
330
+ ${Tn}
331
+ }`,Rr=`query ToolkitPersonTheses($slug: String!, $input: ProfileThesisConnectionInput) {
332
+ scope: person(slug: $slug) { ${kn} ${En} }
333
+ }`,wr=`query ToolkitUserTheses($username: String!, $input: ProfileThesisConnectionInput) {
334
+ scope: publicUser(username: $username) { ${Pr} ${En} }
335
+ }`,Tr=`query ToolkitEntityTheses($id: ID!, $input: EntityThesisConnectionInput) {
336
+ market { scope: entity(input: { id: $id }) { ${Sn}
337
+ theses(input: $input) { edges { cursor node { ${Y} } } ${Tn} }
338
+ } }
339
+ }`,kr=`query ToolkitThesisPeople($query: String!) {
340
+ search: people(input: { query: $query, first: 50 }) {
341
+ edges { node { ${kn} } } pageInfo { hasNextPage }
342
+ }
343
+ }`,Sr=`query ToolkitThesisEntities($query: String!) {
344
+ market { search: entities(input: { query: $query, first: 50, byPrefix: false }) {
345
+ edges { node { ${Sn} } } pageInfo { hasNextPage }
346
+ } }
347
+ }`,Er=`query ToolkitRelatedTheses($id: ID!, $input: RelatedThesisInput) {
348
+ node(id: $id) { ... on Playbook { relatedTheses(input: $input) {
349
+ state nextCursor
350
+ edges { cursor node { itemKey score publication { ${Y} } } }
351
+ } } }
352
+ }`,Ar=["person","personName","user","ticker","entityId"];function An(t){if(!p(t))throw U("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 U("first must be an integer between 1 and 50");if(t.cursor!==void 0&&!N(t.cursor))throw U("cursor must be non-empty")}r(An,"validateThesisPageParams");function vr(t){An(t);let e=Ar.filter(n=>t[n]!==void 0);if(e.length!==1)throw U("Choose exactly one of person, personName, user, ticker or entityId");if(!N(t[e[0]]))throw U(`${e[0]} must be non-empty`);if(t.entityId!==void 0&&!k(t.entityId))throw U("entityId must be a positive int64 string");if(t.status!==void 0&&t.status!=="ACTIVE"&&t.status!=="ARCHIVED")throw U("status must be ACTIVE or ARCHIVED");if(t.status!==void 0&&(t.ticker!==void 0||t.entityId!==void 0))throw U("status applies only to author lists")}r(vr,"validateListThesesParams");async function vn(t,e){vr(e),t._requireAuth();let n={first:e.first??10,after:e.cursor},i=e.ticker===void 0?e.entityId:(await wn(t,Sr,e.ticker,"Entity")).id;if(i!==void 0){let u=await Re(t,Tr,{id:i,input:n});if(!p(u.market))throw T();return Rn(u.market.scope,c=>H(c)?{playbookId:c.playbookId,publication:c}:void 0)}let s={...n,status:e.status},o=e.personName===void 0?e.person:(await wn(t,kr,e.personName,"Person")).slug,a=o===void 0?await Re(t,wr,{username:e.user,input:s}):await Re(t,Rr,{slug:o,input:s});return Rn(a.scope,u=>{if(!k(u.id))return;let c=u.latestRelease;if(c===null)return{playbookId:u.id,publication:null};if(!p(c))return;let d=c.thesisPublication;if(!(d!==null&&!H(d)))return{playbookId:u.id,publication:d}})}r(vn,"listTheses");async function In(t,e,n={}){if(An(n),!k(e))throw U("id must be an internal positive int64 Playbook ID");t._requireAuth();let i=await Re(t,Er,{id:`Playbook:${e}`,input:{first:n.first??10,after:n.cursor}});if(i.node===null)throw vt();if(!p(i.node))throw T();let s=i.node.relatedTheses;if(!p(s)||!["GENERATING","READY","FAILED"].includes(s.state)||s.nextCursor!==null&&!N(s.nextCursor))throw T();for(let o of xn(s))if(!N(o.node.itemKey)||typeof o.node.score!="number"||!H(o.node.publication))throw T();return{state:s.state,edges:s.edges,nextCursor:s.nextCursor}}r(In,"relatedTheses");function Rn(t,e){if(t===null)throw vt();let n=Cn(t);if(!p(t)||!p(t.theses))throw T();let i=t.theses,s=xn(i).map(o=>{let a=e(o.node);if(a===void 0)throw T();return{cursor:o.cursor,node:a}});return{scope:n,edges:s,nextCursor:Ir(i)}}r(Rn,"thesisPage");async function wn(t,e,n,i){let s=await Re(t,e,{query:n}),o=p(s.market)?s.market.search:s.search;if(!p(o)||!Array.isArray(o.edges)||!p(o.pageInfo))throw T();let a=o.edges.map(c=>Cn(p(c)?c.node:void 0));if(!a.every(c=>c.__typename===i))throw T();let u=o.pageInfo.hasNextPage===!0;if(a.length===1&&!u)return a[0];throw a.length===0&&!u?vt():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})}r(wn,"resolveUnique");function Cn(t){if(!p(t)||!N(t.id))throw T();if(t.__typename==="Entity"){if(!["ticker","name","kind","assetClass"].every(n=>typeof t[n]=="string")||t.venue!==null&&(!p(t.venue)||!N(t.venue.id)||typeof t.venue.name!="string"))throw T()}else if(typeof t.displayName!="string"||typeof t.bio!="string"||!(t.__typename==="Person"&&N(t.slug)||t.__typename==="PublicUser"&&N(t.username)))throw T();let e={...t};return delete e.theses,e}r(Cn,"readScope");function xn(t){if(!Array.isArray(t.edges)||!t.edges.every(e=>p(e)&&N(e.cursor)&&p(e.node)))throw T();return t.edges}r(xn,"edges");function Ir(t){let e=t.pageInfo;if(!p(e)||typeof e.hasNextPage!="boolean"||e.hasNextPage&&!N(e.endCursor))throw T();return e.hasNextPage?e.endCursor:null}r(Ir,"nextCursor");async function Re(t,e,n){let i=await t._request("POST","/query",{body:{query:e,variables:n}});if(!p(i))throw T();if(i.errors!==void 0){if(!Array.isArray(i.errors))throw T();if(i.errors.length){let s=i.errors.flatMap(c=>p(c)&&typeof c.message=="string"?[c.message]:[]),o=new Set(i.errors.map(c=>p(c)&&p(c.extensions)?c.extensions.code:void 0)),[a]=o,u=o.size===1&&typeof a=="string"?Cr.get(a):void 0;throw new l(u===void 0?"GRAPHQL_ERROR":String(a),s.join("; ")||"GraphQL request failed",u??400,{errors:i.errors})}}if(!p(i.data))throw T();return i.data}r(Re,"graphql");var Cr=new Map([["NOT_FOUND",404],["PERMISSION_DENIED",403],["UNAUTHENTICATED",401]]);function N(t){return typeof t=="string"&&t.trim().length>0}r(N,"nonempty");function U(t){return new l("INVALID_ARGUMENT",t,400)}r(U,"argument");function T(){return new l("GRAPHQL_INVALID_RESPONSE","Invalid Thesis read response",502)}r(T,"invalid");function vt(){return new l("NOT_FOUND","No visible matching identity or Thesis found",404)}r(vt,"notFound");var xr=9223372036854775807n,qr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Nr=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,qn=new TextEncoder,ne=class{constructor(e){this.client=e}client;static{r(this,"ThesesResource")}list(e){return vn(this.client,e)}related(e,n={}){return In(this.client,e,n)}async assetCandidates(e){this.client._requireAuth();let n=Te(e),i=await this.client._request("POST","/query",{body:{query:`query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
325
353
  viewer { thesisAssetCandidates(input: $input) {
326
354
  mentions { quote ticker resolution stance candidates { entityId ticker name kind } }
327
355
  } }
328
- }`,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 s=i?.data,o=g(s)?s.viewer:void 0,a=g(o)?o.thesisAssetCandidates:void 0;if(!g(a)||!Array.isArray(a.mentions))throw p("asset candidates response must contain mentions");return{mentions:a.mentions.map((u,d)=>{if(!g(u)||typeof u.quote!="string"||typeof u.ticker!="string"||!["RESOLVED","AMBIGUOUS","UNRESOLVED"].includes(u.resolution)||!["UNKNOWN","BULLISH","BEARISH"].includes(u.stance)||!Array.isArray(u.candidates))throw p(`asset mention ${d} is invalid`);let m=u.candidates.map(f=>{if(!g(f)||typeof f.ticker!="string"||typeof f.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(f.kind))throw p(`asset mention ${d} has invalid candidate`);return{entityId:v(f.entityId,`asset mention ${d} candidate.entityId`),ticker:f.ticker,name:f.name,kind:f.kind}});return{...u,candidates:m}})}}async create(e){this.client._requireAuth();let n=rr(e);return z(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){return this.client._requireAuth(),ar(await this.client._request("GET",`/api/v1/theses/${S(e,"id")}`))}async getVersion(e,n){this.client._requireAuth();let i=S(e,"id"),s=S(n,"author_version_id"),o=z(await this.client._request("GET",`/api/v1/theses/${i}/versions/${s}`));if(o.thesis.id!==i||o.thesis.author_version_id!==s)throw p("version response must match the requested thesis and author version");return o}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw y("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw y("cursor must be a string");return cr(await this.client._request("GET",`/api/v1/theses/${S(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=or(n);return z(await this.client._request("PUT",`/api/v1/theses/${S(e,"id")}`,{body:i}))}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw y("params is required");let i=S(e,"id"),s=nt(n.visibility),o=z(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:s}}));if(o.thesis.id!==i||o.thesis.visibility!==s)throw p("visibility response must match the requested thesis and visibility");return o}async close(e,n){this.client._requireAuth();let i={expected_author_version_id:S(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(i.note=G(n.note,"note")),z(await this.client._request("POST",`/api/v1/theses/${S(e,"id")}/close`,{body:i}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${S(e,"id")}`);if(n===void 0)return{};if(!g(n)||Object.keys(n).length!==0)throw p("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=ye(e.body),i=e.mode===void 0?"reformat":lr(e.mode),s=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:i}});if(!g(s)||typeof s.body!="string")throw p("rewrite response must contain a string body");return{body:yn(s.body)}}};function rr(t){let e={request_id:hn(t.request_id),body:ye(t.body),title:kt(t.title??""),entity_ids:fn(t.entity_ids??[],"entity_ids"),visibility:nt(t.visibility??"public")};return t.tickers!==void 0&&(e.tickers=ur(t.tickers)),t.entity_stances!==void 0&&(e.entity_stances=sr(t.entity_stances,e.entity_ids)),e}r(rr,"createBody");function sr(t,e){if(!Array.isArray(t)||t.length>fe)throw y("entity_stances must contain at most 100 values");let n=new Set(e),i=new Set;return t.map((s,o)=>{if(!g(s))throw y(`entity_stances[${o}] must be an object`);let a=S(s.entity_id,`entity_stances[${o}].entity_id`);if(!n.has(a)||i.has(a))throw y("entity stance must reference one unique entity_id");if(i.add(a),!["unknown","bullish","bearish"].includes(s.stance))throw y(`entity_stances[${o}].stance is invalid`);return{entity_id:a,stance:s.stance}})}r(sr,"requireEntityStances");function or(t){return{request_id:hn(t.request_id),expected_author_version_id:S(t.expected_author_version_id,"expected_author_version_id"),body:ye(t.body),title:kt(t.title??""),entity_ids:fn(t.entity_ids??[],"entity_ids"),visibility:nt(t.visibility),editorial:t.editorial??!1}}r(or,"updateBody");function z(t){if(!g(t)||!g(t.thesis))throw p("response must contain thesis");let e=t.thesis,n={id:v(e.id,"thesis.id"),author_version_id:v(e.author_version_id,"thesis.author_version_id"),material_version_id:v(e.material_version_id,"thesis.material_version_id"),title:hr(e.title),body:yn(e.body),entity_ids:dr(e.entity_ids,"thesis.entity_ids"),visibility:mr(e.visibility),closed:tt(e.closed,"thesis.closed"),closing_note:pr(e.closing_note),author_kind:P(e.author_kind,"thesis.author_kind"),author_ref:P(e.author_ref,"thesis.author_ref")};if(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(!g(i))throw p("thesis.entity_stances contains invalid entry");let s=v(i.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(s))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:s,stance:i.stance}})}return{thesis:n}}r(z,"thesisResponse");function ar(t){let e=z(t);if(!g(t)||!g(t.author))throw p("response must contain author");let n=t.author,i={id:v(n.id,"author.id"),kind:P(n.kind,"author.kind"),display_name:P(n.display_name,"author.display_name"),avatar_url:P(n.avatar_url,"author.avatar_url"),username:P(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 s=t.entities.map((o,a)=>{if(!g(o))throw p(`entities[${a}] must be an object`);let c={id:v(o.id,`entities[${a}].id`),ticker:P(o.ticker,`entities[${a}].ticker`),name:P(o.name,`entities[${a}].name`),icon_url:P(o.icon_url,`entities[${a}].icon_url`),kind:P(o.kind,`entities[${a}].kind`)};if(c.id!==e.thesis.entity_ids[a])throw p("entities must preserve thesis.entity_ids order");return c});return{thesis:e.thesis,author:i,entities:s}}r(ar,"thesisGetResponse");function cr(t,e,n){if(!g(t)||!g(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw p("invalid Signal history response");let i=t.research,s={state:P(i.state,"research.state"),pending_work:et(i.pending_work,"research.pending_work"),read_complete:tt(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(s.last_attempt_ms=et(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(s.last_completed_ms=et(i.last_completed_ms,"research.last_completed_ms"));let o=t.entries.map(c=>{if(!g(c)||!g(c.signal)||!g(c.signal.source))throw p("entry must include a Signal and source");let u=c.signal,d=u.source,m=v(u.thesis_id,"signal.thesis_id");if(m!==e)throw p("Signal belongs to another Thesis");let f=Rt(c.cursor,"entry.cursor"),T={title:P(d.title,"source.title")};d.url!==void 0&&(T.url=P(d.url,"source.url")),d.published_at_ms!==void 0&&(T.published_at_ms=et(d.published_at_ms,"source.published_at_ms"));let x={id:v(u.id,"signal.id"),thesis_id:m,author_version_id:v(u.author_version_id,"signal.author_version_id"),statement_snapshot:Rt(u.statement_snapshot,"signal.statement_snapshot"),stance:P(u.stance,"signal.stance"),explanation:P(u.explanation,"signal.explanation"),information_kind:P(u.information_kind,"signal.information_kind"),source:T};if(u.evidence_excerpt!==void 0){if(!g(u.evidence_excerpt))throw p("invalid evidence excerpt");x.evidence_excerpt={text:Rt(u.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:tt(u.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:tt(u.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:v(c.feed_entry_id,"feed_entry_id"),cursor:f,signal:x}}),a=P(t.next_cursor,"next_cursor");if(a&&a!==o[o.length-1]?.cursor)throw p("next_cursor must match the final entry");return{research:s,entries:o,next_cursor:a}}r(cr,"thesisSignalsResponse");function et(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw p(e+" must be a nonnegative safe integer");return t}r(et,"responseNonnegativeInteger");function Rt(t,e){let n=P(t,e);if(!n.trim())throw p(e+" must be nonempty");return n}r(Rt,"responseNonemptyText");function hn(t){if(!nr.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw y("request_id must be a non-zero RFC 4122 UUID");return t}r(hn,"requireRequestID");function S(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw y(`${e} must be a positive int64 decimal string`);if(BigInt(t)>tr)throw y(`${e} must be a positive int64 decimal string`);return t}r(S,"requireID");var fe=100;function fn(t,e){if(!Array.isArray(t))throw y(`${e} must be an array`);if(t.length>fe)throw y(`${e} must contain at most ${fe} IDs`);return t.map((n,i)=>S(n,`${e}[${i}]`))}r(fn,"requireIDs");function ur(t){if(!Array.isArray(t))throw y("tickers must be an array");if(t.length>100)throw y("tickers must contain at most 100 values");return t.map((e,n)=>{let i=G(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw y(`tickers[${n}] must be non-empty`);return i})}r(ur,"requireTickers");function ye(t){let e=G(t,"body");if(e.trim().length===0)throw y("body must not be blank");if(mn.encode(e).byteLength>65536)throw y("body must be at most 65536 UTF-8 bytes");return e}r(ye,"requireBody");function kt(t){let e=G(t,"title");if(mn.encode(e).byteLength>500)throw y("title must be at most 500 UTF-8 bytes");return e}r(kt,"requireTitle");function nt(t){let e=G(t,"visibility");if(e!=="public"&&e!=="private")throw y("visibility must be public or private");return e}r(nt,"requireVisibility");function lr(t){let e=G(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw y("mode must be reformat, shorten, or enrich")}r(lr,"requireRewriteMode");function G(t,e){if(typeof t!="string")throw y(`${e} must be a string`);if(ir.test(t))throw y(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw y(`${e} must not contain NUL`);return t}r(G,"requireText");function v(t,e){if(typeof t=="number")throw p(`${e} must be a decimal string; numeric IDs are unsafe`);try{return S(t,e)}catch{throw p(`${e} must be a positive int64 decimal string`)}}r(v,"responseID");function dr(t,e){if(!Array.isArray(t))throw p(`${e} must be an array`);if(t.length>fe)throw p(`${e} must contain at most ${fe} IDs`);return t.map((n,i)=>v(n,`${e}[${i}]`))}r(dr,"responseIDs");function P(t,e){try{return G(t,e)}catch{throw p(`${e} must be valid text`)}}r(P,"responseText");function pr(t){try{return G(t,"note")}catch{throw p("thesis.closing_note must be valid text")}}r(pr,"responseClosingNote");function tt(t,e){if(typeof t!="boolean")throw p(`${e} must be boolean`);return t}r(tt,"responseBoolean");function mr(t){try{return nt(t)}catch{throw p("thesis.visibility must be public or private")}}r(mr,"responseVisibility");function yn(t){try{return ye(t)}catch{throw p("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}r(yn,"responseBody");function hr(t){try{return kt(t)}catch{throw p("response title must be valid text at most 500 UTF-8 bytes")}}r(hr,"responseTitle");function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(g,"isRecord");function y(t){return new l("INVALID_ARGUMENT",t,400)}r(y,"invalidArgument");function p(t){return new l("INVALID_RESPONSE",t,502)}r(p,"invalidResponse");var fr="https://api-llm.prd.alva.ai",yr="https://data-tools.prd.space.id";function wt(t){return typeof t=="object"&&t!==null}r(wt,"isRecord");function it(t,e){if(!wt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}r(it,"stringField");function gr(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=it(t,"code");i&&(e.code=i)}else if(wt(t)){let i=it(t,"code"),s=it(t,"name"),o=it(t,"message");i&&(e.code=i),s&&(e.name=s),o&&(e.message=o)}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}}r(gr,"describeCause");function br(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:s}=gr(wt(t)?t.cause:void 0);return s&&(n.cause=s),{message:i?`${e}; cause: ${i}`:e,details:n}}r(br,"describeFetchFailure");var rt=class{static{r(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_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;constructor(e){this.baseUrl=e.baseUrl??fr,this.arraysBaseUrl=e.arraysBaseUrl??yr,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 ke(this)}get run(){return this._run??=new we(this)}get deploy(){return this._deploy??=new Se(this)}get serviceAccount(){return this._serviceAccount??=new Te(this)}get release(){return this._release??=new Ae(this)}get feed(){return this._feed??=new Ee(this)}get automation(){return this._automation??=new Q(this)}get playbooks(){return this._playbooks??=new qe(this)}get secrets(){return this._secrets??=new xe(this)}get sdk(){return this._sdk??=new Ne(this)}get dataSkills(){return this._dataSkills??=new De(this)}get playbookSkills(){return this._playbookSkills??=new Ue(this)}get comments(){return this._comments??=new Fe(this)}get remix(){return this._remix??=new Ge(this)}get screenshot(){return this._screenshot??=new Le(this)}get user(){return this._user??=new Oe(this)}get trading(){return this._trading??=new Me(this)}get portfolio(){return this._portfolio??=new $e(this)}get arraysJwt(){return this._arraysJwt??=new je(this)}get notifications(){return this._notifications??=new Be(this)}get notificationPreferences(){return this._notificationPreferences??=new Qe(this)}get subscriptions(){return this._subscriptions??=new Ve(this)}get alerts(){return this._alerts??=new V(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new We(this)}get feedback(){return this._feedback??=new Ye(this)}get functions(){return this._functions??=new He(this)}get credits(){return this._credits??=new Ke(this)}get markets(){return this._markets??=new W(this)}get tradingPairs(){return this._tradingPairs??=new K(this)}get schedules(){return this._schedules??=new Y(this)}get steward(){return this._steward??=new H(this)}get theses(){return this._theses??=new J(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 forYou(){return this._forYou??=new B(this)}async _request(e,n,i){let o=`${i?.baseUrl??this.baseUrl}${n}`;if(i?.query){let C=new URLSearchParams;for(let[N,st]of Object.entries(i.query))st!=null&&C.set(N,String(st));let O=C.toString();O&&(o+=`?${O}`)}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 c;i?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",c=i.rawBody):i?.jsonBody!==void 0?(a["Content-Type"]="application/json",c=i.jsonBody):i?.body!==void 0&&(a["Content-Type"]="application/json",c=JSON.stringify(i.body));let u,d=i?.timeoutMs,m=i?.signal??this.signal;if(m?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let f=d!==void 0?new AbortController:void 0,T=!1,x,ge;f&&d!==void 0&&(m&&(ge=r(()=>f.abort(m.reason),"abortListener"),m.addEventListener("abort",ge,{once:!0})),x=setTimeout(()=>{T=!0,f.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let St={method:e,headers:a,body:c,signal:f?.signal??m};d!==void 0&&(St.timeout=d);try{u=await fetch(o,St)}catch(C){if(m?.aborted&&!T)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(T)throw new l("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let O=br(C);throw new l("NETWORK_ERROR",O.message,0,{method:e,path:n,...O.details})}finally{ge&&m&&m.removeEventListener("abort",ge),x!==void 0&&clearTimeout(x)}if(!u.ok){let C="";try{C=await Promise.resolve(u.text())}catch{C=""}if((u.headers.get("content-type")??"").includes("application/json")&&C)try{let N=JSON.parse(C);if(N.error)throw new l(N.error.code??"UNKNOWN",N.error.message??`HTTP ${u.status}`,u.status)}catch(N){if(N instanceof l)throw N}throw new l("UNKNOWN",`HTTP ${u.status}: ${C.slice(0,200)}`,u.status)}if(u.status===204)return;let Tt=(u.headers.get("content-type")??"").toLowerCase();return Tt.includes("application/json")||Tt.includes("+json")?u.json():u.arrayBuffer()}};var _r="0.31.0";dt();return kn(Pr);})();
356
+ }`,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 s=i?.data,o=g(s)?s.viewer:void 0,a=g(o)?o.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 h=c.candidates.map(f=>{if(!g(f)||typeof f.ticker!="string"||typeof f.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(f.kind))throw m(`asset mention ${d} has invalid candidate`);return{entityId:I(f.entityId,`asset mention ${d} candidate.entityId`),ticker:f.ticker,name:f.name,kind:f.kind}});return{...c,candidates:h}})}}async create(e){this.client._requireAuth();let n=Dr(e);return te(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){return this.client._requireAuth(),Fr(await this.client._request("GET",`/api/v1/theses/${E(e,"id")}`))}async getVersion(e,n){this.client._requireAuth();let i=E(e,"id"),s=E(n,"author_version_id"),o=te(await this.client._request("GET",`/api/v1/theses/${i}/versions/${s}`));if(o.thesis.id!==i||o.thesis.author_version_id!==s)throw m("version response must match the requested thesis and author version");return o}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw y("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw y("cursor must be a string");return Gr(await this.client._request("GET",`/api/v1/theses/${E(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=Lr(n);return te(await this.client._request("PUT",`/api/v1/theses/${E(e,"id")}`,{body:i}))}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw y("params is required");let i=E(e,"id"),s=ct(n.visibility),o=te(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:s}}));if(o.thesis.id!==i||o.thesis.visibility!==s)throw m("visibility response must match the requested thesis and visibility");return o}async close(e,n){this.client._requireAuth();let i={expected_author_version_id:E(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(i.note=M(n.note,"note")),te(await this.client._request("POST",`/api/v1/theses/${E(e,"id")}/close`,{body:i}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${E(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=Te(e.body),i=e.mode===void 0?"reformat":Mr(e.mode),s=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:i}});if(!g(s)||typeof s.body!="string")throw m("rewrite response must contain a string body");return{body:Un(s.body)}}};function Dr(t){let e={request_id:Nn(t.request_id),body:Te(t.body),title:Ct(t.title??""),entity_ids:Dn(t.entity_ids??[],"entity_ids"),visibility:ct(t.visibility??"public")};return t.tickers!==void 0&&(e.tickers=Or(t.tickers)),t.entity_stances!==void 0&&(e.entity_stances=Ur(t.entity_stances,e.entity_ids)),e}r(Dr,"createBody");function Ur(t,e){if(!Array.isArray(t)||t.length>we)throw y("entity_stances must contain at most 100 values");let n=new Set(e),i=new Set;return t.map((s,o)=>{if(!g(s))throw y(`entity_stances[${o}] must be an object`);let a=E(s.entity_id,`entity_stances[${o}].entity_id`);if(!n.has(a)||i.has(a))throw y("entity stance must reference one unique entity_id");if(i.add(a),!["unknown","bullish","bearish"].includes(s.stance))throw y(`entity_stances[${o}].stance is invalid`);return{entity_id:a,stance:s.stance}})}r(Ur,"requireEntityStances");function Lr(t){return{request_id:Nn(t.request_id),expected_author_version_id:E(t.expected_author_version_id,"expected_author_version_id"),body:Te(t.body),title:Ct(t.title??""),entity_ids:Dn(t.entity_ids??[],"entity_ids"),visibility:ct(t.visibility),editorial:t.editorial??!1}}r(Lr,"updateBody");function te(t){if(!g(t)||!g(t.thesis))throw m("response must contain thesis");let e=t.thesis,n={id:I(e.id,"thesis.id"),author_version_id:I(e.author_version_id,"thesis.author_version_id"),material_version_id:I(e.material_version_id,"thesis.material_version_id"),title:Qr(e.title),body:Un(e.body),entity_ids:$r(e.entity_ids,"thesis.entity_ids"),visibility:Br(e.visibility),closed:ut(e.closed,"thesis.closed"),closing_note:jr(e.closing_note),author_kind:P(e.author_kind,"thesis.author_kind"),author_ref:P(e.author_ref,"thesis.author_ref")};if(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 s=I(i.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(s))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:s,stance:i.stance}})}return{thesis:n}}r(te,"thesisResponse");function Fr(t){let e=te(t);if(!g(t)||!g(t.author))throw m("response must contain author");let n=t.author,i={id:I(n.id,"author.id"),kind:P(n.kind,"author.kind"),display_name:P(n.display_name,"author.display_name"),avatar_url:P(n.avatar_url,"author.avatar_url"),username:P(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 s=t.entities.map((o,a)=>{if(!g(o))throw m(`entities[${a}] must be an object`);let u={id:I(o.id,`entities[${a}].id`),ticker:P(o.ticker,`entities[${a}].ticker`),name:P(o.name,`entities[${a}].name`),icon_url:P(o.icon_url,`entities[${a}].icon_url`),kind:P(o.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:s}}r(Fr,"thesisGetResponse");function Gr(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,s={state:P(i.state,"research.state"),pending_work:at(i.pending_work,"research.pending_work"),read_complete:ut(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(s.last_attempt_ms=at(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(s.last_completed_ms=at(i.last_completed_ms,"research.last_completed_ms"));let o=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,h=I(c.thesis_id,"signal.thesis_id");if(h!==e)throw m("Signal belongs to another Thesis");let f=It(u.cursor,"entry.cursor"),A={title:P(d.title,"source.title")};d.url!==void 0&&(A.url=P(d.url,"source.url")),d.published_at_ms!==void 0&&(A.published_at_ms=at(d.published_at_ms,"source.published_at_ms"));let D={id:I(c.id,"signal.id"),thesis_id:h,author_version_id:I(c.author_version_id,"signal.author_version_id"),statement_snapshot:It(c.statement_snapshot,"signal.statement_snapshot"),stance:P(c.stance,"signal.stance"),explanation:P(c.explanation,"signal.explanation"),information_kind:P(c.information_kind,"signal.information_kind"),source:A};if(c.evidence_excerpt!==void 0){if(!g(c.evidence_excerpt))throw m("invalid evidence excerpt");D.evidence_excerpt={text:It(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:ut(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:ut(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:I(u.feed_entry_id,"feed_entry_id"),cursor:f,signal:D}}),a=P(t.next_cursor,"next_cursor");if(a&&a!==o[o.length-1]?.cursor)throw m("next_cursor must match the final entry");return{research:s,entries:o,next_cursor:a}}r(Gr,"thesisSignalsResponse");function at(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw m(e+" must be a nonnegative safe integer");return t}r(at,"responseNonnegativeInteger");function It(t,e){let n=P(t,e);if(!n.trim())throw m(e+" must be nonempty");return n}r(It,"responseNonemptyText");function Nn(t){if(!qr.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw y("request_id must be a non-zero RFC 4122 UUID");return t}r(Nn,"requireRequestID");function E(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw y(`${e} must be a positive int64 decimal string`);if(BigInt(t)>xr)throw y(`${e} must be a positive int64 decimal string`);return t}r(E,"requireID");var we=100;function Dn(t,e){if(!Array.isArray(t))throw y(`${e} must be an array`);if(t.length>we)throw y(`${e} must contain at most ${we} IDs`);return t.map((n,i)=>E(n,`${e}[${i}]`))}r(Dn,"requireIDs");function Or(t){if(!Array.isArray(t))throw y("tickers must be an array");if(t.length>100)throw y("tickers must contain at most 100 values");return t.map((e,n)=>{let i=M(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw y(`tickers[${n}] must be non-empty`);return i})}r(Or,"requireTickers");function Te(t){let e=M(t,"body");if(e.trim().length===0)throw y("body must not be blank");if(qn.encode(e).byteLength>65536)throw y("body must be at most 65536 UTF-8 bytes");return e}r(Te,"requireBody");function Ct(t){let e=M(t,"title");if(qn.encode(e).byteLength>500)throw y("title must be at most 500 UTF-8 bytes");return e}r(Ct,"requireTitle");function ct(t){let e=M(t,"visibility");if(e!=="public"&&e!=="private")throw y("visibility must be public or private");return e}r(ct,"requireVisibility");function Mr(t){let e=M(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw y("mode must be reformat, shorten, or enrich")}r(Mr,"requireRewriteMode");function M(t,e){if(typeof t!="string")throw y(`${e} must be a string`);if(Nr.test(t))throw y(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw y(`${e} must not contain NUL`);return t}r(M,"requireText");function I(t,e){if(typeof t=="number")throw m(`${e} must be a decimal string; numeric IDs are unsafe`);try{return E(t,e)}catch{throw m(`${e} must be a positive int64 decimal string`)}}r(I,"responseID");function $r(t,e){if(!Array.isArray(t))throw m(`${e} must be an array`);if(t.length>we)throw m(`${e} must contain at most ${we} IDs`);return t.map((n,i)=>I(n,`${e}[${i}]`))}r($r,"responseIDs");function P(t,e){try{return M(t,e)}catch{throw m(`${e} must be valid text`)}}r(P,"responseText");function jr(t){try{return M(t,"note")}catch{throw m("thesis.closing_note must be valid text")}}r(jr,"responseClosingNote");function ut(t,e){if(typeof t!="boolean")throw m(`${e} must be boolean`);return t}r(ut,"responseBoolean");function Br(t){try{return ct(t)}catch{throw m("thesis.visibility must be public or private")}}r(Br,"responseVisibility");function Un(t){try{return Te(t)}catch{throw m("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}r(Un,"responseBody");function Qr(t){try{return Ct(t)}catch{throw m("response title must be valid text at most 500 UTF-8 bytes")}}r(Qr,"responseTitle");function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(g,"isRecord");function y(t){return new l("INVALID_ARGUMENT",t,400)}r(y,"invalidArgument");function m(t){return new l("INVALID_RESPONSE",t,502)}r(m,"invalidResponse");var Vr=`mutation CreateCompanyNews($input: CompanyNewsFeedInput!) {
357
+ companyNews {
358
+ createFeed(input: $input) { id producer { id } }
359
+ }
360
+ }`,Yr={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 Hr(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)}}r(Hr,"validateCompanyNewsCreateParams");var ie=class{constructor(e){this.client=e}client;static{r(this,"CompanyNewsResource")}async create(e){this.client._requireAuth(),Hr(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:Vr,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",Yr[u]??502,{errors:i.errors})}let s=i?.data?.companyNews?.createFeed,o={feed_id:s?.id,cronjob_id:s?.producer?.id};if(typeof o!="object"||o===null||!("feed_id"in o)||!Ln(o.feed_id)||!("cronjob_id"in o)||!Ln(o.cronjob_id))throw new l("INVALID_RESPONSE","company news response must contain decimal int64 feed_id and cronjob_id strings",502);return{feed_id:o.feed_id,cronjob_id:o.cronjob_id}}};function Ln(t){return typeof t=="string"&&t.trim()===t&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}r(Ln,"validID");var Wr="https://api-llm.prd.alva.ai",Kr="https://data-tools.prd.space.id";function xt(t){return typeof t=="object"&&t!==null}r(xt,"isRecord");function lt(t,e){if(!xt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}r(lt,"stringField");function zr(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=lt(t,"code");i&&(e.code=i)}else if(xt(t)){let i=lt(t,"code"),s=lt(t,"name"),o=lt(t,"message");i&&(e.code=i),s&&(e.name=s),o&&(e.message=o)}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}}r(zr,"describeCause");function Jr(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:s}=zr(xt(t)?t.cause:void 0);return s&&(n.cause=s),{message:i?`${e}; cause: ${i}`:e,details:n}}r(Jr,"describeFetchFailure");var dt=class{static{r(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_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??Wr,this.arraysBaseUrl=e.arraysBaseUrl??Kr,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 Ie(this)}get run(){return this._run??=new Ce(this)}get deploy(){return this._deploy??=new xe(this)}get serviceAccount(){return this._serviceAccount??=new qe(this)}get release(){return this._release??=new Ne(this)}get feed(){return this._feed??=new Ue(this)}get automation(){return this._automation??=new K(this)}get playbooks(){return this._playbooks??=new Ge(this)}get secrets(){return this._secrets??=new Oe(this)}get sdk(){return this._sdk??=new Me(this)}get dataSkills(){return this._dataSkills??=new $e(this)}get playbookSkills(){return this._playbookSkills??=new je(this)}get comments(){return this._comments??=new Be(this)}get remix(){return this._remix??=new Qe(this)}get screenshot(){return this._screenshot??=new Ve(this)}get user(){return this._user??=new Ye(this)}get trading(){return this._trading??=new He(this)}get portfolio(){return this._portfolio??=new We(this)}get arraysJwt(){return this._arraysJwt??=new Ke(this)}get notifications(){return this._notifications??=new ze(this)}get notificationPreferences(){return this._notificationPreferences??=new Je(this)}get subscriptions(){return this._subscriptions??=new Xe(this)}get alerts(){return this._alerts??=new z(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new Ze(this)}get feedback(){return this._feedback??=new et(this)}get functions(){return this._functions??=new tt(this)}get credits(){return this._credits??=new nt(this)}get markets(){return this._markets??=new J(this)}get tradingPairs(){return this._tradingPairs??=new ee(this)}get schedules(){return this._schedules??=new X(this)}get steward(){return this._steward??=new Z(this)}get theses(){return this._theses??=new ne(this)}get companyNews(){return this._companyNews??=new ie(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 forYou(){return this._forYou??=new W(this)}async _request(e,n,i){let o=`${i?.baseUrl??this.baseUrl}${n}`;if(i?.query){let x=new URLSearchParams;for(let[L,pt]of Object.entries(i.query))pt!=null&&x.set(L,String(pt));let j=x.toString();j&&(o+=`?${j}`)}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,h=i?.signal??this.signal;if(h?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let f=d!==void 0?new AbortController:void 0,A=!1,D,ke;f&&d!==void 0&&(h&&(ke=r(()=>f.abort(h.reason),"abortListener"),h.addEventListener("abort",ke,{once:!0})),D=setTimeout(()=>{A=!0,f.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let qt={method:e,headers:a,body:u,signal:f?.signal??h};d!==void 0&&(qt.timeout=d);try{c=await fetch(o,qt)}catch(x){if(h?.aborted&&!A)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(A)throw new l("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let j=Jr(x);throw new l("NETWORK_ERROR",j.message,0,{method:e,path:n,...j.details})}finally{ke&&h&&h.removeEventListener("abort",ke),D!==void 0&&clearTimeout(D)}if(!c.ok){let x="";try{x=await Promise.resolve(c.text())}catch{x=""}if((c.headers.get("content-type")??"").includes("application/json")&&x)try{let L=JSON.parse(x);if(L.error)throw new l(L.error.code??"UNKNOWN",L.error.message??`HTTP ${c.status}`,c.status)}catch(L){if(L instanceof l)throw L}throw new l("UNKNOWN",`HTTP ${c.status}: ${x.slice(0,200)}`,c.status)}if(c.status===204)return;let Nt=(c.headers.get("content-type")??"").toLowerCase();return Nt.includes("application/json")||Nt.includes("+json")?c.json():c.arrayBuffer()}};var Xr="0.32.0-beta.1";bt();return jn(Zr);})();
329
361
  //# sourceMappingURL=browser.global.js.map