@alva-ai/toolkit 0.24.0 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -176,27 +176,30 @@ import { AlvaClient } from '@alva-ai/toolkit';
176
176
  import { dispatch, CliUsageError } from '@alva-ai/toolkit/dispatch';
177
177
 
178
178
  const client = new AlvaClient({ apiKey: process.env.ALVA_API_KEY });
179
- const result = await dispatch(
180
- client,
181
- ['fs', 'read', '--path', '/alva/home/alice/playbooks/demo/README.md'],
182
- undefined,
183
- { mode: 'jagent' }
184
- );
179
+ const result = await dispatch(client, ['account', 'whoami']);
185
180
  ```
186
181
 
187
- `mode: 'jagent'` keeps the command surface aligned with ALFS-native agent
188
- tools: flags that read or write local files, such as `--local-file`, `--file`,
189
- `--params-schema-file`, and screenshot `--out`, are rejected. Use inline data
190
- or prepare content in ALFS before dispatching the CLI command. `dispatch()`
191
- throws `CliUsageError` for command-line usage errors and `AlvaError` for API
192
- errors. Toolkit-managed commands reject unknown flags before invoking an API;
193
- the error is scoped to the resolved command and suggests a nearby supported
194
- flag when possible. `broker` is the explicit exception because its remaining
195
- arguments are forwarded verbatim to the venue-native CLI.
182
+ The embedded dispatcher always exposes the purpose-built Alpi Alva command
183
+ catalog. It is independent from the packaged system `alva` CLI.
184
+ Authentication/setup, Arrays bootstrap, SDK documentation, duplicate aliases,
185
+ legacy top-level groupings, and `feedback submit` are not part of this catalog;
186
+ old Agent paths are rejected rather than aliased. Run the embedded `--help` for
187
+ the live tree. The independent system CLI continues to expose feedback.
188
+
189
+ The embedded surface is aligned with ALFS-native tools: local-file flags such as
190
+ `--local-file`, `--file`, `--params-schema-file`, and screenshot `--out` are
191
+ absent. Use inline data or prepare content in ALFS before dispatching the
192
+ command; Agent screenshots return image content directly. `dispatch()` throws
193
+ `CliUsageError` for command-line usage errors and `AlvaError` for API errors.
194
+ Managed commands reject unknown flags before invoking an API. `trading broker`
195
+ is the explicit exception because argv after that nested prefix is forwarded
196
+ verbatim to the venue-native Broker contract.
196
197
 
197
198
  Node.js command-line consumers should continue to use
198
199
  `@alva-ai/toolkit/cli`, which adds config files, authentication, local files,
199
- stdio, and Undici timeout configuration around the same dispatcher.
200
+ stdio, and Undici timeout configuration around its independent terminal
201
+ dispatcher. Both entries share the SDK and low-level command execution handlers,
202
+ not their catalogs, parsers, or help.
200
203
 
201
204
  ## SDK Usage (Node.js)
202
205
 
@@ -1,4 +1,4 @@
1
- "use strict";var AlvaToolkit=(()=>{var V=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var ht=Object.prototype.hasOwnProperty;var s=(t,e)=>V(t,"name",{value:e,configurable:!0});var gt=(t,e)=>{for(var i in e)V(t,i,{get:e[i],enumerable:!0})},bt=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ft(e))!ht.call(t,n)&&n!==i&&V(t,n,{get:()=>e[n],enumerable:!(r=yt(e,n))||r.enumerable});return t};var kt=t=>bt(V({},"__esModule",{value:!0}),t);var ci={};gt(ci,{AlertsResource:()=>T,AlvaClient:()=>ve,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>Q,AutomationResource:()=>S,CliUsageError:()=>Y,MarketsResource:()=>w,PBSV_UPDATE_MESSAGE:()=>je,SUBSCRIBE_MANAGE_MESSAGE:()=>Ve,SUBSCRIBE_PROPOSE_MESSAGE:()=>Qe,SUBSCRIBE_RESULT_MESSAGE:()=>We,UDF_AUTH_REQUIRED_MESSAGE:()=>Be,UDF_CONSENT_REQUEST_MESSAGE:()=>Me,UDF_CONSENT_RESPONSE_MESSAGE:()=>$e,UdfAuthRequiredError:()=>E,UdfConsentDeniedError:()=>F,UdfConsentRequiredError:()=>G,UdfConsentTimeoutError:()=>U,UdfError:()=>d,UdfExecutionError:()=>j,UdfFunctionDisabledError:()=>O,UdfFunctionNotFoundError:()=>L,UdfInsufficientCredits:()=>N,UdfPidMismatchError:()=>k,UdfRateLimitedError:()=>D,UdfTokenExpiredError:()=>x,UdfTokenInvalidError:()=>I,UdfTransportError:()=>A,VERSION:()=>li,getViewerToken:()=>M,installPlaybookRuntime:()=>qe,mapUdfErrorResponse:()=>we,playbookIdFromToken:()=>Te,subscribe:()=>Xe,udf:()=>Ze});var d=class extends Error{static{s(this,"UdfError")}code;metadata;status;constructor(e,{code:i,metadata:r={},status:n}){super(e),this.name=new.target.name,this.code=i,this.metadata=r,this.status=n}},E=class extends d{static{s(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},x=class extends d{static{s(this,"UdfTokenExpiredError")}},I=class extends d{static{s(this,"UdfTokenInvalidError")}},k=class extends d{static{s(this,"UdfPidMismatchError")}},G=class extends d{static{s(this,"UdfConsentRequiredError")}},F=class extends d{static{s(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},U=class extends d{static{s(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},N=class extends d{static{s(this,"UdfInsufficientCredits")}},L=class extends d{static{s(this,"UdfFunctionNotFoundError")}},O=class extends d{static{s(this,"UdfFunctionDisabledError")}},D=class extends d{static{s(this,"UdfRateLimitedError")}},j=class extends d{static{s(this,"UdfExecutionError")}},A=class extends d{static{s(this,"UdfTransportError")}},je="alva:pbsv:update",Me="alva:udf:consent-request",$e="alva:udf:consent-response",Be="alva:udf:auth-required",Qe="alva:subscribe:propose",We="alva:subscribe:result",Ve="alva:subscribe:manage",He="https://api-llm.prd.alva.ai",Je=300*1e3,q=null,f=null,Se=He,g=null,y=null,De=!1,H=new Map,J=new Map,_t=s(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Rt=s(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),i=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(i)},"decodeBase64Url"),Te=s(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let i=JSON.parse(Rt(e));if(typeof i.pid=="number")return String(i.pid);if(typeof i.pid=="string")return i.pid}catch{return null}return null},"playbookIdFromToken"),M=s(()=>q,"getViewerToken"),v=s(()=>!!M(),"isAuthenticated"),Pt=s(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),vt=s(t=>{let e=new URLSearchParams(t.location.search);q=e.get("_pbsv"),f=e.get("parent_origin"),Se=(e.get("api_origin")||He).replace(/\/$/,""),g=Te(q),q&&Pt(t)},"parseBootParams"),Ye=s(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Et=s(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),At=s(t=>{let e=t;return{...e,result:Et(e.result)}},"normalizeInvokeResponse"),Ke=s(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),we=s((t,e)=>{let i=t.error?.code||"TRANSPORT",r=t.error?.message||i,n=Ke(t),o={code:i,metadata:n,status:e};switch(i){case"PBSV_EXPIRED":return new x(r,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new I(r,o);case"PBSV_PID_MISMATCH":return new k(r,o);case"CONSENT_REQUIRED":return new G(r,o);case"INSUFFICIENT_CREDITS":return new N(r,o);case"FUNCTION_NOT_FOUND":return new L(r,o);case"FUNCTION_DISABLED":return new O(r,o);case"RESOURCE_EXHAUSTED":return new D(r,o);case"EXECUTION_FAILED":return new j(r,o);default:return new A(r,o)}},"mapUdfErrorResponse"),St=s(t=>{if(!y||!f||t.origin!==f||t.source!==y.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===je){typeof e.token=="string"&&e.token.length>0&&(q=e.token,g=Te(e.token));return}if(e.type===We){if(typeof e.request_id!="string")return;let r=J.get(e.request_id);if(!r)return;clearTimeout(r.timer),J.delete(e.request_id),r.resolve(_t(e.status));return}if(e.type!==$e||typeof e.request_id!="string")return;let i=H.get(e.request_id);i&&(clearTimeout(i.timer),H.delete(e.request_id),i.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),ze=s(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Tt=s(()=>{if(!g)return null;let t=Number(g);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),wt=s(async(t,e)=>{if(!y||!f)return"denied";let i=f,r=ze();return new Promise(n=>{let o=setTimeout(()=>{H.delete(r),n("timeout")},Je);H.set(r,{resolve:n,timer:o}),y?.parent.postMessage({type:Me,request_id:r,playbook_id:t,min_allowance:e},i)})},"requestConsent"),Ct=s(async t=>{if(!y||!f)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",i=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!i)return"error";let r=f,n=ze();return new Promise(o=>{let a=setTimeout(()=>{J.delete(n),o("timeout")},Je);J.set(n,{resolve:o,timer:a}),y?.parent.postMessage({type:Qe,request_id:n,playbook_id:g,feed:{owner:e,name:i}},r)})},"proposeSubscribe"),qt=s(()=>{!y||!f||y.parent.postMessage({type:Ve,playbook_id:g},f)},"manageSubscriptions"),Xe={propose:Ct,manage:qt},xt=s(t=>{!y||!f||y.parent.postMessage({type:Be,function_name:t},f)},"requestAuthentication"),Ce=s(async(t,e,i=!1)=>{let r=M();if(!r)throw new E;if(!g)throw new k("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let n=Tt();if(!n)throw new k("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${Se}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:n,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new A("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Ye(o);if(o.ok)return At(a);if(a.error?.code==="CONSENT_REQUIRED"&&!i){let c=Ke(a),u=typeof c.playbook_id=="string"?c.playbook_id:g,m=typeof c.min_allowance_suggested=="number"?c.min_allowance_suggested:1,p=await wt(u,m);if(p==="granted")return Ce(t,e,!0);throw p==="timeout"?new U:new F}throw we(a,o.status)},"call"),It=s(async()=>{let t=M();if(!t)throw new E;if(!g)throw new k("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${Se}/api/v1/service/functions`);e.searchParams.set("playbook_id",g);let i=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),r=await Ye(i);if(!i.ok)throw we(r,i.status);let n=r.functions;return Array.isArray(n)?n:[]},"list"),Ae=s((t,e,i)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:i}))},"dispatchButtonEvent"),Gt=s(t=>{if(typeof t!="string")return t;let i=y?.document?.querySelector(t);if(i&&"appendChild"in i)return i;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),Ft=s((t,e)=>{if(!y)throw new Error("Playbook runtime is not installed.");let i=Gt(t),r=y.document.createElement("button"),n=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return r.type="button",r.className="alva-udf-button",r.textContent=v()?n:a,r.disabled=!1,r.setAttribute("data-function-name",e.functionName),v()||r.setAttribute("aria-disabled","true"),r.addEventListener("click",async()=>{if(!v()){xt(e.functionName);return}if(!r.disabled){r.disabled=!0,r.textContent=o,Ae(r,"alva:udf-button:loading",{functionName:e.functionName});try{let c=await Ce(e.functionName,e.params??{});Ae(r,"alva:udf-button:result",{functionName:e.functionName,result:c})}catch(c){Ae(r,"alva:udf-button:error",{functionName:e.functionName,error:c})}finally{r.disabled=!1,r.textContent=v()?n:a,v()||r.setAttribute("aria-disabled","true")}}}),i.appendChild(r),r},"renderButton"),Ze={call:Ce,list:It,getViewerToken:M,isAuthenticated:v,renderButton:Ft,UdfError:d,UdfAuthRequiredError:E,UdfTokenExpiredError:x,UdfTokenInvalidError:I,UdfPidMismatchError:k,UdfConsentRequiredError:G,UdfConsentDeniedError:F,UdfConsentTimeoutError:U,UdfInsufficientCredits:N,UdfFunctionNotFoundError:L,UdfFunctionDisabledError:O,UdfRateLimitedError:D,UdfExecutionError:j,UdfTransportError:A},qe=s(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||De)return;y=e,De=!0,vt(e),e.addEventListener("message",St);let i=e,r=i.alva||{};i.alva={...r,udf:Ze,subscribe:Xe}},"installPlaybookRuntime");var l=class extends Error{static{s(this,"AlvaError")}code;status;details;constructor(e,i,r,n){super(i),this.name="AlvaError",this.code=e,this.status=r,this.details=n}},Y=class extends Error{static{s(this,"CliUsageError")}command;constructor(e,i){super(e),this.name="CliUsageError",this.command=i}};function et(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}s(et,"isArrayBuffer");var tt=1;function Ut(t){let e=0;for(;e<t.length;){let i=t[e];if(i<=127){e+=1;continue}let r=0,n=0,o=0;if(i>=194&&i<=223)r=1,n=128,o=i&31;else if(i>=224&&i<=239)r=2,n=2048,o=i&15;else if(i>=240&&i<=244)r=3,n=65536,o=i&7;else return!1;if(e+r>=t.length)return!1;for(let a=1;a<=r;a+=1){let c=t[e+a];if((c&192)!==128)return!1;o=o<<6|c&63}if(o<n||o>1114111||o>=55296&&o<=57343)return!1;e+=r+1}return!0}s(Ut,"isValidUtf8");var K=class{constructor(e){this.client=e}client;static{s(this,"FsResource")}async read(e){let i=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!et(i)||!Ut(new Uint8Array(i)))return i;let r=new TextDecoder("utf-8").decode(i);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:tt}:{}}})}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:tt}:{}},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 it="9007199254740991";function rt(t,e,i,r){let n=t.length+e,o=i.length+r;if(n!==o)return n>o;for(let a=0;a<n;a++){let c=a<t.length?t[a]:"0",u=a<i.length?i[a]:"0";if(c!==u)return c>u}return!1}s(rt,"scaledIntegerGreater");function Nt(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let i=e.groups.whole,r=e.groups.fraction??"",n=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(n))return!0;let o=(i+r).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=n-r.length;return a>=0?rt(o,a,it,0):rt(o,0,it,-a)}s(Nt,"numberOutsideSafeRange");function Lt(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 i=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(i){if(Nt(i[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=i[0].length;continue}}e++}}s(Lt,"validateJSONNumberTokens");function xe(t,e,i){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(i.has(t))throw new TypeError(`${e} must not contain circular references`);if(i.add(t),Array.isArray(t))t.forEach((r,n)=>xe(r,`${e}[${n}]`,i));else{let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[n,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);xe(o.value,`${e}.${n}`,i)}}i.delete(t)}}s(xe,"assertPlainJSONData");function $(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");xe(t,"args",new Set);let e=JSON.stringify(t);return st(e),e}s($,"serializeStructuredArgs");function st(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Lt(t)}s(st,"validateSerializedArgs");function B(t,e,i){let r=Object.entries(t).filter(([n,o])=>o!==void 0&&(i===void 0||n!==e));return i!==void 0&&(st(i),r.push([e,i])),`{${r.map(([n,o])=>{let a=n===e&&i!==void 0?i:JSON.stringify(o);return`${JSON.stringify(n)}:${a}`}).join(",")}}`}s(B,"objectWithRawJSONField");var z=class{constructor(e){this.client=e}client;static{s(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,$(e.args))}async _executeSerializedArgs(e,i){return this.client._requireAuth(),this.request(e,i)}request(e,i){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",{...i===void 0?{body:r}:{jsonBody:B(r,"args",i)},timeoutMs:e.timeout_ms})}};var X=class{constructor(e){this.client=e}client;static{s(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,$(e.args))}async _createSerializedArgs(e,i){return this.client._requireAuth(),this.createRequest(e,i)}createRequest(e,i){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",{...i===void 0?{body:r}:{jsonBody:B(r,"args",i)}})}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,$(e.args))}async _updateSerializedArgs(e,i){return this.client._requireAuth(),this.updateRequest(e,i)}updateRequest(e,i){let{id:r,...n}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${r}`,{...i===void 0?{body:n}:{jsonBody:B(n,"args",i)}})}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 Z=class{constructor(e){this.client=e}client;static{s(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var ee=class{constructor(e){this.client=e}client;static{s(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url}})}};var ie=class{constructor(e){this.client=e}client;static{s(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let i=te(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(i))}/stop`)}async resume(e){this.client._requireAuth();let i=te(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(i))}/resume`)}async delete(e){this.client._requireAuth();let i=te(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(i))}`)}async setVisibility(e){this.client._requireAuth();let i=te(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(i))}/visibility`,{body:{visibility:e.visibility}})}};function te(t){if(!Number.isInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}s(te,"requireFeedID");var Ot=`
1
+ "use strict";var AlvaToolkit=(()=>{var V=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var ht=Object.prototype.hasOwnProperty;var s=(t,e)=>V(t,"name",{value:e,configurable:!0});var gt=(t,e)=>{for(var r in e)V(t,r,{get:e[r],enumerable:!0})},bt=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ft(e))!ht.call(t,n)&&n!==r&&V(t,n,{get:()=>e[n],enumerable:!(i=yt(e,n))||i.enumerable});return t};var kt=t=>bt(V({},"__esModule",{value:!0}),t);var cr={};gt(cr,{AlertsResource:()=>T,AlvaClient:()=>Ee,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>Q,AutomationResource:()=>A,CliUsageError:()=>Y,MarketsResource:()=>w,PBSV_UPDATE_MESSAGE:()=>je,SUBSCRIBE_MANAGE_MESSAGE:()=>Ve,SUBSCRIBE_PROPOSE_MESSAGE:()=>Qe,SUBSCRIBE_RESULT_MESSAGE:()=>We,UDF_AUTH_REQUIRED_MESSAGE:()=>Be,UDF_CONSENT_REQUEST_MESSAGE:()=>Me,UDF_CONSENT_RESPONSE_MESSAGE:()=>$e,UdfAuthRequiredError:()=>E,UdfConsentDeniedError:()=>F,UdfConsentRequiredError:()=>G,UdfConsentTimeoutError:()=>U,UdfError:()=>d,UdfExecutionError:()=>j,UdfFunctionDisabledError:()=>O,UdfFunctionNotFoundError:()=>L,UdfInsufficientCredits:()=>N,UdfPidMismatchError:()=>k,UdfRateLimitedError:()=>D,UdfTokenExpiredError:()=>x,UdfTokenInvalidError:()=>I,UdfTransportError:()=>S,VERSION:()=>lr,getViewerToken:()=>M,installPlaybookRuntime:()=>xe,mapUdfErrorResponse:()=>Ce,playbookIdFromToken:()=>we,subscribe:()=>Xe,udf:()=>Ze});var d=class extends Error{static{s(this,"UdfError")}code;metadata;status;constructor(e,{code:r,metadata:i={},status:n}){super(e),this.name=new.target.name,this.code=r,this.metadata=i,this.status=n}},E=class extends d{static{s(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},x=class extends d{static{s(this,"UdfTokenExpiredError")}},I=class extends d{static{s(this,"UdfTokenInvalidError")}},k=class extends d{static{s(this,"UdfPidMismatchError")}},G=class extends d{static{s(this,"UdfConsentRequiredError")}},F=class extends d{static{s(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},U=class extends d{static{s(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},N=class extends d{static{s(this,"UdfInsufficientCredits")}},L=class extends d{static{s(this,"UdfFunctionNotFoundError")}},O=class extends d{static{s(this,"UdfFunctionDisabledError")}},D=class extends d{static{s(this,"UdfRateLimitedError")}},j=class extends d{static{s(this,"UdfExecutionError")}},S=class extends d{static{s(this,"UdfTransportError")}},je="alva:pbsv:update",Me="alva:udf:consent-request",$e="alva:udf:consent-response",Be="alva:udf:auth-required",Qe="alva:subscribe:propose",We="alva:subscribe:result",Ve="alva:subscribe:manage",He="https://api-llm.prd.alva.ai",Je=300*1e3,q=null,f=null,Te=He,g=null,y=null,De=!1,H=new Map,J=new Map,_t=s(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Rt=s(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(r)},"decodeBase64Url"),we=s(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let r=JSON.parse(Rt(e));if(typeof r.pid=="number")return String(r.pid);if(typeof r.pid=="string")return r.pid}catch{return null}return null},"playbookIdFromToken"),M=s(()=>q,"getViewerToken"),v=s(()=>!!M(),"isAuthenticated"),Pt=s(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),vt=s(t=>{let e=new URLSearchParams(t.location.search);q=e.get("_pbsv"),f=e.get("parent_origin"),Te=(e.get("api_origin")||He).replace(/\/$/,""),g=we(q),q&&Pt(t)},"parseBootParams"),Ye=s(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Et=s(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),St=s(t=>{let e=t;return{...e,result:Et(e.result)}},"normalizeInvokeResponse"),Ke=s(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),Ce=s((t,e)=>{let r=t.error?.code||"TRANSPORT",i=t.error?.message||r,n=Ke(t),o={code:r,metadata:n,status:e};switch(r){case"PBSV_EXPIRED":return new x(i,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new I(i,o);case"PBSV_PID_MISMATCH":return new k(i,o);case"CONSENT_REQUIRED":return new G(i,o);case"INSUFFICIENT_CREDITS":return new N(i,o);case"FUNCTION_NOT_FOUND":return new L(i,o);case"FUNCTION_DISABLED":return new O(i,o);case"RESOURCE_EXHAUSTED":return new D(i,o);case"EXECUTION_FAILED":return new j(i,o);default:return new S(i,o)}},"mapUdfErrorResponse"),At=s(t=>{if(!y||!f||t.origin!==f||t.source!==y.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===je){typeof e.token=="string"&&e.token.length>0&&(q=e.token,g=we(e.token));return}if(e.type===We){if(typeof e.request_id!="string")return;let i=J.get(e.request_id);if(!i)return;clearTimeout(i.timer),J.delete(e.request_id),i.resolve(_t(e.status));return}if(e.type!==$e||typeof e.request_id!="string")return;let r=H.get(e.request_id);r&&(clearTimeout(r.timer),H.delete(e.request_id),r.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),ze=s(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Tt=s(()=>{if(!g)return null;let t=Number(g);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),wt=s(async(t,e)=>{if(!y||!f)return"denied";let r=f,i=ze();return new Promise(n=>{let o=setTimeout(()=>{H.delete(i),n("timeout")},Je);H.set(i,{resolve:n,timer:o}),y?.parent.postMessage({type:Me,request_id:i,playbook_id:t,min_allowance:e},r)})},"requestConsent"),Ct=s(async t=>{if(!y||!f)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",r=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!r)return"error";let i=f,n=ze();return new Promise(o=>{let a=setTimeout(()=>{J.delete(n),o("timeout")},Je);J.set(n,{resolve:o,timer:a}),y?.parent.postMessage({type:Qe,request_id:n,playbook_id:g,feed:{owner:e,name:r}},i)})},"proposeSubscribe"),qt=s(()=>{!y||!f||y.parent.postMessage({type:Ve,playbook_id:g},f)},"manageSubscriptions"),Xe={propose:Ct,manage:qt},xt=s(t=>{!y||!f||y.parent.postMessage({type:Be,function_name:t},f)},"requestAuthentication"),qe=s(async(t,e,r=!1)=>{let i=M();if(!i)throw new E;if(!g)throw new k("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let n=Tt();if(!n)throw new k("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${Te}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:n,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new S("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Ye(o);if(o.ok)return St(a);if(a.error?.code==="CONSENT_REQUIRED"&&!r){let c=Ke(a),u=typeof c.playbook_id=="string"?c.playbook_id:g,m=typeof c.min_allowance_suggested=="number"?c.min_allowance_suggested:1,p=await wt(u,m);if(p==="granted")return qe(t,e,!0);throw p==="timeout"?new U:new F}throw Ce(a,o.status)},"call"),It=s(async()=>{let t=M();if(!t)throw new E;if(!g)throw new k("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${Te}/api/v1/service/functions`);e.searchParams.set("playbook_id",g);let r=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await Ye(r);if(!r.ok)throw Ce(i,r.status);let n=i.functions;return Array.isArray(n)?n:[]},"list"),Ae=s((t,e,r)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:r}))},"dispatchButtonEvent"),Gt=s(t=>{if(typeof t!="string")return t;let r=y?.document?.querySelector(t);if(r&&"appendChild"in r)return r;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),Ft=s((t,e)=>{if(!y)throw new Error("Playbook runtime is not installed.");let r=Gt(t),i=y.document.createElement("button"),n=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=v()?n:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),v()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!v()){xt(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=o,Ae(i,"alva:udf-button:loading",{functionName:e.functionName});try{let c=await qe(e.functionName,e.params??{});Ae(i,"alva:udf-button:result",{functionName:e.functionName,result:c})}catch(c){Ae(i,"alva:udf-button:error",{functionName:e.functionName,error:c})}finally{i.disabled=!1,i.textContent=v()?n:a,v()||i.setAttribute("aria-disabled","true")}}}),r.appendChild(i),i},"renderButton"),Ze={call:qe,list:It,getViewerToken:M,isAuthenticated:v,renderButton:Ft,UdfError:d,UdfAuthRequiredError:E,UdfTokenExpiredError:x,UdfTokenInvalidError:I,UdfPidMismatchError:k,UdfConsentRequiredError:G,UdfConsentDeniedError:F,UdfConsentTimeoutError:U,UdfInsufficientCredits:N,UdfFunctionNotFoundError:L,UdfFunctionDisabledError:O,UdfRateLimitedError:D,UdfExecutionError:j,UdfTransportError:S},xe=s(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||De)return;y=e,De=!0,vt(e),e.addEventListener("message",At);let r=e,i=r.alva||{};r.alva={...i,udf:Ze,subscribe:Xe}},"installPlaybookRuntime");var l=class extends Error{static{s(this,"AlvaError")}code;status;details;constructor(e,r,i,n){super(r),this.name="AlvaError",this.code=e,this.status=i,this.details=n}},Y=class extends Error{static{s(this,"CliUsageError")}command;constructor(e,r){super(e),this.name="CliUsageError",this.command=r}};function et(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}s(et,"isArrayBuffer");var tt=1;function Ut(t){let e=0;for(;e<t.length;){let r=t[e];if(r<=127){e+=1;continue}let i=0,n=0,o=0;if(r>=194&&r<=223)i=1,n=128,o=r&31;else if(r>=224&&r<=239)i=2,n=2048,o=r&15;else if(r>=240&&r<=244)i=3,n=65536,o=r&7;else return!1;if(e+i>=t.length)return!1;for(let a=1;a<=i;a+=1){let c=t[e+a];if((c&192)!==128)return!1;o=o<<6|c&63}if(o<n||o>1114111||o>=55296&&o<=57343)return!1;e+=i+1}return!0}s(Ut,"isValidUtf8");var K=class{constructor(e){this.client=e}client;static{s(this,"FsResource")}async read(e){let r=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!et(r)||!Ut(new Uint8Array(r)))return r;let i=new TextDecoder("utf-8").decode(r);try{return JSON.parse(i)}catch{return i}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:tt}:{}}})}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:tt}:{}},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 it(t,e,r,i){let n=t.length+e,o=r.length+i;if(n!==o)return n>o;for(let a=0;a<n;a++){let c=a<t.length?t[a]:"0",u=a<r.length?r[a]:"0";if(c!==u)return c>u}return!1}s(it,"scaledIntegerGreater");function Nt(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let r=e.groups.whole,i=e.groups.fraction??"",n=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(n))return!0;let o=(r+i).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=n-i.length;return a>=0?it(o,a,rt,0):it(o,0,rt,-a)}s(Nt,"numberOutsideSafeRange");function Lt(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 r=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(r){if(Nt(r[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=r[0].length;continue}}e++}}s(Lt,"validateJSONNumberTokens");function Ie(t,e,r){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(r.has(t))throw new TypeError(`${e} must not contain circular references`);if(r.add(t),Array.isArray(t))t.forEach((i,n)=>Ie(i,`${e}[${n}]`,r));else{let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[n,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);Ie(o.value,`${e}.${n}`,r)}}r.delete(t)}}s(Ie,"assertPlainJSONData");function $(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");Ie(t,"args",new Set);let e=JSON.stringify(t);return st(e),e}s($,"serializeStructuredArgs");function st(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Lt(t)}s(st,"validateSerializedArgs");function B(t,e,r){let i=Object.entries(t).filter(([n,o])=>o!==void 0&&(r===void 0||n!==e));return r!==void 0&&(st(r),i.push([e,r])),`{${i.map(([n,o])=>{let a=n===e&&r!==void 0?r:JSON.stringify(o);return`${JSON.stringify(n)}:${a}`}).join(",")}}`}s(B,"objectWithRawJSONField");var z=class{constructor(e){this.client=e}client;static{s(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,$(e.args))}async _executeSerializedArgs(e,r){return this.client._requireAuth(),this.request(e,r)}request(e,r){let i={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...r===void 0?{body:i}:{jsonBody:B(i,"args",r)},timeoutMs:e.timeout_ms})}};var X=class{constructor(e){this.client=e}client;static{s(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,$(e.args))}async _createSerializedArgs(e,r){return this.client._requireAuth(),this.createRequest(e,r)}createRequest(e,r){let i={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...r===void 0?{body:i}:{jsonBody:B(i,"args",r)}})}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,$(e.args))}async _updateSerializedArgs(e,r){return this.client._requireAuth(),this.updateRequest(e,r)}updateRequest(e,r){let{id:i,...n}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...r===void 0?{body:n}:{jsonBody:B(n,"args",r)}})}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 Z=class{constructor(e){this.client=e}client;static{s(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var ee=class{constructor(e){this.client=e}client;static{s(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url}})}};var re=class{constructor(e){this.client=e}client;static{s(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let r=te(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(r))}/stop`)}async resume(e){this.client._requireAuth();let r=te(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(r))}/resume`)}async delete(e){this.client._requireAuth();let r=te(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(r))}`)}async setVisibility(e){this.client._requireAuth();let r=te(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(r))}/visibility`,{body:{visibility:e.visibility}})}};function te(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}s(te,"requireFeedID");var Ot=`
2
2
  query ToolkitAutomationAlertDelivery($automationId: ID!) {
3
3
  automation(id: $automationId) {
4
4
  alertDelivery {
@@ -23,7 +23,7 @@ mutation ToolkitUpdateAutomationAlertDelivery(
23
23
  }
24
24
  }
25
25
  }
26
- `.trim(),S=class{constructor(e){this.client=e;this.delivery=new Q(e)}client;static{s(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let i=jt(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(i))}`)}async update(e){this.client._requireAuth();let i=Ie(e.id);if(!Mt(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(i))}`,{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)}},Q=class{constructor(e){this.client=e}client;static{s(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let i=Ie(e.id),n=(await this.graphql(Ot,{automationId:i})).automation?.alertDelivery;if(!n)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return n}async update(e){this.client._requireAuth();let i=Ie(e.id),r=e.alvaChannelIds!==void 0,n=e.emailEnabled!==void 0;if(!r&&!n)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=r?$t(e.alvaChannelIds??[]):void 0,c=(await this.graphql(Dt,{input:{automationId:i,...r?{alvaChannelIds:o}:{},...n?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:r,includeEmail:n})).updateAutomationAlertDelivery;if(!c)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return c}async graphql(e,i){let r=await this.client._request("POST","/query",{body:{query:e,variables:i}});if(!r)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(r.errors&&r.errors.length>0)throw new l("GRAPHQL_ERROR",Bt(r.errors),400,{errors:r.errors});if(!r.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};function jt(t){if(!Number.isInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}s(jt,"requireAutomationID");function Ie(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}s(Ie,"requireAutomationIDString");function Mt(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}s(Mt,"hasAutomationUpdate");function $t(t){let e=[...new Set(t)];for(let i of e)if(!/^(0|[1-9]\d*)$/.test(i))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}s($t,"uniqueAlvaChannelIDs");function Bt(t){let e=t.map(i=>i&&typeof i.message=="string"&&i.message?i.message:void 0).filter(i=>!!i);return e.length>0?e.join("; "):"GraphQL request failed"}s(Bt,"graphQLErrorMessage");var nt=["public","private","paid"];var re=class{constructor(e){this.client=e}client;static{s(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let i={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(i.limit=String(e.limit)),e.cursor&&(i.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:i})}async listOwn(e={}){let i={};return e.filter&&(i.filter=e.filter),e.limit!==void 0&&e.limit>0&&(i.limit=String(e.limit)),e.cursor&&(i.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:i})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let i=e.ref.indexOf("/");if(i<=0||i===e.ref.length-1)throw new l("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let r=e.ref.slice(0,i),n=e.ref.slice(i+1),o;for(;;){let a=await this.listByOwner({owner:r,cursor:o,limit:100}),c=a.items.find(u=>u.name===n);if(c)return c;if(!a.has_next||!a.next_cursor)return null;o=a.next_cursor}}throw new l("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let i={};e.cursor&&(i.cursor=e.cursor),e.current&&(i.current=e.current),e.limit!==void 0&&(i.limit=e.limit),e.dir&&(i.dir=e.dir),e.sort&&(i.sort=e.sort),e.keyword&&(i.keyword=e.keyword),e.tags&&e.tags.length>0&&(i.tags=e.tags.join(","));let r=await this.client._request("GET","/api/v1/playbooks/trending",{query:i}),n=Qt(this.client.baseUrl);return{playbooks:(r.playbooks??[]).map(o=>Wt(o,n)),has_next:r.has_next??!1}}async setVisibility(e){if(!nt.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${nt.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Qt(t){try{let e=new URL(t).hostname,i=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(i){let r=i[1].toLowerCase();return r==="prd"?"https://alva.ai":`https://${r}.alva.ai`}}catch{}return"https://alva.ai"}s(Qt,"webOriginFromApiBase");function Wt(t,e){let i=t.creator?.name??"",r=t.name??"",n=i&&r?`${i}/${r}`:r,o=i&&r?`/u/${i}/playbooks/${r}`:"";return{id:t.id===void 0?"":String(t.id),ref:n,username:i,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??""}}s(Wt,"toAgentPlaybook");var se=class{constructor(e){this.client=e}client;static{s(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let i=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${i}`)}async update(e){this.client._requireAuth();let i=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${i}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let i=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${i}`)}};var ne=class{constructor(e){this.client=e}client;static{s(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let i=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${i}/summary`)}};var ot=[{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 at(t,e){return ot.find(i=>i.skill===t&&i.file===e)}s(at,"getSkillEndpointMetadata");function Ge(t){return ot.filter(e=>e.skill===t)}s(Ge,"listSkillEndpointMetadata");var oe=class{constructor(e){this.client=e}client;static{s(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(i=>({...i,...lt(i.name)}))}}async summary(e){let i=encodeURIComponent(e.name),n=(await this.client._request("GET",`/api/v1/skills/${i}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!n)throw new Error(`empty skills summary response for "${e.name}"`);let o=Ge(e.name);return{...n,...lt(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let i=encodeURIComponent(e.name),n=(await this.client._request("GET",`/api/v1/skills/${i}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!n)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=at(e.name,e.file);return{...n,...o?{metadata:o}:{}}}};function lt(t){let e=Ge(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}s(lt,"metadataSummaryForSkill");function ct(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}s(ct,"normalizePlaybookSkillSummary");function ut(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new l("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}s(ut,"parsePlaybookSkillId");var ae=class{constructor(e){this.client=e}client;static{s(this,"PlaybookSkillsResource")}async list(e){let i={};return e?.tag&&(i.tag=e.tag),e?.username&&(i.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:i})).data??[]).map(ct)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:i,name:r}=ut(e),n=encodeURIComponent(i),o=encodeURIComponent(r),c=(await this.client._request("GET",`/api/v1/skills/${n}/${o}`)).data?.[0];if(!c)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...ct(c),files:c.files??[]}}async file(e,i){let{username:r,name:n}=ut(e),o=encodeURIComponent(r),a=encodeURIComponent(n),c=i.split("/").map(encodeURIComponent).join("/"),m=(await this.client._request("GET",`/api/v1/skills/${o}/${a}/files/${c}`)).data?.[0];if(!m)throw new l("NOT_FOUND",`empty playbook skills file response for ${e} path ${i}`,0);return m}};var le=class{constructor(e){this.client=e}client;static{s(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var ce=class{constructor(e){this.client=e}client;static{s(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var ue=class{constructor(e){this.client=e}client;static{s(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var pe=class{constructor(e){this.client=e}client;static{s(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var de=class{constructor(e){this.client=e}client;static{s(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var me=class{constructor(e){this.client=e}client;static{s(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var ye=class{constructor(e){this.client=e}client;static{s(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var fe=class{constructor(e){this.client=e}client;static{s(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let i=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",i,{query:Vt(e)})}};function Vt(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}s(Vt,"buildQuery");var he=class{constructor(e){this.client=e}client;static{s(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var ge=class{constructor(e){this.client=e}client;static{s(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let i=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",i)}async unfollowPlaybook(e){this.client._requireAuth();let i=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",i)}async subscribeFeed(e){this.client._requireAuth();let i=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",i):this.client._request("POST",i,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let i=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",i)}async list(e={}){this.client._requireAuth();let i={};return e.first!==void 0&&e.first>0&&(i.first=String(e.first)),e.cursor&&(i.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:i})}async follows(e={}){this.client._requireAuth();let i={};return e.limit!==void 0&&e.limit>0&&(i.limit=String(e.limit)),e.cursor&&(i.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:i})}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 T=class{constructor(e){this.client=e}client;static{s(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var be=class{constructor(e){this.client=e}client;static{s(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:pt(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:pt(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 pt(t){return`{"session_id":${dt(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${dt(t.target_id)}}`}s(pt,"mutationBody");function dt(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}s(dt,"idLiteral");var ke=class{constructor(e){this.client=e}client;static{s(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var _e=class{constructor(e){this.client=e}client;static{s(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let i=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{...i,result:Jt(i.result)}}async getAllowance(e){this.client._requireAuth();let i=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return Fe(i.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(i=>Fe(i)).filter(i=>i!==null)}}async createAllowance(e){this.client._requireAuth();let i=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:Ht(i.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 Fe(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},i=mt(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),r=mt(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return i!==void 0&&(e.created_at_ms=i),r!==void 0&&(e.updated_at_ms=r),e}s(Fe,"normalizeAllowance");function Ht(t){let e=Fe(t);if(!e)throw new Error("allowance response missing allowance");return e}s(Ht,"requireAllowance");function mt(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let n=Number(t);if(Number.isFinite(n))return n;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}if(typeof t!="object")return;let e=t,i=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(!(i===void 0||!Number.isFinite(i)))return i*1e3+Math.floor((Number.isFinite(r)?r:0)/1e6)}s(mt,"timestampMs");function Jt(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}s(Jt,"parseResultPayload");var Yt=`
26
+ `.trim(),A=class{constructor(e){this.client=e;this.delivery=new Q(e)}client;static{s(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let r=jt(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(r))}`)}async update(e){this.client._requireAuth();let r=ie(e.id);if(!Mt(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(r))}`,{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)}},Q=class{constructor(e){this.client=e}client;static{s(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let r=ie(e.id),n=(await this.graphql(Ot,{automationId:r})).automation?.alertDelivery;if(!n)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return n}async update(e){this.client._requireAuth();let r=ie(e.id),i=e.alvaChannelIds!==void 0,n=e.emailEnabled!==void 0;if(!i&&!n)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=i?$t(e.alvaChannelIds??[]):void 0,c=(await this.graphql(Dt,{input:{automationId:r,...i?{alvaChannelIds:o}:{},...n?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,includeEmail:n})).updateAutomationAlertDelivery;if(!c)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return c}async graphql(e,r){let i=await this.client._request("POST","/query",{body:{query:e,variables:r}});if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Bt(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};function jt(t){if(typeof t=="string")return ie(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}s(jt,"requireAutomationID");function ie(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}s(ie,"requireAutomationIDString");function Mt(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}s(Mt,"hasAutomationUpdate");function $t(t){let e=[...new Set(t)];for(let r of e)if(!/^(0|[1-9]\d*)$/.test(r))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}s($t,"uniqueAlvaChannelIDs");function Bt(t){let e=t.map(r=>r&&typeof r.message=="string"&&r.message?r.message:void 0).filter(r=>!!r);return e.length>0?e.join("; "):"GraphQL request failed"}s(Bt,"graphQLErrorMessage");var nt=["public","private","paid"];var se=class{constructor(e){this.client=e}client;static{s(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let r={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(r.limit=String(e.limit)),e.cursor&&(r.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:r})}async listOwn(e={}){let r={};return e.filter&&(r.filter=e.filter),e.limit!==void 0&&e.limit>0&&(r.limit=String(e.limit)),e.cursor&&(r.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:r})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let r=e.ref.indexOf("/");if(r<=0||r===e.ref.length-1)throw new l("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let i=e.ref.slice(0,r),n=e.ref.slice(r+1),o;for(;;){let a=await this.listByOwner({owner:i,cursor:o,limit:100}),c=a.items.find(u=>u.name===n);if(c)return c;if(!a.has_next||!a.next_cursor)return null;o=a.next_cursor}}throw new l("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let r={};e.cursor&&(r.cursor=e.cursor),e.current&&(r.current=e.current),e.limit!==void 0&&(r.limit=e.limit),e.dir&&(r.dir=e.dir),e.sort&&(r.sort=e.sort),e.keyword&&(r.keyword=e.keyword),e.tags&&e.tags.length>0&&(r.tags=e.tags.join(","));let i=await this.client._request("GET","/api/v1/playbooks/trending",{query:r}),n=Qt(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(o=>Wt(o,n)),has_next:i.has_next??!1}}async setVisibility(e){if(!nt.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${nt.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Qt(t){try{let e=new URL(t).hostname,r=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(r){let i=r[1].toLowerCase();return i==="prd"?"https://alva.ai":`https://${i}.alva.ai`}}catch{}return"https://alva.ai"}s(Qt,"webOriginFromApiBase");function Wt(t,e){let r=t.creator?.name??"",i=t.name??"",n=r&&i?`${r}/${i}`:i,o=r&&i?`/u/${r}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:n,username:r,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}s(Wt,"toAgentPlaybook");var ne=class{constructor(e){this.client=e}client;static{s(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let r=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${r}`)}async update(e){this.client._requireAuth();let r=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${r}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let r=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${r}`)}};var oe=class{constructor(e){this.client=e}client;static{s(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let r=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${r}/summary`)}};var ot=[{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 at(t,e){return ot.find(r=>r.skill===t&&r.file===e)}s(at,"getSkillEndpointMetadata");function Ge(t){return ot.filter(e=>e.skill===t)}s(Ge,"listSkillEndpointMetadata");var ae=class{constructor(e){this.client=e}client;static{s(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(r=>({...r,...lt(r.name)}))}}async summary(e){let r=encodeURIComponent(e.name),n=(await this.client._request("GET",`/api/v1/skills/${r}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!n)throw new Error(`empty skills summary response for "${e.name}"`);let o=Ge(e.name);return{...n,...lt(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let r=encodeURIComponent(e.name),n=(await this.client._request("GET",`/api/v1/skills/${r}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!n)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=at(e.name,e.file);return{...n,...o?{metadata:o}:{}}}};function lt(t){let e=Ge(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}s(lt,"metadataSummaryForSkill");function ct(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}s(ct,"normalizePlaybookSkillSummary");function ut(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new l("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}s(ut,"parsePlaybookSkillId");var le=class{constructor(e){this.client=e}client;static{s(this,"PlaybookSkillsResource")}async list(e){let r={};return e?.tag&&(r.tag=e.tag),e?.username&&(r.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:r})).data??[]).map(ct)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:r,name:i}=ut(e),n=encodeURIComponent(r),o=encodeURIComponent(i),c=(await this.client._request("GET",`/api/v1/skills/${n}/${o}`)).data?.[0];if(!c)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...ct(c),files:c.files??[]}}async file(e,r){let{username:i,name:n}=ut(e),o=encodeURIComponent(i),a=encodeURIComponent(n),c=r.split("/").map(encodeURIComponent).join("/"),m=(await this.client._request("GET",`/api/v1/skills/${o}/${a}/files/${c}`)).data?.[0];if(!m)throw new l("NOT_FOUND",`empty playbook skills file response for ${e} path ${r}`,0);return m}};var ce=class{constructor(e){this.client=e}client;static{s(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var ue=class{constructor(e){this.client=e}client;static{s(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var pe=class{constructor(e){this.client=e}client;static{s(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var de=class{constructor(e){this.client=e}client;static{s(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var me=class{constructor(e){this.client=e}client;static{s(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var ye=class{constructor(e){this.client=e}client;static{s(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var fe=class{constructor(e){this.client=e}client;static{s(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var he=class{constructor(e){this.client=e}client;static{s(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let r=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",r,{query:Vt(e)})}};function Vt(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}s(Vt,"buildQuery");var ge=class{constructor(e){this.client=e}client;static{s(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var be=class{constructor(e){this.client=e}client;static{s(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let r=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",r)}async unfollowPlaybook(e){this.client._requireAuth();let r=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",r)}async subscribeFeed(e){this.client._requireAuth();let r=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",r):this.client._request("POST",r,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let r=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",r)}async list(e={}){this.client._requireAuth();let r={};return e.first!==void 0&&e.first>0&&(r.first=String(e.first)),e.cursor&&(r.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:r})}async follows(e={}){this.client._requireAuth();let r={};return e.limit!==void 0&&e.limit>0&&(r.limit=String(e.limit)),e.cursor&&(r.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:r})}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 T=class{constructor(e){this.client=e}client;static{s(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var ke=class{constructor(e){this.client=e}client;static{s(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:pt(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:pt(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 pt(t){return`{"session_id":${dt(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${dt(t.target_id)}}`}s(pt,"mutationBody");function dt(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}s(dt,"idLiteral");var _e=class{constructor(e){this.client=e}client;static{s(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var Re=class{constructor(e){this.client=e}client;static{s(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let r=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{...r,result:Jt(r.result)}}async getAllowance(e){this.client._requireAuth();let r=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return Fe(r.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(r=>Fe(r)).filter(r=>r!==null)}}async createAllowance(e){this.client._requireAuth();let r=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:Ht(r.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 Fe(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},r=mt(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=mt(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return r!==void 0&&(e.created_at_ms=r),i!==void 0&&(e.updated_at_ms=i),e}s(Fe,"normalizeAllowance");function Ht(t){let e=Fe(t);if(!e)throw new Error("allowance response missing allowance");return e}s(Ht,"requireAllowance");function mt(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let n=Number(t);if(Number.isFinite(n))return n;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}if(typeof t!="object")return;let e=t,r=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,i=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(r===void 0||!Number.isFinite(r)))return r*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}s(mt,"timestampMs");function Jt(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}s(Jt,"parseResultPayload");var Yt=`
27
27
  query ToolkitCreditWallet {
28
28
  viewer {
29
29
  creditWallet {
@@ -65,7 +65,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
65
65
  }
66
66
  }
67
67
  }
68
- `.trim();function zt(t){let e=t.map(i=>typeof i.message=="string"&&i.message?i.message:void 0).filter(i=>!!i);return e.length>0?e.join("; "):"GraphQL request failed"}s(zt,"graphQLErrorMessage");var Re=class{constructor(e){this.client=e}client;static{s(this,"CreditsResource")}async wallet(){this.client._requireAuth();let i=(await this.graphql(Yt)).viewer?.creditWallet;if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return i}async items(e){this.client._requireAuth();let r=(await this.graphql(Kt,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!r)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return r}async graphql(e,i){let r=await this.client._request("POST","/query",{body:i===void 0?{query:e}:{query:e,variables:i}});if(r.errors&&r.errors.length>0)throw new l("GRAPHQL_ERROR",zt(r.errors),400,{errors:r.errors});if(!r.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var Xt=["Q1","Q2","Q3","Q4"],Zt=["latest-completed","next-confirmed"],ei=`
68
+ `.trim();function zt(t){let e=t.map(r=>typeof r.message=="string"&&r.message?r.message:void 0).filter(r=>!!r);return e.length>0?e.join("; "):"GraphQL request failed"}s(zt,"graphQLErrorMessage");var Pe=class{constructor(e){this.client=e}client;static{s(this,"CreditsResource")}async wallet(){this.client._requireAuth();let r=(await this.graphql(Yt)).viewer?.creditWallet;if(!r)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return r}async items(e){this.client._requireAuth();let i=(await this.graphql(Kt,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return i}async graphql(e,r){let i=await this.client._request("POST","/query",{body:r===void 0?{query:e}:{query:e,variables:r}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",zt(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var Xt=["Q1","Q2","Q3","Q4"],Zt=["latest-completed","next-confirmed"],er=`
69
69
  query ToolkitCompanyNarrative($ticker: String!) {
70
70
  market {
71
71
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -91,7 +91,7 @@ query ToolkitCompanyNarrative($ticker: String!) {
91
91
  }
92
92
  }
93
93
  }
94
- `.trim(),ti=`
94
+ `.trim(),tr=`
95
95
  query ToolkitCompanyEarningsCatalog($ticker: String!) {
96
96
  market {
97
97
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -122,7 +122,7 @@ query ToolkitCompanyEarningsCatalog($ticker: String!) {
122
122
  }
123
123
  }
124
124
  }
125
- `.trim(),ii=`
125
+ `.trim(),rr=`
126
126
  query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
127
127
  market {
128
128
  entity(input: { ticker: $ticker, kind: STOCK }) {
@@ -192,5 +192,5 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
192
192
  }
193
193
  }
194
194
  }
195
- `.trim();function ri(t){let e=t.map(i=>typeof i.message=="string"&&i.message?i.message:void 0).filter(i=>!!i);return e.length>0?e.join("; "):"GraphQL request failed"}s(ri,"graphQLErrorMessage");function Ue(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}s(Ue,"normalizedTicker");var w=class{constructor(e){this.client=e}client;static{s(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let i=Ue(e),n=(await this.graphql(ei,{ticker:i})).market?.entity;if(!n)throw this.notFound(i);return{ticker:n.ticker,current:n.companyInsight,history:n.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let i=Ue(e),n=(await this.graphql(ti,{ticker:i})).market?.entity;if(!n)throw this.notFound(i);if(!n.earningsPeriods)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${n.ticker}`,404,{ticker:n.ticker});return n.earningsPeriods}async earnings(e){this.client._requireAuth();let i=Ue(e.ticker),r=e.event,n=e.fiscalYear,o=e.fiscalQuarter;if(r!==void 0&&(n!==void 0||o!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(n===void 0!=(o===void 0))throw new l("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(r!==void 0&&!Zt.includes(r))throw new l("INVALID_ARGUMENT",`Unknown earnings event selector: ${r}`,400);if(n!==void 0&&(!Number.isInteger(n)||n<1900||n>9999))throw new l("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!Xt.includes(o))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let c,u;if(n!==void 0&&o!==void 0)c=n,u=o;else{let _=r??"latest-completed",C=await this.earningsPeriods(i),R=this.selectPeriod(C,_,i);c=R.fiscalYear,u=R.fiscalQuarter}let p=(await this.graphql(ii,{ticker:i,input:{fiscalYear:c,fiscalQuarter:u}})).market?.entity;if(!p)throw this.notFound(i);if(!p.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${p.ticker} FY${c} ${u}`,404,{ticker:p.ticker,fiscalYear:c,fiscalQuarter:u});return{ticker:p.ticker,...p.earnings}}selectPeriod(e,i,r){if(i==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let n=e.periods.filter(o=>o.status==="UPCOMING").sort((o,a)=>o.earningsDate.localeCompare(a.earningsDate));if(n.length>0)return n[0]}throw new l("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${i} earnings event is available for ${r}`,404,{ticker:r,event:i})}notFound(e){return new l("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,i){let r=await this.client._request("POST","/query",{body:{query:e,variables:i}});if(r.errors&&r.errors.length>0)throw new l("GRAPHQL_ERROR",ri(r.errors),400,{errors:r.errors});if(!r.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var si="https://api-llm.prd.alva.ai",ni="https://data-tools.prd.space.id";function Ne(t){return typeof t=="object"&&t!==null}s(Ne,"isRecord");function Pe(t,e){if(!Ne(t))return;let i=t[e];return typeof i=="string"&&i?i:void 0}s(Pe,"stringField");function oi(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=Pe(t,"code");r&&(e.code=r)}else if(Ne(t)){let r=Pe(t,"code"),n=Pe(t,"name"),o=Pe(t,"message");r&&(e.code=r),n&&(e.name=n),o&&(e.message=o)}else e.message=String(t);let i=[e.code,e.name,e.message].filter(r=>!!r);return{message:i.length>0?i.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}s(oi,"describeCause");function ai(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",i={};t instanceof Error?(i.name=t.name,i.message=t.message):i.message=String(t);let{message:r,details:n}=oi(Ne(t)?t.cause:void 0);return n&&(i.cause=n),{message:r?`${e}; cause: ${r}`:e,details:i}}s(ai,"describeFetchFailure");var ve=class{static{s(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;constructor(e){this.baseUrl=e.baseUrl??si,this.arraysBaseUrl=e.arraysBaseUrl??ni,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 K(this)}get run(){return this._run??=new z(this)}get deploy(){return this._deploy??=new X(this)}get serviceAccount(){return this._serviceAccount??=new Z(this)}get release(){return this._release??=new ee(this)}get feed(){return this._feed??=new ie(this)}get automation(){return this._automation??=new S(this)}get playbooks(){return this._playbooks??=new re(this)}get secrets(){return this._secrets??=new se(this)}get sdk(){return this._sdk??=new ne(this)}get dataSkills(){return this._dataSkills??=new oe(this)}get playbookSkills(){return this._playbookSkills??=new ae(this)}get comments(){return this._comments??=new le(this)}get remix(){return this._remix??=new ce(this)}get screenshot(){return this._screenshot??=new ue(this)}get user(){return this._user??=new pe(this)}get trading(){return this._trading??=new de(this)}get portfolio(){return this._portfolio??=new me(this)}get arraysJwt(){return this._arraysJwt??=new ye(this)}get notifications(){return this._notifications??=new fe(this)}get notificationPreferences(){return this._notificationPreferences??=new he(this)}get subscriptions(){return this._subscriptions??=new ge(this)}get alerts(){return this._alerts??=new T(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new be(this)}get feedback(){return this._feedback??=new ke(this)}get functions(){return this._functions??=new _e(this)}get credits(){return this._credits??=new Re(this)}get markets(){return this._markets??=new w(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new l("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}async _request(e,i,r){let o=`${r?.baseUrl??this.baseUrl}${i}`;if(r?.query){let h=new URLSearchParams;for(let[b,Ee]of Object.entries(r.query))Ee!=null&&h.set(b,String(Ee));let P=h.toString();P&&(o+=`?${P}`)}let a={};r?.noAuth||(this.pbsvToken?(a.Authorization=`Bearer ${this.pbsvToken}`,a["X-Pbsv"]="1"):this.viewer_token?a["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(a["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(a["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(a["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(a["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!r?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let c;r?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",c=r.rawBody):r?.jsonBody!==void 0?(a["Content-Type"]="application/json",c=r.jsonBody):r?.body!==void 0&&(a["Content-Type"]="application/json",c=JSON.stringify(r.body));let u,m=r?.timeoutMs,p=r?.signal??this.signal;if(p?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${i}`,0,{method:e,path:i});let _=m!==void 0?new AbortController:void 0,C=!1,R,W;_&&m!==void 0&&(p&&(W=s(()=>_.abort(p.reason),"abortListener"),p.addEventListener("abort",W,{once:!0})),R=setTimeout(()=>{C=!0,_.abort(new Error(`Request timed out after ${m}ms while calling ${e} ${i}`))},m));let Le={method:e,headers:a,body:c,signal:_?.signal??p};m!==void 0&&(Le.timeout=m);try{u=await fetch(o,Le)}catch(h){if(p?.aborted&&!C)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${i}`,0,{method:e,path:i});if(C)throw new l("NETWORK_TIMEOUT",`Request timed out after ${m}ms while calling ${e} ${i}`,0,{method:e,path:i,timeout_ms:m});let P=ai(h);throw new l("NETWORK_ERROR",P.message,0,{method:e,path:i,...P.details})}finally{W&&p&&p.removeEventListener("abort",W),R!==void 0&&clearTimeout(R)}if(!u.ok){let h="";try{h=await Promise.resolve(u.text())}catch{h=""}if((u.headers.get("content-type")??"").includes("application/json")&&h)try{let b=JSON.parse(h);if(b.error)throw new l(b.error.code??"UNKNOWN",b.error.message??`HTTP ${u.status}`,u.status)}catch(b){if(b instanceof l)throw b}throw new l("UNKNOWN",`HTTP ${u.status}: ${h.slice(0,200)}`,u.status)}if(u.status===204)return;let Oe=(u.headers.get("content-type")??"").toLowerCase();return Oe.includes("application/json")||Oe.includes("+json")?u.json():u.arrayBuffer()}};var li="0.24.0";qe();return kt(ci);})();
195
+ `.trim();function ir(t){let e=t.map(r=>typeof r.message=="string"&&r.message?r.message:void 0).filter(r=>!!r);return e.length>0?e.join("; "):"GraphQL request failed"}s(ir,"graphQLErrorMessage");function Ue(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}s(Ue,"normalizedTicker");var w=class{constructor(e){this.client=e}client;static{s(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let r=Ue(e),n=(await this.graphql(er,{ticker:r})).market?.entity;if(!n)throw this.notFound(r);return{ticker:n.ticker,current:n.companyInsight,history:n.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let r=Ue(e),n=(await this.graphql(tr,{ticker:r})).market?.entity;if(!n)throw this.notFound(r);if(!n.earningsPeriods)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${n.ticker}`,404,{ticker:n.ticker});return n.earningsPeriods}async earnings(e){this.client._requireAuth();let r=Ue(e.ticker),i=e.event,n=e.fiscalYear,o=e.fiscalQuarter;if(i!==void 0&&(n!==void 0||o!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(n===void 0!=(o===void 0))throw new l("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(i!==void 0&&!Zt.includes(i))throw new l("INVALID_ARGUMENT",`Unknown earnings event selector: ${i}`,400);if(n!==void 0&&(!Number.isInteger(n)||n<1900||n>9999))throw new l("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!Xt.includes(o))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let c,u;if(n!==void 0&&o!==void 0)c=n,u=o;else{let _=i??"latest-completed",C=await this.earningsPeriods(r),R=this.selectPeriod(C,_,r);c=R.fiscalYear,u=R.fiscalQuarter}let p=(await this.graphql(rr,{ticker:r,input:{fiscalYear:c,fiscalQuarter:u}})).market?.entity;if(!p)throw this.notFound(r);if(!p.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${p.ticker} FY${c} ${u}`,404,{ticker:p.ticker,fiscalYear:c,fiscalQuarter:u});return{ticker:p.ticker,...p.earnings}}selectPeriod(e,r,i){if(r==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let n=e.periods.filter(o=>o.status==="UPCOMING").sort((o,a)=>o.earningsDate.localeCompare(a.earningsDate));if(n.length>0)return n[0]}throw new l("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${r} earnings event is available for ${i}`,404,{ticker:i,event:r})}notFound(e){return new l("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,r){let i=await this.client._request("POST","/query",{body:{query:e,variables:r}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",ir(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var sr="https://api-llm.prd.alva.ai",nr="https://data-tools.prd.space.id";function Ne(t){return typeof t=="object"&&t!==null}s(Ne,"isRecord");function ve(t,e){if(!Ne(t))return;let r=t[e];return typeof r=="string"&&r?r:void 0}s(ve,"stringField");function or(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let i=ve(t,"code");i&&(e.code=i)}else if(Ne(t)){let i=ve(t,"code"),n=ve(t,"name"),o=ve(t,"message");i&&(e.code=i),n&&(e.name=n),o&&(e.message=o)}else e.message=String(t);let r=[e.code,e.name,e.message].filter(i=>!!i);return{message:r.length>0?r.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}s(or,"describeCause");function ar(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",r={};t instanceof Error?(r.name=t.name,r.message=t.message):r.message=String(t);let{message:i,details:n}=or(Ne(t)?t.cause:void 0);return n&&(r.cause=n),{message:i?`${e}; cause: ${i}`:e,details:r}}s(ar,"describeFetchFailure");var Ee=class{static{s(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;constructor(e){this.baseUrl=e.baseUrl??sr,this.arraysBaseUrl=e.arraysBaseUrl??nr,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 K(this)}get run(){return this._run??=new z(this)}get deploy(){return this._deploy??=new X(this)}get serviceAccount(){return this._serviceAccount??=new Z(this)}get release(){return this._release??=new ee(this)}get feed(){return this._feed??=new re(this)}get automation(){return this._automation??=new A(this)}get playbooks(){return this._playbooks??=new se(this)}get secrets(){return this._secrets??=new ne(this)}get sdk(){return this._sdk??=new oe(this)}get dataSkills(){return this._dataSkills??=new ae(this)}get playbookSkills(){return this._playbookSkills??=new le(this)}get comments(){return this._comments??=new ce(this)}get remix(){return this._remix??=new ue(this)}get screenshot(){return this._screenshot??=new pe(this)}get user(){return this._user??=new de(this)}get trading(){return this._trading??=new me(this)}get portfolio(){return this._portfolio??=new ye(this)}get arraysJwt(){return this._arraysJwt??=new fe(this)}get notifications(){return this._notifications??=new he(this)}get notificationPreferences(){return this._notificationPreferences??=new ge(this)}get subscriptions(){return this._subscriptions??=new be(this)}get alerts(){return this._alerts??=new T(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new ke(this)}get feedback(){return this._feedback??=new _e(this)}get functions(){return this._functions??=new Re(this)}get credits(){return this._credits??=new Pe(this)}get markets(){return this._markets??=new w(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new l("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}async _request(e,r,i){let o=`${i?.baseUrl??this.baseUrl}${r}`;if(i?.query){let h=new URLSearchParams;for(let[b,Se]of Object.entries(i.query))Se!=null&&h.set(b,String(Se));let P=h.toString();P&&(o+=`?${P}`)}let a={};i?.noAuth||(this.pbsvToken?(a.Authorization=`Bearer ${this.pbsvToken}`,a["X-Pbsv"]="1"):this.viewer_token?a["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(a["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(a["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(a["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(a["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!i?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let c;i?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",c=i.rawBody):i?.jsonBody!==void 0?(a["Content-Type"]="application/json",c=i.jsonBody):i?.body!==void 0&&(a["Content-Type"]="application/json",c=JSON.stringify(i.body));let u,m=i?.timeoutMs,p=i?.signal??this.signal;if(p?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${r}`,0,{method:e,path:r});let _=m!==void 0?new AbortController:void 0,C=!1,R,W;_&&m!==void 0&&(p&&(W=s(()=>_.abort(p.reason),"abortListener"),p.addEventListener("abort",W,{once:!0})),R=setTimeout(()=>{C=!0,_.abort(new Error(`Request timed out after ${m}ms while calling ${e} ${r}`))},m));let Le={method:e,headers:a,body:c,signal:_?.signal??p};m!==void 0&&(Le.timeout=m);try{u=await fetch(o,Le)}catch(h){if(p?.aborted&&!C)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${r}`,0,{method:e,path:r});if(C)throw new l("NETWORK_TIMEOUT",`Request timed out after ${m}ms while calling ${e} ${r}`,0,{method:e,path:r,timeout_ms:m});let P=ar(h);throw new l("NETWORK_ERROR",P.message,0,{method:e,path:r,...P.details})}finally{W&&p&&p.removeEventListener("abort",W),R!==void 0&&clearTimeout(R)}if(!u.ok){let h="";try{h=await Promise.resolve(u.text())}catch{h=""}if((u.headers.get("content-type")??"").includes("application/json")&&h)try{let b=JSON.parse(h);if(b.error)throw new l(b.error.code??"UNKNOWN",b.error.message??`HTTP ${u.status}`,u.status)}catch(b){if(b instanceof l)throw b}throw new l("UNKNOWN",`HTTP ${u.status}: ${h.slice(0,200)}`,u.status)}if(u.status===204)return;let Oe=(u.headers.get("content-type")??"").toLowerCase();return Oe.includes("application/json")||Oe.includes("+json")?u.json():u.arrayBuffer()}};var lr="0.25.1";xe();return kt(cr);})();
196
196
  //# sourceMappingURL=browser.global.js.map