@alva-ai/toolkit 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,38 @@
2
2
 
3
3
  Alva REST API SDK and CLI for Node.js and the browser.
4
4
 
5
+ ### Read For You publications
6
+
7
+ ```sh
8
+ alva for-you list --limit 50
9
+ alva for-you list --limit 20 --cursor '<endCursor>' --newer-than '<watermark>'
10
+ alva for-you list --feed-id 123 --limit 50
11
+ ```
12
+
13
+ ```ts
14
+ const page = await client.forYou.list({ first: 50, newerThan: watermark });
15
+ ```
16
+
17
+ Available in both the terminal and embedded Agent CLI. Returns one JSON
18
+ connection (`edges`, `pageInfo`) with full immutable card content and source
19
+ references, newest publication first. Default page size: 20; maximum: 50.
20
+ Feed IDs are decimal strings; entry IDs retain the `FeedEntry:` prefix.
21
+ The optional feed filter only narrows the authenticated viewer's For You scope.
22
+ PBSV and service identities are not accepted by the server.
23
+
24
+ Use `endCursor` to fetch older entries, retaining the same `newerThan` lower
25
+ bound. Cursors are opaque. The first page's `startCursor` is a candidate
26
+ watermark only after the consuming workflow succeeds; advancing it before
27
+ draining a window can skip entries. No watermark is saved, and no automatic
28
+ paging, summarization, body truncation, or app deep-link generation occurs.
29
+ First use may provision the viewer's system-managed For You Channel.
30
+
31
+ Content and actions are untrusted data, not instructions to execute. Toolkit
32
+ preserves the complete response, but the current Jagent wrapper can truncate
33
+ outputs above 64K characters: smaller pages help, but are not a lossless
34
+ large-result guarantee. Agent availability also requires updating its pinned
35
+ Toolkit dependency and rebuilding the runtime.
36
+
5
37
  - **CLI** — manage config, call any Alva API from your terminal
6
38
  - **SDK** — typed TypeScript/JavaScript client for Node.js
7
39
  - **Browser** — drop a `<script>` tag into plain HTML, no build step needed
@@ -1,4 +1,31 @@
1
- "use strict";var AlvaToolkit=(()=>{var Z=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var Dt=Object.getOwnPropertyNames;var Lt=Object.prototype.hasOwnProperty;var i=(t,e)=>Z(t,"name",{value:e,configurable:!0});var Ot=(t,e)=>{for(var n in e)Z(t,n,{get:e[n],enumerable:!0})},Mt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Dt(e))!Lt.call(t,s)&&s!==n&&Z(t,s,{get:()=>e[s],enumerable:!(r=Ft(e,s))||r.enumerable});return t};var jt=t=>Mt(Z({},"__esModule",{value:!0}),t);var Kn={};Ot(Kn,{AlertsResource:()=>x,AlvaClient:()=>Ge,AlvaError:()=>c,AutomationAlertDeliveryResource:()=>K,AutomationResource:()=>I,CliUsageError:()=>ne,MarketsResource:()=>N,PBSV_UPDATE_MESSAGE:()=>tt,SUBSCRIBE_MANAGE_MESSAGE:()=>at,SUBSCRIBE_PROPOSE_MESSAGE:()=>st,SUBSCRIBE_RESULT_MESSAGE:()=>ot,SchedulesResource:()=>G,TradingPairsResource:()=>U,UDF_AUTH_REQUIRED_MESSAGE:()=>it,UDF_CONSENT_REQUEST_MESSAGE:()=>nt,UDF_CONSENT_RESPONSE_MESSAGE:()=>rt,UdfAuthRequiredError:()=>C,UdfConsentDeniedError:()=>j,UdfConsentRequiredError:()=>M,UdfConsentTimeoutError:()=>$,UdfError:()=>y,UdfExecutionError:()=>H,UdfFunctionDisabledError:()=>W,UdfFunctionNotFoundError:()=>Q,UdfInsufficientCredits:()=>B,UdfPidMismatchError:()=>v,UdfRateLimitedError:()=>V,UdfTokenExpiredError:()=>L,UdfTokenInvalidError:()=>O,UdfTransportError:()=>q,VERSION:()=>Jn,getViewerToken:()=>Y,installPlaybookRuntime:()=>je,mapUdfErrorResponse:()=>Oe,playbookIdFromToken:()=>Le,subscribe:()=>mt,udf:()=>yt});var y=class extends Error{static{i(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:r={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=r,this.status=s}},C=class extends y{static{i(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},L=class extends y{static{i(this,"UdfTokenExpiredError")}},O=class extends y{static{i(this,"UdfTokenInvalidError")}},v=class extends y{static{i(this,"UdfPidMismatchError")}},M=class extends y{static{i(this,"UdfConsentRequiredError")}},j=class extends y{static{i(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},$=class extends y{static{i(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},B=class extends y{static{i(this,"UdfInsufficientCredits")}},Q=class extends y{static{i(this,"UdfFunctionNotFoundError")}},W=class extends y{static{i(this,"UdfFunctionDisabledError")}},V=class extends y{static{i(this,"UdfRateLimitedError")}},H=class extends y{static{i(this,"UdfExecutionError")}},q=class extends y{static{i(this,"UdfTransportError")}},tt="alva:pbsv:update",nt="alva:udf:consent-request",rt="alva:udf:consent-response",it="alva:udf:auth-required",st="alva:subscribe:propose",ot="alva:subscribe:result",at="alva:subscribe:manage",lt="https://api-llm.prd.alva.ai",ct=300*1e3,D=null,b=null,De=lt,_=null,g=null,et=!1,ee=new Map,te=new Map,$t=i(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Bt=i(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),Le=i(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Bt(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),Y=i(()=>D,"getViewerToken"),w=i(()=>!!Y(),"isAuthenticated"),Qt=i(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),Wt=i(t=>{let e=new URLSearchParams(t.location.search);D=e.get("_pbsv"),b=e.get("parent_origin"),De=(e.get("api_origin")||lt).replace(/\/$/,""),_=Le(D),D&&Qt(t)},"parseBootParams"),ut=i(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Vt=i(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),Ht=i(t=>{let e=t;return{...e,result:Vt(e.result)}},"normalizeInvokeResponse"),dt=i(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),Oe=i((t,e)=>{let n=t.error?.code||"TRANSPORT",r=t.error?.message||n,s=dt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new L(r,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new O(r,o);case"PBSV_PID_MISMATCH":return new v(r,o);case"CONSENT_REQUIRED":return new M(r,o);case"INSUFFICIENT_CREDITS":return new B(r,o);case"FUNCTION_NOT_FOUND":return new Q(r,o);case"FUNCTION_DISABLED":return new W(r,o);case"RESOURCE_EXHAUSTED":return new V(r,o);case"EXECUTION_FAILED":return new H(r,o);default:return new q(r,o)}},"mapUdfErrorResponse"),Yt=i(t=>{if(!g||!b||t.origin!==b||t.source!==g.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===tt){typeof e.token=="string"&&e.token.length>0&&(D=e.token,_=Le(e.token));return}if(e.type===ot){if(typeof e.request_id!="string")return;let r=te.get(e.request_id);if(!r)return;clearTimeout(r.timer),te.delete(e.request_id),r.resolve($t(e.status));return}if(e.type!==rt||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"),pt=i(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),zt=i(()=>{if(!_)return null;let t=Number(_);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),Jt=i(async(t,e)=>{if(!g||!b)return"denied";let n=b,r=pt();return new Promise(s=>{let o=setTimeout(()=>{ee.delete(r),s("timeout")},ct);ee.set(r,{resolve:s,timer:o}),g?.parent.postMessage({type:nt,request_id:r,playbook_id:t,min_allowance:e},n)})},"requestConsent"),Kt=i(async t=>{if(!g||!b)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 r=b,s=pt();return new Promise(o=>{let l=setTimeout(()=>{te.delete(s),o("timeout")},ct);te.set(s,{resolve:o,timer:l}),g?.parent.postMessage({type:st,request_id:s,playbook_id:_,feed:{owner:e,name:n}},r)})},"proposeSubscribe"),Xt=i(()=>{!g||!b||g.parent.postMessage({type:at,playbook_id:_},b)},"manageSubscriptions"),mt={propose:Kt,manage:Xt},Zt=i(t=>{!g||!b||g.parent.postMessage({type:it,function_name:t},b)},"requestAuthentication"),Me=i(async(t,e,n=!1)=>{let r=Y();if(!r)throw new C;if(!_)throw new v("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=zt();if(!s)throw new v("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${De}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new q("Network error while invoking UDF.",{code:"TRANSPORT"})}let l=await ut(o);if(o.ok)return Ht(l);if(l.error?.code==="CONSENT_REQUIRED"&&!n){let a=dt(l),u=typeof a.playbook_id=="string"?a.playbook_id:_,d=typeof a.min_allowance_suggested=="number"?a.min_allowance_suggested:1,p=await Jt(u,d);if(p==="granted")return Me(t,e,!0);throw p==="timeout"?new $:new j}throw Oe(l,o.status)},"call"),en=i(async()=>{let t=Y();if(!t)throw new C;if(!_)throw new v("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${De}/api/v1/service/functions`);e.searchParams.set("playbook_id",_);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),r=await ut(n);if(!n.ok)throw Oe(r,n.status);let s=r.functions;return Array.isArray(s)?s:[]},"list"),Fe=i((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),tn=i(t=>{if(typeof t!="string")return t;let n=g?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),nn=i((t,e)=>{if(!g)throw new Error("Playbook runtime is not installed.");let n=tn(t),r=g.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",l=e.disabledLabel||"Sign in to run";return r.type="button",r.className="alva-udf-button",r.textContent=w()?s:l,r.disabled=!1,r.setAttribute("data-function-name",e.functionName),w()||r.setAttribute("aria-disabled","true"),r.addEventListener("click",async()=>{if(!w()){Zt(e.functionName);return}if(!r.disabled){r.disabled=!0,r.textContent=o,Fe(r,"alva:udf-button:loading",{functionName:e.functionName});try{let a=await Me(e.functionName,e.params??{});Fe(r,"alva:udf-button:result",{functionName:e.functionName,result:a})}catch(a){Fe(r,"alva:udf-button:error",{functionName:e.functionName,error:a})}finally{r.disabled=!1,r.textContent=w()?s:l,w()||r.setAttribute("aria-disabled","true")}}}),n.appendChild(r),r},"renderButton"),yt={call:Me,list:en,getViewerToken:Y,isAuthenticated:w,renderButton:nn,UdfError:y,UdfAuthRequiredError:C,UdfTokenExpiredError:L,UdfTokenInvalidError:O,UdfPidMismatchError:v,UdfConsentRequiredError:M,UdfConsentDeniedError:j,UdfConsentTimeoutError:$,UdfInsufficientCredits:B,UdfFunctionNotFoundError:Q,UdfFunctionDisabledError:W,UdfRateLimitedError:V,UdfExecutionError:H,UdfTransportError:q},je=i(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||et)return;g=e,et=!0,Wt(e),e.addEventListener("message",Yt);let n=e,r=n.alva||{};n.alva={...r,udf:yt,subscribe:mt}},"installPlaybookRuntime");var c=class extends Error{static{i(this,"AlvaError")}code;status;details;constructor(e,n,r,s){super(n),this.name="AlvaError",this.code=e,this.status=r,this.details=s}},ne=class extends Error{static{i(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function ft(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}i(ft,"isArrayBuffer");var ht=1;function rn(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let r=0,s=0,o=0;if(n>=194&&n<=223)r=1,s=128,o=n&31;else if(n>=224&&n<=239)r=2,s=2048,o=n&15;else if(n>=240&&n<=244)r=3,s=65536,o=n&7;else return!1;if(e+r>=t.length)return!1;for(let l=1;l<=r;l+=1){let a=t[e+l];if((a&192)!==128)return!1;o=o<<6|a&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=r+1}return!0}i(rn,"isValidUtf8");var re=class{constructor(e){this.client=e}client;static{i(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(!ft(n)||!rn(new Uint8Array(n)))return n;let r=new TextDecoder("utf-8").decode(n);try{return JSON.parse(r)}catch{return r}}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:ht}:{}}})}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:ht}:{}},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 gt="9007199254740991";function bt(t,e,n,r){let s=t.length+e,o=n.length+r;if(s!==o)return s>o;for(let l=0;l<s;l++){let a=l<t.length?t[l]:"0",u=l<n.length?n[l]:"0";if(a!==u)return a>u}return!1}i(bt,"scaledIntegerGreater");function sn(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,r=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+r).replace(/^0+/,"")||"0";if(o==="0")return!1;let l=s-r.length;return l>=0?bt(o,l,gt,0):bt(o,0,gt,-l)}i(sn,"numberOutsideSafeRange");function on(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(sn(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++}}i(on,"validateJSONNumberTokens");function $e(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((r,s)=>$e(r,`${e}[${s}]`,n));else{let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==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`);$e(o.value,`${e}.${s}`,n)}}n.delete(t)}}i($e,"assertPlainJSONData");function z(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");$e(t,"args",new Set);let e=JSON.stringify(t);return kt(e),e}i(z,"serializeStructuredArgs");function kt(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");on(t)}i(kt,"validateSerializedArgs");function J(t,e,n){let r=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(kt(n),r.push([e,n])),`{${r.map(([s,o])=>{let l=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${l}`}).join(",")}}`}i(J,"objectWithRawJSONField");var ie=class{constructor(e){this.client=e}client;static{i(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,z(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let r={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:r}:{jsonBody:J(r,"args",n)},timeoutMs:e.timeout_ms})}};var se=class{constructor(e){this.client=e}client;static{i(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,z(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let r={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:r}:{jsonBody:J(r,"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,z(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:r,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${r}`,{...n===void 0?{body:s}:{jsonBody:J(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 oe=class{constructor(e){this.client=e}client;static{i(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{i(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}})}};var ce=class{constructor(e){this.client=e}client;static{i(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=le(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=le(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=le(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=le(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 le(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}i(le,"requireFeedID");var an=`
1
+ "use strict";var AlvaToolkit=(()=>{var ne=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var $t=Object.prototype.hasOwnProperty;var i=(t,e)=>ne(t,"name",{value:e,configurable:!0});var Bt=(t,e)=>{for(var n in e)ne(t,n,{get:e[n],enumerable:!0})},Qt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jt(e))!$t.call(t,s)&&s!==n&&ne(t,s,{get:()=>e[s],enumerable:!(r=Mt(e,s))||r.enumerable});return t};var Wt=t=>Qt(ne({},"__esModule",{value:!0}),t);var ir={};Bt(ir,{AlertsResource:()=>U,AlvaClient:()=>De,AlvaError:()=>c,AutomationAlertDeliveryResource:()=>ee,AutomationResource:()=>F,CliUsageError:()=>se,ForYouResource:()=>N,MarketsResource:()=>G,PBSV_UPDATE_MESSAGE:()=>st,SUBSCRIBE_MANAGE_MESSAGE:()=>dt,SUBSCRIBE_PROPOSE_MESSAGE:()=>ct,SUBSCRIBE_RESULT_MESSAGE:()=>ut,SchedulesResource:()=>L,TradingPairsResource:()=>D,UDF_AUTH_REQUIRED_MESSAGE:()=>lt,UDF_CONSENT_REQUEST_MESSAGE:()=>ot,UDF_CONSENT_RESPONSE_MESSAGE:()=>at,UdfAuthRequiredError:()=>I,UdfConsentDeniedError:()=>Q,UdfConsentRequiredError:()=>B,UdfConsentTimeoutError:()=>W,UdfError:()=>f,UdfExecutionError:()=>J,UdfFunctionDisabledError:()=>H,UdfFunctionNotFoundError:()=>V,UdfInsufficientCredits:()=>Y,UdfPidMismatchError:()=>v,UdfRateLimitedError:()=>z,UdfTokenExpiredError:()=>j,UdfTokenInvalidError:()=>$,UdfTransportError:()=>x,VERSION:()=>rr,getViewerToken:()=>K,installPlaybookRuntime:()=>We,mapUdfErrorResponse:()=>Be,playbookIdFromToken:()=>$e,subscribe:()=>gt,udf:()=>bt});var f=class extends Error{static{i(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:r={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=r,this.status=s}},I=class extends f{static{i(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},j=class extends f{static{i(this,"UdfTokenExpiredError")}},$=class extends f{static{i(this,"UdfTokenInvalidError")}},v=class extends f{static{i(this,"UdfPidMismatchError")}},B=class extends f{static{i(this,"UdfConsentRequiredError")}},Q=class extends f{static{i(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},W=class extends f{static{i(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},Y=class extends f{static{i(this,"UdfInsufficientCredits")}},V=class extends f{static{i(this,"UdfFunctionNotFoundError")}},H=class extends f{static{i(this,"UdfFunctionDisabledError")}},z=class extends f{static{i(this,"UdfRateLimitedError")}},J=class extends f{static{i(this,"UdfExecutionError")}},x=class extends f{static{i(this,"UdfTransportError")}},st="alva:pbsv:update",ot="alva:udf:consent-request",at="alva:udf:consent-response",lt="alva:udf:auth-required",ct="alva:subscribe:propose",ut="alva:subscribe:result",dt="alva:subscribe:manage",pt="https://api-llm.prd.alva.ai",mt=300*1e3,M=null,b=null,je=pt,R=null,g=null,it=!1,re=new Map,ie=new Map,Yt=i(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Vt=i(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),$e=i(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Vt(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),K=i(()=>M,"getViewerToken"),q=i(()=>!!K(),"isAuthenticated"),Ht=i(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),zt=i(t=>{let e=new URLSearchParams(t.location.search);M=e.get("_pbsv"),b=e.get("parent_origin"),je=(e.get("api_origin")||pt).replace(/\/$/,""),R=$e(M),M&&Ht(t)},"parseBootParams"),ft=i(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Jt=i(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),Kt=i(t=>{let e=t;return{...e,result:Jt(e.result)}},"normalizeInvokeResponse"),yt=i(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),Be=i((t,e)=>{let n=t.error?.code||"TRANSPORT",r=t.error?.message||n,s=yt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new j(r,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new $(r,o);case"PBSV_PID_MISMATCH":return new v(r,o);case"CONSENT_REQUIRED":return new B(r,o);case"INSUFFICIENT_CREDITS":return new Y(r,o);case"FUNCTION_NOT_FOUND":return new V(r,o);case"FUNCTION_DISABLED":return new H(r,o);case"RESOURCE_EXHAUSTED":return new z(r,o);case"EXECUTION_FAILED":return new J(r,o);default:return new x(r,o)}},"mapUdfErrorResponse"),Xt=i(t=>{if(!g||!b||t.origin!==b||t.source!==g.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===st){typeof e.token=="string"&&e.token.length>0&&(M=e.token,R=$e(e.token));return}if(e.type===ut){if(typeof e.request_id!="string")return;let r=ie.get(e.request_id);if(!r)return;clearTimeout(r.timer),ie.delete(e.request_id),r.resolve(Yt(e.status));return}if(e.type!==at||typeof e.request_id!="string")return;let n=re.get(e.request_id);n&&(clearTimeout(n.timer),re.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),ht=i(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Zt=i(()=>{if(!R)return null;let t=Number(R);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),en=i(async(t,e)=>{if(!g||!b)return"denied";let n=b,r=ht();return new Promise(s=>{let o=setTimeout(()=>{re.delete(r),s("timeout")},mt);re.set(r,{resolve:s,timer:o}),g?.parent.postMessage({type:ot,request_id:r,playbook_id:t,min_allowance:e},n)})},"requestConsent"),tn=i(async t=>{if(!g||!b)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 r=b,s=ht();return new Promise(o=>{let l=setTimeout(()=>{ie.delete(s),o("timeout")},mt);ie.set(s,{resolve:o,timer:l}),g?.parent.postMessage({type:ct,request_id:s,playbook_id:R,feed:{owner:e,name:n}},r)})},"proposeSubscribe"),nn=i(()=>{!g||!b||g.parent.postMessage({type:dt,playbook_id:R},b)},"manageSubscriptions"),gt={propose:tn,manage:nn},rn=i(t=>{!g||!b||g.parent.postMessage({type:lt,function_name:t},b)},"requestAuthentication"),Qe=i(async(t,e,n=!1)=>{let r=K();if(!r)throw new I;if(!R)throw new v("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=Zt();if(!s)throw new v("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${je}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new x("Network error while invoking UDF.",{code:"TRANSPORT"})}let l=await ft(o);if(o.ok)return Kt(l);if(l.error?.code==="CONSENT_REQUIRED"&&!n){let a=yt(l),u=typeof a.playbook_id=="string"?a.playbook_id:R,d=typeof a.min_allowance_suggested=="number"?a.min_allowance_suggested:1,p=await en(u,d);if(p==="granted")return Qe(t,e,!0);throw p==="timeout"?new W:new Q}throw Be(l,o.status)},"call"),sn=i(async()=>{let t=K();if(!t)throw new I;if(!R)throw new v("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${je}/api/v1/service/functions`);e.searchParams.set("playbook_id",R);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),r=await ft(n);if(!n.ok)throw Be(r,n.status);let s=r.functions;return Array.isArray(s)?s:[]},"list"),Me=i((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),on=i(t=>{if(typeof t!="string")return t;let n=g?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),an=i((t,e)=>{if(!g)throw new Error("Playbook runtime is not installed.");let n=on(t),r=g.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",l=e.disabledLabel||"Sign in to run";return r.type="button",r.className="alva-udf-button",r.textContent=q()?s:l,r.disabled=!1,r.setAttribute("data-function-name",e.functionName),q()||r.setAttribute("aria-disabled","true"),r.addEventListener("click",async()=>{if(!q()){rn(e.functionName);return}if(!r.disabled){r.disabled=!0,r.textContent=o,Me(r,"alva:udf-button:loading",{functionName:e.functionName});try{let a=await Qe(e.functionName,e.params??{});Me(r,"alva:udf-button:result",{functionName:e.functionName,result:a})}catch(a){Me(r,"alva:udf-button:error",{functionName:e.functionName,error:a})}finally{r.disabled=!1,r.textContent=q()?s:l,q()||r.setAttribute("aria-disabled","true")}}}),n.appendChild(r),r},"renderButton"),bt={call:Qe,list:sn,getViewerToken:K,isAuthenticated:q,renderButton:an,UdfError:f,UdfAuthRequiredError:I,UdfTokenExpiredError:j,UdfTokenInvalidError:$,UdfPidMismatchError:v,UdfConsentRequiredError:B,UdfConsentDeniedError:Q,UdfConsentTimeoutError:W,UdfInsufficientCredits:Y,UdfFunctionNotFoundError:V,UdfFunctionDisabledError:H,UdfRateLimitedError:z,UdfExecutionError:J,UdfTransportError:x},We=i(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||it)return;g=e,it=!0,zt(e),e.addEventListener("message",Xt);let n=e,r=n.alva||{};n.alva={...r,udf:bt,subscribe:gt}},"installPlaybookRuntime");var c=class extends Error{static{i(this,"AlvaError")}code;status;details;constructor(e,n,r,s){super(n),this.name="AlvaError",this.code=e,this.status=r,this.details=s}},se=class extends Error{static{i(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]"}i(kt,"isArrayBuffer");var Pt=1;function ln(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let r=0,s=0,o=0;if(n>=194&&n<=223)r=1,s=128,o=n&31;else if(n>=224&&n<=239)r=2,s=2048,o=n&15;else if(n>=240&&n<=244)r=3,s=65536,o=n&7;else return!1;if(e+r>=t.length)return!1;for(let l=1;l<=r;l+=1){let a=t[e+l];if((a&192)!==128)return!1;o=o<<6|a&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=r+1}return!0}i(ln,"isValidUtf8");var oe=class{constructor(e){this.client=e}client;static{i(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)||!ln(new Uint8Array(n)))return n;let r=new TextDecoder("utf-8").decode(n);try{return JSON.parse(r)}catch{return r}}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:Pt}:{}}})}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:Pt}:{}},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 Rt="9007199254740991";function _t(t,e,n,r){let s=t.length+e,o=n.length+r;if(s!==o)return s>o;for(let l=0;l<s;l++){let a=l<t.length?t[l]:"0",u=l<n.length?n[l]:"0";if(a!==u)return a>u}return!1}i(_t,"scaledIntegerGreater");function cn(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,r=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+r).replace(/^0+/,"")||"0";if(o==="0")return!1;let l=s-r.length;return l>=0?_t(o,l,Rt,0):_t(o,0,Rt,-l)}i(cn,"numberOutsideSafeRange");function un(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(cn(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++}}i(un,"validateJSONNumberTokens");function Ye(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((r,s)=>Ye(r,`${e}[${s}]`,n));else{let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==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`);Ye(o.value,`${e}.${s}`,n)}}n.delete(t)}}i(Ye,"assertPlainJSONData");function X(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");Ye(t,"args",new Set);let e=JSON.stringify(t);return Et(e),e}i(X,"serializeStructuredArgs");function Et(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");un(t)}i(Et,"validateSerializedArgs");function Z(t,e,n){let r=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Et(n),r.push([e,n])),`{${r.map(([s,o])=>{let l=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${l}`}).join(",")}}`}i(Z,"objectWithRawJSONField");var ae=class{constructor(e){this.client=e}client;static{i(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,X(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let r={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:r}:{jsonBody:Z(r,"args",n)},timeoutMs:e.timeout_ms})}};var le=class{constructor(e){this.client=e}client;static{i(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,X(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let r={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:r}:{jsonBody:Z(r,"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,X(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:r,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${r}`,{...n===void 0?{body:s}:{jsonBody:Z(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 ce=class{constructor(e){this.client=e}client;static{i(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 ue=class{constructor(e){this.client=e}client;static{i(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}})}};var pe=class{constructor(e){this.client=e}client;static{i(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}i(de,"requireFeedID");var dn=`
2
+ query ToolkitForYou($input: FeedEntryConnectionInput) {
3
+ viewer {
4
+ forYou(input: $input) {
5
+ edges {
6
+ cursor
7
+ node {
8
+ id
9
+ feed { id }
10
+ major { id feedId number }
11
+ displayName source eventTimeMs publishedAtMs title body
12
+ actions { type label url prompt }
13
+ presentation {
14
+ card {
15
+ accentColor url thumbnailUrl footer
16
+ fields { label value inline }
17
+ }
18
+ }
19
+ tickers { symbol logoUrl sentiment }
20
+ media { type coverUrl url }
21
+ sources { type url iconUrl title subtitle description publishedAtMs }
22
+ }
23
+ }
24
+ pageInfo { startCursor endCursor hasNextPage hasPreviousPage }
25
+ }
26
+ }
27
+ }
28
+ `.trim();function k(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(k,"record");function pn(t){if(!k(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 r=t[n];if(r!==void 0&&(typeof r!="string"||!r.trim()))throw new Error(`${n} must be a non-empty cursor`)}if(t.feedId!==void 0&&!me(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}i(pn,"validateForYouListParams");function me(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}i(me,"isPositiveInt64");function S(){throw new c("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}i(S,"invalidResponse");function mn(t){if(!k(t)||!Array.isArray(t.edges)||!k(t.pageInfo))return S();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return S();for(let s of t.edges){if(!k(s)||typeof s.cursor!="string"||!s.cursor.trim()||!k(s.node))return S();let o=s.node;if(typeof o.id!="string"||!o.id.startsWith("FeedEntry:")||!me(o.id.slice(10))||!k(o.feed)||!me(o.feed.id)||!k(o.major)||typeof o.major.id!="string"||!me(o.major.feedId)||typeof o.title!="string"||typeof o.body!="string")return S()}let n=t.edges[0],r=t.edges[t.edges.length-1];return e.startCursor!==(n?.cursor??"")||e.endCursor!==(r?.cursor??"")||t.edges.length===0&&e.hasNextPage?S():t}i(mn,"connection");var N=class{constructor(e){this.client=e}client;static{i(this,"ForYouResource")}async list(e={}){pn(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:dn,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});if(!k(n))return S();if(n.errors!==void 0){if(!Array.isArray(n.errors))return S();if(n.errors.length>0){let r=n.errors.flatMap(s=>k(s)&&typeof s.message=="string"?[s.message]:[]);throw new c("GRAPHQL_ERROR",r.join("; ")||"GraphQL request failed",400,{errors:n.errors})}}if(!k(n.data)||!k(n.data.viewer)||n.data.viewer.forYou==null)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.forYou",502);return mn(n.data.viewer.forYou)}};var fn=`
2
29
  query ToolkitAutomationAlertDelivery($automationId: ID!) {
3
30
  automation(id: $automationId) {
4
31
  alertDelivery {
@@ -8,7 +35,7 @@ query ToolkitAutomationAlertDelivery($automationId: ID!) {
8
35
  }
9
36
  }
10
37
  }
11
- `.trim(),ln=`
38
+ `.trim(),yn=`
12
39
  mutation ToolkitUpdateAutomationAlertDelivery(
13
40
  $input: UpdateAutomationAlertDeliveryInput!
14
41
  $includeAlvaChannels: Boolean!
@@ -23,7 +50,7 @@ mutation ToolkitUpdateAutomationAlertDelivery(
23
50
  }
24
51
  }
25
52
  }
26
- `.trim(),I=class{constructor(e){this.client=e;this.delivery=new K(e)}client;static{i(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=cn(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=ue(e.id);if(!un(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)}},K=class{constructor(e){this.client=e}client;static{i(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=ue(e.id),s=(await this.graphql(an,{automationId:n})).automation?.alertDelivery;if(!s)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=ue(e.id),r=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!r&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=r?dn(e.alvaChannelIds??[]):void 0,a=(await this.graphql(ln,{input:{automationId:n,...r?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:r,includeEmail:s})).updateAutomationAlertDelivery;if(!a)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return a}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!r)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(r.errors&&r.errors.length>0)throw new c("GRAPHQL_ERROR",pn(r.errors),400,{errors:r.errors});if(!r.data)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};function cn(t){if(typeof t=="string")return ue(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}i(cn,"requireAutomationID");function ue(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}i(ue,"requireAutomationIDString");function un(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}i(un,"hasAutomationUpdate");function dn(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}i(dn,"uniqueAlvaChannelIDs");function pn(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"}i(pn,"graphQLErrorMessage");var _t=["public","private","paid"];var de=class{constructor(e){this.client=e}client;static{i(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 c("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let r=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let l=await this.listByOwner({owner:r,cursor:o,limit:100}),a=l.items.find(u=>u.name===s);if(a)return a;if(!l.has_next||!l.next_cursor)return null;o=l.next_cursor}}throw new c("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 r=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=mn(this.client.baseUrl);return{playbooks:(r.playbooks??[]).map(o=>yn(o,s)),has_next:r.has_next??!1}}async setVisibility(e){if(!_t.includes(e.visibility))throw new c("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${_t.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function mn(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let r=n[1].toLowerCase();return r==="prd"?"https://alva.ai":`https://${r}.alva.ai`}}catch{}return"https://alva.ai"}i(mn,"webOriginFromApiBase");function yn(t,e){let n=t.creator?.name??"",r=t.name??"",s=n&&r?`${n}/${r}`:r,o=n&&r?`/u/${n}/playbooks/${r}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:r,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??""}}i(yn,"toAgentPlaybook");var pe=class{constructor(e){this.client=e}client;static{i(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{i(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 Rt=[{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 Pt(t,e){return Rt.find(n=>n.skill===t&&n.file===e)}i(Pt,"getSkillEndpointMetadata");function Be(t){return Rt.filter(e=>e.skill===t)}i(Be,"listSkillEndpointMetadata");var ye=class{constructor(e){this.client=e}client;static{i(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...vt(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=Be(e.name);return{...s,...vt(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=Pt(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function vt(t){let e=Be(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}i(vt,"metadataSummaryForSkill");function Et(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}}i(Et,"normalizePlaybookSkillSummary");function At(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new c("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}i(At,"parsePlaybookSkillId");var fe=class{constructor(e){this.client=e}client;static{i(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(Et)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:r}=At(e),s=encodeURIComponent(n),o=encodeURIComponent(r),a=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!a)throw new c("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...Et(a),files:a.files??[]}}async file(e,n){let{username:r,name:s}=At(e),o=encodeURIComponent(r),l=encodeURIComponent(s),a=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${l}/files/${a}`)).data?.[0];if(!d)throw new c("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var he=class{constructor(e){this.client=e}client;static{i(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{i(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var be=class{constructor(e){this.client=e}client;static{i(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 ke=class{constructor(e){this.client=e}client;static{i(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var _e=class{constructor(e){this.client=e}client;static{i(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 Re=class{constructor(e){this.client=e}client;static{i(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 Pe=class{constructor(e){this.client=e}client;static{i(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 ve=class{constructor(e){this.client=e}client;static{i(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:fn(e)})}};function fn(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}i(fn,"buildQuery");var Ee=class{constructor(e){this.client=e}client;static{i(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 Ae=class{constructor(e){this.client=e}client;static{i(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 x=class{constructor(e){this.client=e}client;static{i(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 Se=class{constructor(e){this.client=e}client;static{i(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:St(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:St(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 St(t){return`{"session_id":${Tt(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${Tt(t.target_id)}}`}i(St,"mutationBody");function Tt(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new c("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 c("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}i(Tt,"idLiteral");var Te=class{constructor(e){this.client=e}client;static{i(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var we=class{constructor(e){this.client=e}client;static{i(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:gn(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 Qe(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>Qe(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:hn(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 Qe(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=wt(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),r=wt(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),r!==void 0&&(e.updated_at_ms=r),e}i(Qe,"normalizeAllowance");function hn(t){let e=Qe(t);if(!e)throw new Error("allowance response missing allowance");return e}i(hn,"requireAllowance");function wt(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,r=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(r)?r:0)/1e6)}i(wt,"timestampMs");function gn(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}i(gn,"parseResultPayload");var bn=`
53
+ `.trim(),F=class{constructor(e){this.client=e;this.delivery=new ee(e)}client;static{i(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=hn(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(!gn(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)}},ee=class{constructor(e){this.client=e}client;static{i(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=fe(e.id),s=(await this.graphql(fn,{automationId:n})).automation?.alertDelivery;if(!s)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=fe(e.id),r=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!r&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=r?bn(e.alvaChannelIds??[]):void 0,a=(await this.graphql(yn,{input:{automationId:n,...r?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:r,includeEmail:s})).updateAutomationAlertDelivery;if(!a)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return a}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!r)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(r.errors&&r.errors.length>0)throw new c("GRAPHQL_ERROR",kn(r.errors),400,{errors:r.errors});if(!r.data)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};function hn(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}i(hn,"requireAutomationID");function fe(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}i(fe,"requireAutomationIDString");function gn(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}i(gn,"hasAutomationUpdate");function bn(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}i(bn,"uniqueAlvaChannelIDs");function kn(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"}i(kn,"graphQLErrorMessage");var vt=["public","private","paid"];var ye=class{constructor(e){this.client=e}client;static{i(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 c("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let r=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let l=await this.listByOwner({owner:r,cursor:o,limit:100}),a=l.items.find(u=>u.name===s);if(a)return a;if(!l.has_next||!l.next_cursor)return null;o=l.next_cursor}}throw new c("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 r=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=Pn(this.client.baseUrl);return{playbooks:(r.playbooks??[]).map(o=>Rn(o,s)),has_next:r.has_next??!1}}async setVisibility(e){if(!vt.includes(e.visibility))throw new c("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${vt.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Pn(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let r=n[1].toLowerCase();return r==="prd"?"https://alva.ai":`https://${r}.alva.ai`}}catch{}return"https://alva.ai"}i(Pn,"webOriginFromApiBase");function Rn(t,e){let n=t.creator?.name??"",r=t.name??"",s=n&&r?`${n}/${r}`:r,o=n&&r?`/u/${n}/playbooks/${r}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:r,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??""}}i(Rn,"toAgentPlaybook");var he=class{constructor(e){this.client=e}client;static{i(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 ge=class{constructor(e){this.client=e}client;static{i(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 At=[{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 St(t,e){return At.find(n=>n.skill===t&&n.file===e)}i(St,"getSkillEndpointMetadata");function Ve(t){return At.filter(e=>e.skill===t)}i(Ve,"listSkillEndpointMetadata");var be=class{constructor(e){this.client=e}client;static{i(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...Tt(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=Ve(e.name);return{...s,...Tt(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=St(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function Tt(t){let e=Ve(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}i(Tt,"metadataSummaryForSkill");function wt(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}}i(wt,"normalizePlaybookSkillSummary");function Ct(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new c("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}i(Ct,"parsePlaybookSkillId");var ke=class{constructor(e){this.client=e}client;static{i(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(wt)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:r}=Ct(e),s=encodeURIComponent(n),o=encodeURIComponent(r),a=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!a)throw new c("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...wt(a),files:a.files??[]}}async file(e,n){let{username:r,name:s}=Ct(e),o=encodeURIComponent(r),l=encodeURIComponent(s),a=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${l}/files/${a}`)).data?.[0];if(!d)throw new c("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var Pe=class{constructor(e){this.client=e}client;static{i(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 Re=class{constructor(e){this.client=e}client;static{i(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var _e=class{constructor(e){this.client=e}client;static{i(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 Ee=class{constructor(e){this.client=e}client;static{i(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var ve=class{constructor(e){this.client=e}client;static{i(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 Ae=class{constructor(e){this.client=e}client;static{i(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 Se=class{constructor(e){this.client=e}client;static{i(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 Te=class{constructor(e){this.client=e}client;static{i(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:_n(e)})}};function _n(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}i(_n,"buildQuery");var we=class{constructor(e){this.client=e}client;static{i(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 Ce=class{constructor(e){this.client=e}client;static{i(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 U=class{constructor(e){this.client=e}client;static{i(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 qe=class{constructor(e){this.client=e}client;static{i(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:qt(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:qt(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 qt(t){return`{"session_id":${It(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${It(t.target_id)}}`}i(qt,"mutationBody");function It(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new c("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 c("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}i(It,"idLiteral");var Ie=class{constructor(e){this.client=e}client;static{i(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var xe=class{constructor(e){this.client=e}client;static{i(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:vn(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 He(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>He(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:En(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 He(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=xt(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),r=xt(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),r!==void 0&&(e.updated_at_ms=r),e}i(He,"normalizeAllowance");function En(t){let e=He(t);if(!e)throw new Error("allowance response missing allowance");return e}i(En,"requireAllowance");function xt(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,r=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(r)?r:0)/1e6)}i(xt,"timestampMs");function vn(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}i(vn,"parseResultPayload");var An=`
27
54
  query ToolkitCreditWallet {
28
55
  viewer {
29
56
  creditWallet {
@@ -33,7 +60,7 @@ query ToolkitCreditWallet {
33
60
  }
34
61
  }
35
62
  }
36
- `.trim(),kn=`
63
+ `.trim(),Sn=`
37
64
  query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
38
65
  viewer {
39
66
  creditWallet {
@@ -65,7 +92,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
65
92
  }
66
93
  }
67
94
  }
68
- `.trim();function _n(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"}i(_n,"graphQLErrorMessage");var Ce=class{constructor(e){this.client=e}client;static{i(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(bn)).viewer?.creditWallet;if(!n)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return n}async items(e){this.client._requireAuth();let r=(await this.graphql(kn,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!r)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return r}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors&&r.errors.length>0)throw new c("GRAPHQL_ERROR",_n(r.errors),400,{errors:r.errors});if(!r.data)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var Rn=["Q1","Q2","Q3","Q4"],Pn=["latest-completed","next-confirmed"],vn=`
95
+ `.trim();function Tn(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"}i(Tn,"graphQLErrorMessage");var Ne=class{constructor(e){this.client=e}client;static{i(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(An)).viewer?.creditWallet;if(!n)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return n}async items(e){this.client._requireAuth();let r=(await this.graphql(Sn,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!r)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return r}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors&&r.errors.length>0)throw new c("GRAPHQL_ERROR",Tn(r.errors),400,{errors:r.errors});if(!r.data)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var wn=["Q1","Q2","Q3","Q4"],Cn=["latest-completed","next-confirmed"],qn=`
69
96
  query ToolkitCompanyNarrative($ticker: String!) {
70
97
  market {
71
98
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -91,7 +118,7 @@ query ToolkitCompanyNarrative($ticker: String!) {
91
118
  }
92
119
  }
93
120
  }
94
- `.trim(),En=`
121
+ `.trim(),In=`
95
122
  query ToolkitCompanyEarningsCatalog($ticker: String!) {
96
123
  market {
97
124
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -122,7 +149,7 @@ query ToolkitCompanyEarningsCatalog($ticker: String!) {
122
149
  }
123
150
  }
124
151
  }
125
- `.trim(),An=`
152
+ `.trim(),xn=`
126
153
  query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
127
154
  market {
128
155
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -192,7 +219,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
192
219
  }
193
220
  }
194
221
  }
195
- `.trim();function Sn(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"}i(Sn,"graphQLErrorMessage");function We(t){let e=t.trim().toUpperCase();if(!e)throw new c("INVALID_ARGUMENT","ticker is required",400);return e}i(We,"normalizedTicker");var N=class{constructor(e){this.client=e}client;static{i(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=We(e),s=(await this.graphql(vn,{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=We(e),s=(await this.graphql(En,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);if(!s.earningsPeriods)throw new c("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=We(e.ticker),r=e.event,s=e.fiscalYear,o=e.fiscalQuarter;if(r!==void 0&&(s!==void 0||o!==void 0))throw new c("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(s===void 0!=(o===void 0))throw new c("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(r!==void 0&&!Pn.includes(r))throw new c("INVALID_ARGUMENT",`Unknown earnings event selector: ${r}`,400);if(s!==void 0&&(!Number.isInteger(s)||s<1900||s>9999))throw new c("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!Rn.includes(o))throw new c("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let a,u;if(s!==void 0&&o!==void 0)a=s,u=o;else{let R=r??"latest-completed",F=await this.earningsPeriods(n),S=this.selectPeriod(F,R,n);a=S.fiscalYear,u=S.fiscalQuarter}let p=(await this.graphql(An,{ticker:n,input:{fiscalYear:a,fiscalQuarter:u}})).market?.entity;if(!p)throw this.notFound(n);if(!p.earnings)throw new c("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${p.ticker} FY${a} ${u}`,404,{ticker:p.ticker,fiscalYear:a,fiscalQuarter:u});return{ticker:p.ticker,...p.earnings}}selectPeriod(e,n,r){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let s=e.periods.filter(o=>o.status==="UPCOMING").sort((o,l)=>o.earningsDate.localeCompare(l.earningsDate));if(s.length>0)return s[0]}throw new c("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${n} earnings event is available for ${r}`,404,{ticker:r,event:n})}notFound(e){return new c("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(r.errors&&r.errors.length>0)throw new c("GRAPHQL_ERROR",Sn(r.errors),400,{errors:r.errors});if(!r.data)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var It=`
222
+ `.trim();function Nn(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"}i(Nn,"graphQLErrorMessage");function ze(t){let e=t.trim().toUpperCase();if(!e)throw new c("INVALID_ARGUMENT","ticker is required",400);return e}i(ze,"normalizedTicker");var G=class{constructor(e){this.client=e}client;static{i(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=ze(e),s=(await this.graphql(qn,{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=ze(e),s=(await this.graphql(In,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);if(!s.earningsPeriods)throw new c("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=ze(e.ticker),r=e.event,s=e.fiscalYear,o=e.fiscalQuarter;if(r!==void 0&&(s!==void 0||o!==void 0))throw new c("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(s===void 0!=(o===void 0))throw new c("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(r!==void 0&&!Cn.includes(r))throw new c("INVALID_ARGUMENT",`Unknown earnings event selector: ${r}`,400);if(s!==void 0&&(!Number.isInteger(s)||s<1900||s>9999))throw new c("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!wn.includes(o))throw new c("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let a,u;if(s!==void 0&&o!==void 0)a=s,u=o;else{let _=r??"latest-completed",O=await this.earningsPeriods(n),w=this.selectPeriod(O,_,n);a=w.fiscalYear,u=w.fiscalQuarter}let p=(await this.graphql(xn,{ticker:n,input:{fiscalYear:a,fiscalQuarter:u}})).market?.entity;if(!p)throw this.notFound(n);if(!p.earnings)throw new c("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${p.ticker} FY${a} ${u}`,404,{ticker:p.ticker,fiscalYear:a,fiscalQuarter:u});return{ticker:p.ticker,...p.earnings}}selectPeriod(e,n,r){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let s=e.periods.filter(o=>o.status==="UPCOMING").sort((o,l)=>o.earningsDate.localeCompare(l.earningsDate));if(s.length>0)return s[0]}throw new c("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${n} earnings event is available for ${r}`,404,{ticker:r,event:n})}notFound(e){return new c("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(r.errors&&r.errors.length>0)throw new c("GRAPHQL_ERROR",Nn(r.errors),400,{errors:r.errors});if(!r.data)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var Ut=`
196
223
  id
197
224
  channel { id }
198
225
  name
@@ -206,22 +233,22 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
206
233
  nextFireAtMs
207
234
  createdAtMs
208
235
  updatedAtMs
209
- `,Tn=`
236
+ `,Fn=`
210
237
  query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
211
238
  viewer { channel(id: $channelId) {
212
239
  schedules(input: { first: 64, after: $after }) {
213
- edges { node { ${It} } }
240
+ edges { node { ${Ut} } }
214
241
  pageInfo { hasNextPage endCursor }
215
242
  }
216
243
  } }
217
- }`.trim(),Ve=`
244
+ }`.trim(),Je=`
218
245
  mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
219
246
  updateChannelSchedule(input: $input) {
220
- schedule { ${It} }
247
+ schedule { ${Ut} }
221
248
  deleted
222
249
  }
223
- }`.trim(),wn=`
250
+ }`.trim(),Un=`
224
251
  query ToolkitAgentChannel {
225
252
  viewer { channels { id kind } }
226
- }`.trim(),Cn=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,qn=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,In=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,xn={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},G=class{constructor(e){this.client=e}client;static{i(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Ye(e.channelId),r=[],s=null,o=new Set;for(;;){let a=(await this.graphql(Tn,{channelId:n,after:s})).viewer?.channel?.schedules;if(!a?.edges)throw qt();for(let d of a.edges){if(!d?.node)throw f();r.push(He(d.node))}if(a.pageInfo?.hasNextPage!==!0)return r;let u=a.pageInfo.endCursor;if(!u||o.has(u))throw f();o.add(u),s=u}}async put(e){this.client._requireAuth();let n={channelId:Ye(e.channelId),name:xt(e.name),definition:{...Nn(e.rule,e.bounds),message:{text:Fn(e.text)}}},s=(await this.graphql(Ve,{input:n})).updateChannelSchedule?.schedule;if(!s)throw f();return He(s)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.graphql(Ve,{input:{...Ct(e),lifecycle:"REMOVED"}})).updateChannelSchedule?.deleted!==!0)throw f()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(wn)).viewer?.channels?.find(r=>r.kind==="AGENT")?.id;if(!n)throw qt();return n}async manage(e,n){this.client._requireAuth();let s=(await this.graphql(Ve,{input:{...Ct(n),lifecycle:e}})).updateChannelSchedule?.schedule;if(!s)throw f();return He(s)}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors?.length){let s=r.errors.map(d=>d.extensions?.code),l=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=l?xn[l]:void 0,u=l!==void 0&&a!==void 0?l:"GRAPHQL_ERROR";throw new c(u,r.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",a??502,{errors:r.errors})}if(!r.data)throw f();return r.data}};function Nn(t,e){let n=Gn(e);switch(t.kind){case"after":if(n)throw h("after does not accept recurring bounds");let r=Date.now()+Nt(t.duration,1),s=Math.ceil(r/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw h("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw h("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:ze(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Dn(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw h("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}i(Nn,"ruleInput");function Gn(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=ze(t.startsAt)),t.until!==void 0&&(e.untilMs=ze(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw h("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}i(Gn,"boundsInput");function He(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw f();let r=t.bounds??{},s=t.message??{},o={name:t.name,rule:Un(t.rule),bounds:{...r.startsAtMs!=null?{startsAt:A(r.startsAtMs,!0)}:{},...r.untilMs!=null?{until:A(r.untilMs,!0)}:{},...r.maxOccurrences!=null?{maxOccurrences:Je(r.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:Je(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:A(t.nextFireAtMs,!0)}:{},createdAt:A(t.createdAtMs),updatedAt:A(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw f();let a={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!a)throw f();o.failure={code:a,...t.failureAtMs!=null?{at:A(t.failureAtMs)}:{}}}return o}i(He,"fromWireSchedule");function Un(t){switch(t.kind){case"AT":if(t.atMs==null)throw f();return{kind:"at",timestamp:A(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw f();return{kind:"every",interval:`PT${Je(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw f();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw f()}i(Un,"fromWireRule");function Ct(t){return{channelId:Ye(t.channelId),name:xt(t.name)}}i(Ct,"managementInput");function Ye(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw h("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 h("channelId must be a positive integer");return e}i(Ye,"channelID");function xt(t){if(!Cn.test(t))throw h("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}i(xt,"requireName");function Fn(t){let e=Ln(t);if(e===void 0||!t.trim()||e>16*1024)throw h("text must be 1..16384 UTF-8 bytes");return t}i(Fn,"requireText");function Dn(t){let e=Nt(t,60);if(e%1e3!==0)throw h("duration must resolve to whole seconds");return e/1e3}i(Dn,"durationSeconds");function Nt(t,e){let n=In.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 h("duration must be a positive ISO 8601 day/time duration");let[r,s,o,l]=n.slice(1,5).map(d=>BigInt(d??"0")),a=((r*24n+s)*60n+o)*60n+l;if(a<BigInt(e))throw h(`duration must be at least ${e} whole seconds`);let u=Number(a*1000n);if(!Number.isSafeInteger(u))throw h("duration is out of range");return u}i(Nt,"durationMilliseconds");function ze(t){let e=qn.exec(t);if(!e)throw h("timestamp must be RFC3339 with a timezone");let[n,r,s,o,l,a]=e.slice(1,7).map(Number),u=Number(e[8]??0),d=Number(e[9]??0),p=new Date(Date.UTC(n,r,0)).getUTCDate(),R=Date.parse(t);if(!Number.isFinite(R)||n<1||n>9999||r<1||r>12||s<1||s>p||o>23||l>59||a>59||u>23||d>59)throw h("timestamp must be RFC3339 with a timezone");return R}i(ze,"timestampMilliseconds");function A(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw f();let n=new Date(t);if(Number.isNaN(n.getTime()))throw f();return n.toISOString()}i(A,"timestampString");function Je(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw h(`${e} exceeds JavaScript safe integer range`);return n}i(Je,"safeInteger");function h(t){return new c("INVALID_ARGUMENT",t,400)}i(h,"invalid");function Ln(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}i(Ln,"utf8Size");function qt(){return new c("NOT_FOUND","channel schedule target not found",404)}i(qt,"scheduleNotFound");function f(){return new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}i(f,"scheduleEmptyResponse");function E(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(E,"isRecord");function m(t){return typeof t=="string"&&t.trim()!==""?t:void 0}i(m,"stringValue");function qe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(qe,"numberValue");function xe(t){return t===void 0?void 0:t.trim().toUpperCase()}i(xe,"upper");function Ut(t){return t.split("_")}i(Ut,"pairParts");function On(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Ut(e)[1]?.toLowerCase()??""}i(On,"inferInstrumentType");function Mn(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}i(Mn,"inferUnderlyingType");function Gt(t,e){let n=m(t.trading_pair)??m(t.tradingPair)??m(t.symbol);if(n===void 0)return;let r=m(t.type),s=Ut(n),o=m(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),l=m(t.market)??m(t.exchange)??s[0]??"",a=m(t.quote)??s[s.length-1]??"",u=m(t.instrument_type)??m(t.instrumentType)??On(r,n),d=m(t.underlying_type)??m(t.underlyingType)??Mn(r);return{symbol:o,tradingPair:n,market:l,instrumentType:u,...d===void 0?{}:{underlyingType:d},quote:a,...r===void 0?{}:{type:r},...m(t.description)===void 0?{}:{description:m(t.description)},...qe(t.fee_rate)===void 0?qe(t.feeRate)===void 0?{}:{feeRate:qe(t.feeRate)}:{feeRate:qe(t.fee_rate)},...m(t.symbol_icon_url)===void 0?m(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:m(t.symbolIconUrl)}:{symbolIconUrl:m(t.symbol_icon_url)}}}i(Gt,"normalizeCandidate");function jn(t){if(!E(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>E(s)?[Gt(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let r=[];for(let s of n){if(!E(s))continue;let o=m(s.symbol),l=s.trading_pairs;if(Array.isArray(l)){for(let a of l)if(!(!E(a)||!Array.isArray(a.pairs)))for(let u of a.pairs){if(!E(u))continue;let d=Gt({...u,instrument_type:u.instrument_type??a.instrument_type},o);d!==void 0&&r.push(d)}}}return r}i(jn,"flattenResponse");function $n(t,e){let n=e.trim();return t.tradingPair===n?!0:xe(t.symbol)===xe(n)}i($n,"matchesQuery");function Ie(t,e){return e===void 0||xe(t)===xe(e)}i(Ie,"matchesFilter");function Bn(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}i(Bn,"dedupe");function Qn(t){let e=E(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}}i(Qn,"resolveFilters");function Wn(t,e){let n=t.split("_"),r=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,l=n.at(-1);return!r||!s||!o||!l?{symbol:t,...e}:{symbol:o,market:e.market??r,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??l}}i(Wn,"pairSearchParams");var U=class{constructor(e){this.client=e}client;static{i(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=E(e)?e.symbol:void 0,r=typeof n=="string"?n.trim():"";if(!r)throw new c("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:r,strict:!0}}),o=Bn(jn(s)).filter(a=>$n(a,r)).filter(a=>Ie(a.market,e.market)).filter(a=>Ie(a.instrumentType,e.instrumentType)).filter(a=>Ie(a.underlyingType,e.underlyingType)).filter(a=>Ie(a.quote,e.quote)),l=e.limit;return l!==void 0&&o.length>l?{query:r,candidates:o.slice(0,l),truncated:!0}:{query:r,candidates:o}}async resolve(e){let n=E(e)?e:{},r=typeof n.pair=="string"?n.pair.trim():void 0,s=Qn(e),o=r===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Wn(r,s),l=await this.search(o),a=r===void 0?l.candidates:l.candidates.filter(u=>u.tradingPair===r);if(a.length!==1)throw new c(a.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",a.length===0?`no canonical trading pair matched "${r??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,a.length===0?404:409,{query:r??o.symbol,candidateCount:a.length,candidates:a.slice(0,50),...a.length>50?{truncated:!0}:{}});return a[0]}};var Vn="https://api-llm.prd.alva.ai",Hn="https://data-tools.prd.space.id";function Ke(t){return typeof t=="object"&&t!==null}i(Ke,"isRecord");function Ne(t,e){if(!Ke(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}i(Ne,"stringField");function Yn(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let r=Ne(t,"code");r&&(e.code=r)}else if(Ke(t)){let r=Ne(t,"code"),s=Ne(t,"name"),o=Ne(t,"message");r&&(e.code=r),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(r=>!!r);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}i(Yn,"describeCause");function zn(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:r,details:s}=Yn(Ke(t)?t.cause:void 0);return s&&(n.cause=s),{message:r?`${e}; cause: ${r}`:e,details:n}}i(zn,"describeFetchFailure");var Ge=class{static{i(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;_fs;_run;_deploy;_serviceAccount;_release;_feed;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_tradingPairs;constructor(e){this.baseUrl=e.baseUrl??Vn,this.arraysBaseUrl=e.arraysBaseUrl??Hn,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}get fs(){return this._fs??=new re(this)}get run(){return this._run??=new ie(this)}get deploy(){return this._deploy??=new se(this)}get serviceAccount(){return this._serviceAccount??=new oe(this)}get release(){return this._release??=new ae(this)}get feed(){return this._feed??=new ce(this)}get automation(){return this._automation??=new I(this)}get playbooks(){return this._playbooks??=new de(this)}get secrets(){return this._secrets??=new pe(this)}get sdk(){return this._sdk??=new me(this)}get dataSkills(){return this._dataSkills??=new ye(this)}get playbookSkills(){return this._playbookSkills??=new fe(this)}get comments(){return this._comments??=new he(this)}get remix(){return this._remix??=new ge(this)}get screenshot(){return this._screenshot??=new be(this)}get user(){return this._user??=new ke(this)}get trading(){return this._trading??=new _e(this)}get portfolio(){return this._portfolio??=new Re(this)}get arraysJwt(){return this._arraysJwt??=new Pe(this)}get notifications(){return this._notifications??=new ve(this)}get notificationPreferences(){return this._notificationPreferences??=new Ee(this)}get subscriptions(){return this._subscriptions??=new Ae(this)}get alerts(){return this._alerts??=new x(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new Se(this)}get feedback(){return this._feedback??=new Te(this)}get functions(){return this._functions??=new we(this)}get credits(){return this._credits??=new Ce(this)}get markets(){return this._markets??=new N(this)}get tradingPairs(){return this._tradingPairs??=new U(this)}get schedules(){return this._schedules??=new G(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new c("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}async _request(e,n,r){let o=`${r?.baseUrl??this.baseUrl}${n}`;if(r?.query){let k=new URLSearchParams;for(let[P,Ue]of Object.entries(r.query))Ue!=null&&k.set(P,String(Ue));let T=k.toString();T&&(o+=`?${T}`)}let l={};r?.noAuth||(this.pbsvToken?(l.Authorization=`Bearer ${this.pbsvToken}`,l["X-Pbsv"]="1"):this.viewer_token?l["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(l["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(l["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(l["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(l["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!r?.noAuth&&(l["X-Alva-Origin-Session-Id"]=this.originSessionId);let a;r?.rawBody!==void 0?(l["Content-Type"]="application/octet-stream",a=r.rawBody):r?.jsonBody!==void 0?(l["Content-Type"]="application/json",a=r.jsonBody):r?.body!==void 0&&(l["Content-Type"]="application/json",a=JSON.stringify(r.body));let u,d=r?.timeoutMs,p=r?.signal??this.signal;if(p?.aborted)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let R=d!==void 0?new AbortController:void 0,F=!1,S,X;R&&d!==void 0&&(p&&(X=i(()=>R.abort(p.reason),"abortListener"),p.addEventListener("abort",X,{once:!0})),S=setTimeout(()=>{F=!0,R.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let Xe={method:e,headers:l,body:a,signal:R?.signal??p};d!==void 0&&(Xe.timeout=d);try{u=await fetch(o,Xe)}catch(k){if(p?.aborted&&!F)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(F)throw new c("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let T=zn(k);throw new c("NETWORK_ERROR",T.message,0,{method:e,path:n,...T.details})}finally{X&&p&&p.removeEventListener("abort",X),S!==void 0&&clearTimeout(S)}if(!u.ok){let k="";try{k=await Promise.resolve(u.text())}catch{k=""}if((u.headers.get("content-type")??"").includes("application/json")&&k)try{let P=JSON.parse(k);if(P.error)throw new c(P.error.code??"UNKNOWN",P.error.message??`HTTP ${u.status}`,u.status)}catch(P){if(P instanceof c)throw P}throw new c("UNKNOWN",`HTTP ${u.status}: ${k.slice(0,200)}`,u.status)}if(u.status===204)return;let Ze=(u.headers.get("content-type")??"").toLowerCase();return Ze.includes("application/json")||Ze.includes("+json")?u.json():u.arrayBuffer()}};var Jn="0.27.0";je();return jt(Kn);})();
253
+ }`.trim(),Gn=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Ln=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Dn=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,On={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},L=class{constructor(e){this.client=e}client;static{i(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Xe(e.channelId),r=[],s=null,o=new Set;for(;;){let a=(await this.graphql(Fn,{channelId:n,after:s})).viewer?.channel?.schedules;if(!a?.edges)throw Ft();for(let d of a.edges){if(!d?.node)throw y();r.push(Ke(d.node))}if(a.pageInfo?.hasNextPage!==!0)return r;let u=a.pageInfo.endCursor;if(!u||o.has(u))throw y();o.add(u),s=u}}async put(e){this.client._requireAuth();let n={channelId:Xe(e.channelId),name:Gt(e.name),definition:{...Mn(e.rule,e.bounds),message:{text:Bn(e.text)}}},s=(await this.graphql(Je,{input:n})).updateChannelSchedule?.schedule;if(!s)throw y();return Ke(s)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.graphql(Je,{input:{...Nt(e),lifecycle:"REMOVED"}})).updateChannelSchedule?.deleted!==!0)throw y()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Un)).viewer?.channels?.find(r=>r.kind==="AGENT")?.id;if(!n)throw Ft();return n}async manage(e,n){this.client._requireAuth();let s=(await this.graphql(Je,{input:{...Nt(n),lifecycle:e}})).updateChannelSchedule?.schedule;if(!s)throw y();return Ke(s)}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors?.length){let s=r.errors.map(d=>d.extensions?.code),l=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=l?On[l]:void 0,u=l!==void 0&&a!==void 0?l:"GRAPHQL_ERROR";throw new c(u,r.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",a??502,{errors:r.errors})}if(!r.data)throw y();return r.data}};function Mn(t,e){let n=jn(e);switch(t.kind){case"after":if(n)throw h("after does not accept recurring bounds");let r=Date.now()+Lt(t.duration,1),s=Math.ceil(r/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw h("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw h("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:Ze(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Qn(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw h("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}i(Mn,"ruleInput");function jn(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=Ze(t.startsAt)),t.until!==void 0&&(e.untilMs=Ze(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw h("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}i(jn,"boundsInput");function Ke(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw y();let r=t.bounds??{},s=t.message??{},o={name:t.name,rule:$n(t.rule),bounds:{...r.startsAtMs!=null?{startsAt:T(r.startsAtMs,!0)}:{},...r.untilMs!=null?{until:T(r.untilMs,!0)}:{},...r.maxOccurrences!=null?{maxOccurrences:et(r.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:et(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:T(t.nextFireAtMs,!0)}:{},createdAt:T(t.createdAtMs),updatedAt:T(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw y();let a={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!a)throw y();o.failure={code:a,...t.failureAtMs!=null?{at:T(t.failureAtMs)}:{}}}return o}i(Ke,"fromWireSchedule");function $n(t){switch(t.kind){case"AT":if(t.atMs==null)throw y();return{kind:"at",timestamp:T(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw y();return{kind:"every",interval:`PT${et(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw y();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw y()}i($n,"fromWireRule");function Nt(t){return{channelId:Xe(t.channelId),name:Gt(t.name)}}i(Nt,"managementInput");function Xe(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw h("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 h("channelId must be a positive integer");return e}i(Xe,"channelID");function Gt(t){if(!Gn.test(t))throw h("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}i(Gt,"requireName");function Bn(t){let e=Wn(t);if(e===void 0||!t.trim()||e>16*1024)throw h("text must be 1..16384 UTF-8 bytes");return t}i(Bn,"requireText");function Qn(t){let e=Lt(t,60);if(e%1e3!==0)throw h("duration must resolve to whole seconds");return e/1e3}i(Qn,"durationSeconds");function Lt(t,e){let n=Dn.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 h("duration must be a positive ISO 8601 day/time duration");let[r,s,o,l]=n.slice(1,5).map(d=>BigInt(d??"0")),a=((r*24n+s)*60n+o)*60n+l;if(a<BigInt(e))throw h(`duration must be at least ${e} whole seconds`);let u=Number(a*1000n);if(!Number.isSafeInteger(u))throw h("duration is out of range");return u}i(Lt,"durationMilliseconds");function Ze(t){let e=Ln.exec(t);if(!e)throw h("timestamp must be RFC3339 with a timezone");let[n,r,s,o,l,a]=e.slice(1,7).map(Number),u=Number(e[8]??0),d=Number(e[9]??0),p=new Date(Date.UTC(n,r,0)).getUTCDate(),_=Date.parse(t);if(!Number.isFinite(_)||n<1||n>9999||r<1||r>12||s<1||s>p||o>23||l>59||a>59||u>23||d>59)throw h("timestamp must be RFC3339 with a timezone");return _}i(Ze,"timestampMilliseconds");function T(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw y();let n=new Date(t);if(Number.isNaN(n.getTime()))throw y();return n.toISOString()}i(T,"timestampString");function et(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw h(`${e} exceeds JavaScript safe integer range`);return n}i(et,"safeInteger");function h(t){return new c("INVALID_ARGUMENT",t,400)}i(h,"invalid");function Wn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}i(Wn,"utf8Size");function Ft(){return new c("NOT_FOUND","channel schedule target not found",404)}i(Ft,"scheduleNotFound");function y(){return new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}i(y,"scheduleEmptyResponse");function A(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(A,"isRecord");function m(t){return typeof t=="string"&&t.trim()!==""?t:void 0}i(m,"stringValue");function Fe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(Fe,"numberValue");function Ge(t){return t===void 0?void 0:t.trim().toUpperCase()}i(Ge,"upper");function Ot(t){return t.split("_")}i(Ot,"pairParts");function Yn(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Ot(e)[1]?.toLowerCase()??""}i(Yn,"inferInstrumentType");function Vn(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}i(Vn,"inferUnderlyingType");function Dt(t,e){let n=m(t.trading_pair)??m(t.tradingPair)??m(t.symbol);if(n===void 0)return;let r=m(t.type),s=Ot(n),o=m(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),l=m(t.market)??m(t.exchange)??s[0]??"",a=m(t.quote)??s[s.length-1]??"",u=m(t.instrument_type)??m(t.instrumentType)??Yn(r,n),d=m(t.underlying_type)??m(t.underlyingType)??Vn(r);return{symbol:o,tradingPair:n,market:l,instrumentType:u,...d===void 0?{}:{underlyingType:d},quote:a,...r===void 0?{}:{type:r},...m(t.description)===void 0?{}:{description:m(t.description)},...Fe(t.fee_rate)===void 0?Fe(t.feeRate)===void 0?{}:{feeRate:Fe(t.feeRate)}:{feeRate:Fe(t.fee_rate)},...m(t.symbol_icon_url)===void 0?m(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:m(t.symbolIconUrl)}:{symbolIconUrl:m(t.symbol_icon_url)}}}i(Dt,"normalizeCandidate");function Hn(t){if(!A(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>A(s)?[Dt(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let r=[];for(let s of n){if(!A(s))continue;let o=m(s.symbol),l=s.trading_pairs;if(Array.isArray(l)){for(let a of l)if(!(!A(a)||!Array.isArray(a.pairs)))for(let u of a.pairs){if(!A(u))continue;let d=Dt({...u,instrument_type:u.instrument_type??a.instrument_type},o);d!==void 0&&r.push(d)}}}return r}i(Hn,"flattenResponse");function zn(t,e){let n=e.trim();return t.tradingPair===n?!0:Ge(t.symbol)===Ge(n)}i(zn,"matchesQuery");function Ue(t,e){return e===void 0||Ge(t)===Ge(e)}i(Ue,"matchesFilter");function Jn(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}i(Jn,"dedupe");function Kn(t){let e=A(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}}i(Kn,"resolveFilters");function Xn(t,e){let n=t.split("_"),r=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,l=n.at(-1);return!r||!s||!o||!l?{symbol:t,...e}:{symbol:o,market:e.market??r,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??l}}i(Xn,"pairSearchParams");var D=class{constructor(e){this.client=e}client;static{i(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=A(e)?e.symbol:void 0,r=typeof n=="string"?n.trim():"";if(!r)throw new c("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:r,strict:!0}}),o=Jn(Hn(s)).filter(a=>zn(a,r)).filter(a=>Ue(a.market,e.market)).filter(a=>Ue(a.instrumentType,e.instrumentType)).filter(a=>Ue(a.underlyingType,e.underlyingType)).filter(a=>Ue(a.quote,e.quote)),l=e.limit;return l!==void 0&&o.length>l?{query:r,candidates:o.slice(0,l),truncated:!0}:{query:r,candidates:o}}async resolve(e){let n=A(e)?e:{},r=typeof n.pair=="string"?n.pair.trim():void 0,s=Kn(e),o=r===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Xn(r,s),l=await this.search(o),a=r===void 0?l.candidates:l.candidates.filter(u=>u.tradingPair===r);if(a.length!==1)throw new c(a.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",a.length===0?`no canonical trading pair matched "${r??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,a.length===0?404:409,{query:r??o.symbol,candidateCount:a.length,candidates:a.slice(0,50),...a.length>50?{truncated:!0}:{}});return a[0]}};var Zn="https://api-llm.prd.alva.ai",er="https://data-tools.prd.space.id";function tt(t){return typeof t=="object"&&t!==null}i(tt,"isRecord");function Le(t,e){if(!tt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}i(Le,"stringField");function tr(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let r=Le(t,"code");r&&(e.code=r)}else if(tt(t)){let r=Le(t,"code"),s=Le(t,"name"),o=Le(t,"message");r&&(e.code=r),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(r=>!!r);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}i(tr,"describeCause");function nr(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:r,details:s}=tr(tt(t)?t.cause:void 0);return s&&(n.cause=s),{message:r?`${e}; cause: ${r}`:e,details:n}}i(nr,"describeFetchFailure");var De=class{static{i(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;_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;_tradingPairs;constructor(e){this.baseUrl=e.baseUrl??Zn,this.arraysBaseUrl=e.arraysBaseUrl??er,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}get fs(){return this._fs??=new oe(this)}get run(){return this._run??=new ae(this)}get deploy(){return this._deploy??=new le(this)}get serviceAccount(){return this._serviceAccount??=new ce(this)}get release(){return this._release??=new ue(this)}get feed(){return this._feed??=new pe(this)}get automation(){return this._automation??=new F(this)}get playbooks(){return this._playbooks??=new ye(this)}get secrets(){return this._secrets??=new he(this)}get sdk(){return this._sdk??=new ge(this)}get dataSkills(){return this._dataSkills??=new be(this)}get playbookSkills(){return this._playbookSkills??=new ke(this)}get comments(){return this._comments??=new Pe(this)}get remix(){return this._remix??=new Re(this)}get screenshot(){return this._screenshot??=new _e(this)}get user(){return this._user??=new Ee(this)}get trading(){return this._trading??=new ve(this)}get portfolio(){return this._portfolio??=new Ae(this)}get arraysJwt(){return this._arraysJwt??=new Se(this)}get notifications(){return this._notifications??=new Te(this)}get notificationPreferences(){return this._notificationPreferences??=new we(this)}get subscriptions(){return this._subscriptions??=new Ce(this)}get alerts(){return this._alerts??=new U(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new qe(this)}get feedback(){return this._feedback??=new Ie(this)}get functions(){return this._functions??=new xe(this)}get credits(){return this._credits??=new Ne(this)}get markets(){return this._markets??=new G(this)}get tradingPairs(){return this._tradingPairs??=new D(this)}get schedules(){return this._schedules??=new L(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new c("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get forYou(){return this._forYou??=new N(this)}async _request(e,n,r){let o=`${r?.baseUrl??this.baseUrl}${n}`;if(r?.query){let P=new URLSearchParams;for(let[E,Oe]of Object.entries(r.query))Oe!=null&&P.set(E,String(Oe));let C=P.toString();C&&(o+=`?${C}`)}let l={};r?.noAuth||(this.pbsvToken?(l.Authorization=`Bearer ${this.pbsvToken}`,l["X-Pbsv"]="1"):this.viewer_token?l["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(l["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(l["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(l["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(l["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!r?.noAuth&&(l["X-Alva-Origin-Session-Id"]=this.originSessionId);let a;r?.rawBody!==void 0?(l["Content-Type"]="application/octet-stream",a=r.rawBody):r?.jsonBody!==void 0?(l["Content-Type"]="application/json",a=r.jsonBody):r?.body!==void 0&&(l["Content-Type"]="application/json",a=JSON.stringify(r.body));let u,d=r?.timeoutMs,p=r?.signal??this.signal;if(p?.aborted)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let _=d!==void 0?new AbortController:void 0,O=!1,w,te;_&&d!==void 0&&(p&&(te=i(()=>_.abort(p.reason),"abortListener"),p.addEventListener("abort",te,{once:!0})),w=setTimeout(()=>{O=!0,_.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let nt={method:e,headers:l,body:a,signal:_?.signal??p};d!==void 0&&(nt.timeout=d);try{u=await fetch(o,nt)}catch(P){if(p?.aborted&&!O)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(O)throw new c("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let C=nr(P);throw new c("NETWORK_ERROR",C.message,0,{method:e,path:n,...C.details})}finally{te&&p&&p.removeEventListener("abort",te),w!==void 0&&clearTimeout(w)}if(!u.ok){let P="";try{P=await Promise.resolve(u.text())}catch{P=""}if((u.headers.get("content-type")??"").includes("application/json")&&P)try{let E=JSON.parse(P);if(E.error)throw new c(E.error.code??"UNKNOWN",E.error.message??`HTTP ${u.status}`,u.status)}catch(E){if(E instanceof c)throw E}throw new c("UNKNOWN",`HTTP ${u.status}: ${P.slice(0,200)}`,u.status)}if(u.status===204)return;let rt=(u.headers.get("content-type")??"").toLowerCase();return rt.includes("application/json")||rt.includes("+json")?u.json():u.arrayBuffer()}};var rr="0.28.0";We();return Wt(ir);})();
227
254
  //# sourceMappingURL=browser.global.js.map