@alva-ai/toolkit 0.28.0-beta.0 → 0.28.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/browser.global.js +52 -16
- package/dist/browser.global.js.map +1 -1
- package/dist/cli.d.ts +190 -8
- package/dist/cli.js +993 -44
- package/dist/cli.js.map +1 -1
- package/dist/dispatch.d.ts +190 -8
- package/dist/dispatch.js +644 -20
- package/dist/dispatch.js.map +1 -1
- package/dist/index.cjs +613 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +189 -9
- package/dist/index.d.ts +189 -9
- package/dist/index.js +611 -25
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/browser.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AlvaToolkit=(()=>{var ne=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var $t=Object.prototype.hasOwnProperty;var i=(t,e)=>ne(t,"name",{value:e,configurable:!0});var Bt=(t,e)=>{for(var n in e)ne(t,n,{get:e[n],enumerable:!0})},Qt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jt(e))!$t.call(t,s)&&s!==n&&ne(t,s,{get:()=>e[s],enumerable:!(r=Mt(e,s))||r.enumerable});return t};var Wt=t=>Qt(ne({},"__esModule",{value:!0}),t);var ir={};Bt(ir,{AlertsResource:()=>U,AlvaClient:()=>De,AlvaError:()=>c,AutomationAlertDeliveryResource:()=>ee,AutomationResource:()=>F,CliUsageError:()=>se,ForYouResource:()=>N,MarketsResource:()=>G,PBSV_UPDATE_MESSAGE:()=>st,SUBSCRIBE_MANAGE_MESSAGE:()=>dt,SUBSCRIBE_PROPOSE_MESSAGE:()=>ct,SUBSCRIBE_RESULT_MESSAGE:()=>ut,SchedulesResource:()=>L,TradingPairsResource:()=>D,UDF_AUTH_REQUIRED_MESSAGE:()=>lt,UDF_CONSENT_REQUEST_MESSAGE:()=>ot,UDF_CONSENT_RESPONSE_MESSAGE:()=>at,UdfAuthRequiredError:()=>I,UdfConsentDeniedError:()=>Q,UdfConsentRequiredError:()=>B,UdfConsentTimeoutError:()=>W,UdfError:()=>f,UdfExecutionError:()=>J,UdfFunctionDisabledError:()=>H,UdfFunctionNotFoundError:()=>V,UdfInsufficientCredits:()=>Y,UdfPidMismatchError:()=>v,UdfRateLimitedError:()=>z,UdfTokenExpiredError:()=>j,UdfTokenInvalidError:()=>$,UdfTransportError:()=>x,VERSION:()=>rr,getViewerToken:()=>K,installPlaybookRuntime:()=>We,mapUdfErrorResponse:()=>Be,playbookIdFromToken:()=>$e,subscribe:()=>gt,udf:()=>bt});var f=class extends Error{static{i(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:r={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=r,this.status=s}},I=class extends f{static{i(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},j=class extends f{static{i(this,"UdfTokenExpiredError")}},$=class extends f{static{i(this,"UdfTokenInvalidError")}},v=class extends f{static{i(this,"UdfPidMismatchError")}},B=class extends f{static{i(this,"UdfConsentRequiredError")}},Q=class extends f{static{i(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},W=class extends f{static{i(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},Y=class extends f{static{i(this,"UdfInsufficientCredits")}},V=class extends f{static{i(this,"UdfFunctionNotFoundError")}},H=class extends f{static{i(this,"UdfFunctionDisabledError")}},z=class extends f{static{i(this,"UdfRateLimitedError")}},J=class extends f{static{i(this,"UdfExecutionError")}},x=class extends f{static{i(this,"UdfTransportError")}},st="alva:pbsv:update",ot="alva:udf:consent-request",at="alva:udf:consent-response",lt="alva:udf:auth-required",ct="alva:subscribe:propose",ut="alva:subscribe:result",dt="alva:subscribe:manage",pt="https://api-llm.prd.alva.ai",mt=300*1e3,M=null,b=null,je=pt,R=null,g=null,it=!1,re=new Map,ie=new Map,Yt=i(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Vt=i(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),$e=i(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Vt(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),K=i(()=>M,"getViewerToken"),q=i(()=>!!K(),"isAuthenticated"),Ht=i(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),zt=i(t=>{let e=new URLSearchParams(t.location.search);M=e.get("_pbsv"),b=e.get("parent_origin"),je=(e.get("api_origin")||pt).replace(/\/$/,""),R=$e(M),M&&Ht(t)},"parseBootParams"),ft=i(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Jt=i(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),Kt=i(t=>{let e=t;return{...e,result:Jt(e.result)}},"normalizeInvokeResponse"),yt=i(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),Be=i((t,e)=>{let n=t.error?.code||"TRANSPORT",r=t.error?.message||n,s=yt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new j(r,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new $(r,o);case"PBSV_PID_MISMATCH":return new v(r,o);case"CONSENT_REQUIRED":return new B(r,o);case"INSUFFICIENT_CREDITS":return new Y(r,o);case"FUNCTION_NOT_FOUND":return new V(r,o);case"FUNCTION_DISABLED":return new H(r,o);case"RESOURCE_EXHAUSTED":return new z(r,o);case"EXECUTION_FAILED":return new J(r,o);default:return new x(r,o)}},"mapUdfErrorResponse"),Xt=i(t=>{if(!g||!b||t.origin!==b||t.source!==g.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===st){typeof e.token=="string"&&e.token.length>0&&(M=e.token,R=$e(e.token));return}if(e.type===ut){if(typeof e.request_id!="string")return;let r=ie.get(e.request_id);if(!r)return;clearTimeout(r.timer),ie.delete(e.request_id),r.resolve(Yt(e.status));return}if(e.type!==at||typeof e.request_id!="string")return;let n=re.get(e.request_id);n&&(clearTimeout(n.timer),re.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),ht=i(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Zt=i(()=>{if(!R)return null;let t=Number(R);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),en=i(async(t,e)=>{if(!g||!b)return"denied";let n=b,r=ht();return new Promise(s=>{let o=setTimeout(()=>{re.delete(r),s("timeout")},mt);re.set(r,{resolve:s,timer:o}),g?.parent.postMessage({type:ot,request_id:r,playbook_id:t,min_allowance:e},n)})},"requestConsent"),tn=i(async t=>{if(!g||!b)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let r=b,s=ht();return new Promise(o=>{let l=setTimeout(()=>{ie.delete(s),o("timeout")},mt);ie.set(s,{resolve:o,timer:l}),g?.parent.postMessage({type:ct,request_id:s,playbook_id:R,feed:{owner:e,name:n}},r)})},"proposeSubscribe"),nn=i(()=>{!g||!b||g.parent.postMessage({type:dt,playbook_id:R},b)},"manageSubscriptions"),gt={propose:tn,manage:nn},rn=i(t=>{!g||!b||g.parent.postMessage({type:lt,function_name:t},b)},"requestAuthentication"),Qe=i(async(t,e,n=!1)=>{let r=K();if(!r)throw new I;if(!R)throw new v("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=Zt();if(!s)throw new v("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${je}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new x("Network error while invoking UDF.",{code:"TRANSPORT"})}let l=await ft(o);if(o.ok)return Kt(l);if(l.error?.code==="CONSENT_REQUIRED"&&!n){let a=yt(l),u=typeof a.playbook_id=="string"?a.playbook_id:R,d=typeof a.min_allowance_suggested=="number"?a.min_allowance_suggested:1,p=await en(u,d);if(p==="granted")return Qe(t,e,!0);throw p==="timeout"?new W:new Q}throw Be(l,o.status)},"call"),sn=i(async()=>{let t=K();if(!t)throw new I;if(!R)throw new v("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${je}/api/v1/service/functions`);e.searchParams.set("playbook_id",R);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),r=await ft(n);if(!n.ok)throw Be(r,n.status);let s=r.functions;return Array.isArray(s)?s:[]},"list"),Me=i((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),on=i(t=>{if(typeof t!="string")return t;let n=g?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),an=i((t,e)=>{if(!g)throw new Error("Playbook runtime is not installed.");let n=on(t),r=g.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",l=e.disabledLabel||"Sign in to run";return r.type="button",r.className="alva-udf-button",r.textContent=q()?s:l,r.disabled=!1,r.setAttribute("data-function-name",e.functionName),q()||r.setAttribute("aria-disabled","true"),r.addEventListener("click",async()=>{if(!q()){rn(e.functionName);return}if(!r.disabled){r.disabled=!0,r.textContent=o,Me(r,"alva:udf-button:loading",{functionName:e.functionName});try{let a=await Qe(e.functionName,e.params??{});Me(r,"alva:udf-button:result",{functionName:e.functionName,result:a})}catch(a){Me(r,"alva:udf-button:error",{functionName:e.functionName,error:a})}finally{r.disabled=!1,r.textContent=q()?s:l,q()||r.setAttribute("aria-disabled","true")}}}),n.appendChild(r),r},"renderButton"),bt={call:Qe,list:sn,getViewerToken:K,isAuthenticated:q,renderButton:an,UdfError:f,UdfAuthRequiredError:I,UdfTokenExpiredError:j,UdfTokenInvalidError:$,UdfPidMismatchError:v,UdfConsentRequiredError:B,UdfConsentDeniedError:Q,UdfConsentTimeoutError:W,UdfInsufficientCredits:Y,UdfFunctionNotFoundError:V,UdfFunctionDisabledError:H,UdfRateLimitedError:z,UdfExecutionError:J,UdfTransportError:x},We=i(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||it)return;g=e,it=!0,zt(e),e.addEventListener("message",Xt);let n=e,r=n.alva||{};n.alva={...r,udf:bt,subscribe:gt}},"installPlaybookRuntime");var c=class extends Error{static{i(this,"AlvaError")}code;status;details;constructor(e,n,r,s){super(n),this.name="AlvaError",this.code=e,this.status=r,this.details=s}},se=class extends Error{static{i(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function kt(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}i(kt,"isArrayBuffer");var Pt=1;function ln(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let r=0,s=0,o=0;if(n>=194&&n<=223)r=1,s=128,o=n&31;else if(n>=224&&n<=239)r=2,s=2048,o=n&15;else if(n>=240&&n<=244)r=3,s=65536,o=n&7;else return!1;if(e+r>=t.length)return!1;for(let l=1;l<=r;l+=1){let a=t[e+l];if((a&192)!==128)return!1;o=o<<6|a&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=r+1}return!0}i(ln,"isValidUtf8");var oe=class{constructor(e){this.client=e}client;static{i(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!kt(n)||!ln(new Uint8Array(n)))return n;let r=new TextDecoder("utf-8").decode(n);try{return JSON.parse(r)}catch{return r}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:Pt}:{}}})}async rawWrite(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{query:{path:e.path,mkdir_parents:e.mkdir_parents,...e.append?{flags:Pt}:{}},rawBody:e.body})}async stat(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/stat",{query:{path:e.path}})}async readdir(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readdir",{query:{path:e.path,recursive:e.recursive}})}async mkdir(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/mkdir",{body:{path:e.path}})}async remove(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/fs/remove",{query:{path:e.path,recursive:e.recursive}})}async rename(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/rename",{body:{old_path:e.old_path,new_path:e.new_path}})}async copy(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/copy",{body:{src_path:e.src_path,dst_path:e.dst_path}})}async symlink(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/symlink",{body:{target_path:e.target_path,link_path:e.link_path}})}async readlink(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readlink",{query:{path:e.path}})}async chmod(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/chmod",{body:{path:e.path,mode:e.mode}})}async grant(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/grant",{body:{path:e.path,subject:e.subject,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/revoke",{body:{path:e.path,subject:e.subject,permission:e.permission}})}};var Rt="9007199254740991";function _t(t,e,n,r){let s=t.length+e,o=n.length+r;if(s!==o)return s>o;for(let l=0;l<s;l++){let a=l<t.length?t[l]:"0",u=l<n.length?n[l]:"0";if(a!==u)return a>u}return!1}i(_t,"scaledIntegerGreater");function cn(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,r=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+r).replace(/^0+/,"")||"0";if(o==="0")return!1;let l=s-r.length;return l>=0?_t(o,l,Rt,0):_t(o,0,Rt,-l)}i(cn,"numberOutsideSafeRange");function un(t){let e=0;for(;e<t.length;){if(t[e]==='"'){for(e++;e<t.length;)if(t[e]==="\\")e+=2;else if(t[e++]==='"')break;continue}if(t[e]==="-"||/\d/.test(t[e]??"")){let n=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(n){if(cn(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}i(un,"validateJSONNumberTokens");function Ye(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((r,s)=>Ye(r,`${e}[${s}]`,n));else{let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);Ye(o.value,`${e}.${s}`,n)}}n.delete(t)}}i(Ye,"assertPlainJSONData");function X(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");Ye(t,"args",new Set);let e=JSON.stringify(t);return Et(e),e}i(X,"serializeStructuredArgs");function Et(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");un(t)}i(Et,"validateSerializedArgs");function Z(t,e,n){let r=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Et(n),r.push([e,n])),`{${r.map(([s,o])=>{let l=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${l}`}).join(",")}}`}i(Z,"objectWithRawJSONField");var ae=class{constructor(e){this.client=e}client;static{i(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,X(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let r={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:r}:{jsonBody:Z(r,"args",n)},timeoutMs:e.timeout_ms})}};var le=class{constructor(e){this.client=e}client;static{i(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,X(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let r={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:r}:{jsonBody:Z(r,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,X(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:r,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${r}`,{...n===void 0?{body:s}:{jsonBody:Z(s,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var ce=class{constructor(e){this.client=e}client;static{i(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var ue=class{constructor(e){this.client=e}client;static{i(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url}})}};var pe=class{constructor(e){this.client=e}client;static{i(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=de(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=de(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=de(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=de(e.id);if(e.visibility!=="public"&&e.visibility!=="private")throw new Error("visibility must be 'public' or 'private'");return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/visibility`,{body:{visibility:e.visibility}})}};function de(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}i(de,"requireFeedID");var dn=`
|
|
1
|
+
"use strict";var AlvaToolkit=(()=>{var he=Object.defineProperty;var cn=Object.getOwnPropertyDescriptor;var dn=Object.getOwnPropertyNames;var pn=Object.prototype.hasOwnProperty;var i=(t,e)=>he(t,"name",{value:e,configurable:!0});var mn=(t,e)=>{for(var n in e)he(t,n,{get:e[n],enumerable:!0})},hn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dn(e))!pn.call(t,s)&&s!==n&&he(t,s,{get:()=>e[s],enumerable:!(r=cn(e,s))||r.enumerable});return t};var fn=t=>hn(he({},"__esModule",{value:!0}),t);var Zr={};mn(Zr,{AlertsResource:()=>Q,AlvaClient:()=>Ze,AlvaError:()=>u,AutomationAlertDeliveryResource:()=>de,AutomationResource:()=>B,CliUsageError:()=>ge,ForYouResource:()=>j,MarketsResource:()=>W,PBSV_UPDATE_MESSAGE:()=>kt,SUBSCRIBE_MANAGE_MESSAGE:()=>At,SUBSCRIBE_PROPOSE_MESSAGE:()=>Et,SUBSCRIBE_RESULT_MESSAGE:()=>Tt,SchedulesResource:()=>V,StewardResource:()=>Y,ThesesResource:()=>J,TradingPairsResource:()=>H,UDF_AUTH_REQUIRED_MESSAGE:()=>St,UDF_CONSENT_REQUEST_MESSAGE:()=>wt,UDF_CONSENT_RESPONSE_MESSAGE:()=>vt,UdfAuthRequiredError:()=>M,UdfConsentDeniedError:()=>te,UdfConsentRequiredError:()=>ee,UdfConsentTimeoutError:()=>ne,UdfError:()=>y,UdfExecutionError:()=>ae,UdfFunctionDisabledError:()=>se,UdfFunctionNotFoundError:()=>ie,UdfInsufficientCredits:()=>re,UdfPidMismatchError:()=>C,UdfRateLimitedError:()=>oe,UdfTokenExpiredError:()=>X,UdfTokenInvalidError:()=>Z,UdfTransportError:()=>$,VERSION:()=>Xr,getViewerToken:()=>le,installPlaybookRuntime:()=>ot,mapUdfErrorResponse:()=>it,playbookIdFromToken:()=>rt,subscribe:()=>Dt,udf:()=>Ut});var y=class extends Error{static{i(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:r={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=r,this.status=s}},M=class extends y{static{i(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},X=class extends y{static{i(this,"UdfTokenExpiredError")}},Z=class extends y{static{i(this,"UdfTokenInvalidError")}},C=class extends y{static{i(this,"UdfPidMismatchError")}},ee=class extends y{static{i(this,"UdfConsentRequiredError")}},te=class extends y{static{i(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},ne=class extends y{static{i(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},re=class extends y{static{i(this,"UdfInsufficientCredits")}},ie=class extends y{static{i(this,"UdfFunctionNotFoundError")}},se=class extends y{static{i(this,"UdfFunctionDisabledError")}},oe=class extends y{static{i(this,"UdfRateLimitedError")}},ae=class extends y{static{i(this,"UdfExecutionError")}},$=class extends y{static{i(this,"UdfTransportError")}},kt="alva:pbsv:update",wt="alva:udf:consent-request",vt="alva:udf:consent-response",St="alva:udf:auth-required",Et="alva:subscribe:propose",Tt="alva:subscribe:result",At="alva:subscribe:manage",Ct="https://api-llm.prd.alva.ai",It=300*1e3,K=null,k=null,nt=Ct,S=null,b=null,Rt=!1,fe=new Map,ye=new Map,yn=i(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),gn=i(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),rt=i(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(gn(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),le=i(()=>K,"getViewerToken"),O=i(()=>!!le(),"isAuthenticated"),bn=i(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),_n=i(t=>{let e=new URLSearchParams(t.location.search);K=e.get("_pbsv"),k=e.get("parent_origin"),nt=(e.get("api_origin")||Ct).replace(/\/$/,""),S=rt(K),K&&bn(t)},"parseBootParams"),qt=i(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Pn=i(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),Rn=i(t=>{let e=t;return{...e,result:Pn(e.result)}},"normalizeInvokeResponse"),xt=i(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),it=i((t,e)=>{let n=t.error?.code||"TRANSPORT",r=t.error?.message||n,s=xt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new X(r,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new Z(r,o);case"PBSV_PID_MISMATCH":return new C(r,o);case"CONSENT_REQUIRED":return new ee(r,o);case"INSUFFICIENT_CREDITS":return new re(r,o);case"FUNCTION_NOT_FOUND":return new ie(r,o);case"FUNCTION_DISABLED":return new se(r,o);case"RESOURCE_EXHAUSTED":return new oe(r,o);case"EXECUTION_FAILED":return new ae(r,o);default:return new $(r,o)}},"mapUdfErrorResponse"),kn=i(t=>{if(!b||!k||t.origin!==k||t.source!==b.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===kt){typeof e.token=="string"&&e.token.length>0&&(K=e.token,S=rt(e.token));return}if(e.type===Tt){if(typeof e.request_id!="string")return;let r=ye.get(e.request_id);if(!r)return;clearTimeout(r.timer),ye.delete(e.request_id),r.resolve(yn(e.status));return}if(e.type!==vt||typeof e.request_id!="string")return;let n=fe.get(e.request_id);n&&(clearTimeout(n.timer),fe.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Nt=i(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),wn=i(()=>{if(!S)return null;let t=Number(S);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),vn=i(async(t,e)=>{if(!b||!k)return"denied";let n=k,r=Nt();return new Promise(s=>{let o=setTimeout(()=>{fe.delete(r),s("timeout")},It);fe.set(r,{resolve:s,timer:o}),b?.parent.postMessage({type:wt,request_id:r,playbook_id:t,min_allowance:e},n)})},"requestConsent"),Sn=i(async t=>{if(!b||!k)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let r=k,s=Nt();return new Promise(o=>{let a=setTimeout(()=>{ye.delete(s),o("timeout")},It);ye.set(s,{resolve:o,timer:a}),b?.parent.postMessage({type:Et,request_id:s,playbook_id:S,feed:{owner:e,name:n}},r)})},"proposeSubscribe"),En=i(()=>{!b||!k||b.parent.postMessage({type:At,playbook_id:S},k)},"manageSubscriptions"),Dt={propose:Sn,manage:En},Tn=i(t=>{!b||!k||b.parent.postMessage({type:St,function_name:t},k)},"requestAuthentication"),st=i(async(t,e,n=!1)=>{let r=le();if(!r)throw new M;if(!S)throw new C("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=wn();if(!s)throw new C("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${nt}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new $("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await qt(o);if(o.ok)return Rn(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let l=xt(a),c=typeof l.playbook_id=="string"?l.playbook_id:S,d=typeof l.min_allowance_suggested=="number"?l.min_allowance_suggested:1,p=await vn(c,d);if(p==="granted")return st(t,e,!0);throw p==="timeout"?new ne:new te}throw it(a,o.status)},"call"),An=i(async()=>{let t=le();if(!t)throw new M;if(!S)throw new C("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${nt}/api/v1/service/functions`);e.searchParams.set("playbook_id",S);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),r=await qt(n);if(!n.ok)throw it(r,n.status);let s=r.functions;return Array.isArray(s)?s:[]},"list"),tt=i((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),Cn=i(t=>{if(typeof t!="string")return t;let n=b?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),In=i((t,e)=>{if(!b)throw new Error("Playbook runtime is not installed.");let n=Cn(t),r=b.document.createElement("button"),s=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=O()?s:a,r.disabled=!1,r.setAttribute("data-function-name",e.functionName),O()||r.setAttribute("aria-disabled","true"),r.addEventListener("click",async()=>{if(!O()){Tn(e.functionName);return}if(!r.disabled){r.disabled=!0,r.textContent=o,tt(r,"alva:udf-button:loading",{functionName:e.functionName});try{let l=await st(e.functionName,e.params??{});tt(r,"alva:udf-button:result",{functionName:e.functionName,result:l})}catch(l){tt(r,"alva:udf-button:error",{functionName:e.functionName,error:l})}finally{r.disabled=!1,r.textContent=O()?s:a,O()||r.setAttribute("aria-disabled","true")}}}),n.appendChild(r),r},"renderButton"),Ut={call:st,list:An,getViewerToken:le,isAuthenticated:O,renderButton:In,UdfError:y,UdfAuthRequiredError:M,UdfTokenExpiredError:X,UdfTokenInvalidError:Z,UdfPidMismatchError:C,UdfConsentRequiredError:ee,UdfConsentDeniedError:te,UdfConsentTimeoutError:ne,UdfInsufficientCredits:re,UdfFunctionNotFoundError:ie,UdfFunctionDisabledError:se,UdfRateLimitedError:oe,UdfExecutionError:ae,UdfTransportError:$},ot=i(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||Rt)return;b=e,Rt=!0,_n(e),e.addEventListener("message",kn);let n=e,r=n.alva||{};n.alva={...r,udf:Ut,subscribe:Dt}},"installPlaybookRuntime");var u=class extends Error{static{i(this,"AlvaError")}code;status;details;constructor(e,n,r,s){super(n),this.name="AlvaError",this.code=e,this.status=r,this.details=s}},ge=class extends Error{static{i(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function Ft(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}i(Ft,"isArrayBuffer");var Gt=1;function qn(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let r=0,s=0,o=0;if(n>=194&&n<=223)r=1,s=128,o=n&31;else if(n>=224&&n<=239)r=2,s=2048,o=n&15;else if(n>=240&&n<=244)r=3,s=65536,o=n&7;else return!1;if(e+r>=t.length)return!1;for(let a=1;a<=r;a+=1){let l=t[e+a];if((l&192)!==128)return!1;o=o<<6|l&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=r+1}return!0}i(qn,"isValidUtf8");var be=class{constructor(e){this.client=e}client;static{i(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!Ft(n)||!qn(new Uint8Array(n)))return n;let r=new TextDecoder("utf-8").decode(n);try{return JSON.parse(r)}catch{return r}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:Gt}:{}}})}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:Gt}:{}},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 Lt="9007199254740991";function Ot(t,e,n,r){let s=t.length+e,o=n.length+r;if(s!==o)return s>o;for(let a=0;a<s;a++){let l=a<t.length?t[a]:"0",c=a<n.length?n[a]:"0";if(l!==c)return l>c}return!1}i(Ot,"scaledIntegerGreater");function xn(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,r=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+r).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=s-r.length;return a>=0?Ot(o,a,Lt,0):Ot(o,0,Lt,-a)}i(xn,"numberOutsideSafeRange");function Nn(t){let e=0;for(;e<t.length;){if(t[e]==='"'){for(e++;e<t.length;)if(t[e]==="\\")e+=2;else if(t[e++]==='"')break;continue}if(t[e]==="-"||/\d/.test(t[e]??"")){let n=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(n){if(xn(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}i(Nn,"validateJSONNumberTokens");function at(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((r,s)=>at(r,`${e}[${s}]`,n));else{let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);at(o.value,`${e}.${s}`,n)}}n.delete(t)}}i(at,"assertPlainJSONData");function ue(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");at(t,"args",new Set);let e=JSON.stringify(t);return Mt(e),e}i(ue,"serializeStructuredArgs");function Mt(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Nn(t)}i(Mt,"validateSerializedArgs");function ce(t,e,n){let r=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Mt(n),r.push([e,n])),`{${r.map(([s,o])=>{let a=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}i(ce,"objectWithRawJSONField");var _e=class{constructor(e){this.client=e}client;static{i(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,ue(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let r={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:r}:{jsonBody:ce(r,"args",n)},timeoutMs:e.timeout_ms})}};var Pe=class{constructor(e){this.client=e}client;static{i(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,ue(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let r={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:r}:{jsonBody:ce(r,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,ue(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:r,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${r}`,{...n===void 0?{body:s}:{jsonBody:ce(s,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var Re=class{constructor(e){this.client=e}client;static{i(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var ke=class{constructor(e){this.client=e}client;static{i(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url}})}};var ve=class{constructor(e){this.client=e}client;static{i(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=we(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=we(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=we(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=we(e.id);if(e.visibility!=="public"&&e.visibility!=="private")throw new Error("visibility must be 'public' or 'private'");return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/visibility`,{body:{visibility:e.visibility}})}};function we(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}i(we,"requireFeedID");var Dn=`
|
|
2
2
|
query ToolkitForYou($input: FeedEntryConnectionInput) {
|
|
3
3
|
viewer {
|
|
4
4
|
forYou(input: $input) {
|
|
@@ -25,7 +25,7 @@ query ToolkitForYou($input: FeedEntryConnectionInput) {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
`.trim();function
|
|
28
|
+
`.trim();function w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(w,"record");function Un(t){if(!w(t))throw new Error("For You parameters must be an object");let e=t.first===void 0?20:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw new Error("first must be an integer between 1 and 50");for(let n of["after","newerThan"]){let r=t[n];if(r!==void 0&&(typeof r!="string"||!r.trim()))throw new Error(`${n} must be a non-empty cursor`)}if(t.feedId!==void 0&&!Se(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}i(Un,"validateForYouListParams");function Se(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}i(Se,"isPositiveInt64");function N(){throw new u("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}i(N,"invalidResponse");function Fn(t){if(!w(t)||!Array.isArray(t.edges)||!w(t.pageInfo))return N();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return N();for(let s of t.edges){if(!w(s)||typeof s.cursor!="string"||!s.cursor.trim()||!w(s.node))return N();let o=s.node;if(typeof o.id!="string"||!o.id.startsWith("FeedEntry:")||!Se(o.id.slice(10))||!w(o.feed)||!Se(o.feed.id)||!w(o.major)||typeof o.major.id!="string"||!Se(o.major.feedId)||typeof o.title!="string"||typeof o.body!="string")return N()}let n=t.edges[0],r=t.edges[t.edges.length-1];return e.startCursor!==(n?.cursor??"")||e.endCursor!==(r?.cursor??"")||t.edges.length===0&&e.hasNextPage?N():t}i(Fn,"connection");var j=class{constructor(e){this.client=e}client;static{i(this,"ForYouResource")}async list(e={}){Un(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Dn,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});if(!w(n))return N();if(n.errors!==void 0){if(!Array.isArray(n.errors))return N();if(n.errors.length>0){let r=n.errors.flatMap(s=>w(s)&&typeof s.message=="string"?[s.message]:[]);throw new u("GRAPHQL_ERROR",r.join("; ")||"GraphQL request failed",400,{errors:n.errors})}}if(!w(n.data)||!w(n.data.viewer)||n.data.viewer.forYou==null)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.forYou",502);return Fn(n.data.viewer.forYou)}};var Gn=`
|
|
29
29
|
query ToolkitAutomationAlertDelivery($automationId: ID!) {
|
|
30
30
|
automation(id: $automationId) {
|
|
31
31
|
alertDelivery {
|
|
@@ -35,7 +35,7 @@ query ToolkitAutomationAlertDelivery($automationId: ID!) {
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
-
`.trim(),
|
|
38
|
+
`.trim(),Ln=`
|
|
39
39
|
mutation ToolkitUpdateAutomationAlertDelivery(
|
|
40
40
|
$input: UpdateAutomationAlertDeliveryInput!
|
|
41
41
|
$includeAlvaChannels: Boolean!
|
|
@@ -50,7 +50,7 @@ mutation ToolkitUpdateAutomationAlertDelivery(
|
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
|
-
`.trim(),F=class{constructor(e){this.client=e;this.delivery=new ee(e)}client;static{i(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=hn(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=fe(e.id);if(!gn(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(n))}`,{body:{version:e.version,cronjob_id:e.cronjob_id,description:e.description,changelog:e.changelog,agent_type:e.agent_type,trigger:e.trigger}})}stop(e){return this.client.feed.stop(e)}resume(e){return this.client.feed.resume(e)}delete(e){return this.client.feed.delete(e)}publish(e){return this.client.release.feed(e)}},ee=class{constructor(e){this.client=e}client;static{i(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=fe(e.id),s=(await this.graphql(fn,{automationId:n})).automation?.alertDelivery;if(!s)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=fe(e.id),r=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!r&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=r?bn(e.alvaChannelIds??[]):void 0,a=(await this.graphql(yn,{input:{automationId:n,...r?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:r,includeEmail:s})).updateAutomationAlertDelivery;if(!a)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return a}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!r)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(r.errors&&r.errors.length>0)throw new c("GRAPHQL_ERROR",kn(r.errors),400,{errors:r.errors});if(!r.data)throw new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};function hn(t){if(typeof t=="string")return fe(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}i(hn,"requireAutomationID");function fe(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}i(fe,"requireAutomationIDString");function gn(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}i(gn,"hasAutomationUpdate");function bn(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}i(bn,"uniqueAlvaChannelIDs");function kn(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}i(kn,"graphQLErrorMessage");var vt=["public","private","paid"];var ye=class{constructor(e){this.client=e}client;static{i(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new c("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let r=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let l=await this.listByOwner({owner:r,cursor:o,limit:100}),a=l.items.find(u=>u.name===s);if(a)return a;if(!l.has_next||!l.next_cursor)return null;o=l.next_cursor}}throw new c("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let n={};e.cursor&&(n.cursor=e.cursor),e.current&&(n.current=e.current),e.limit!==void 0&&(n.limit=e.limit),e.dir&&(n.dir=e.dir),e.sort&&(n.sort=e.sort),e.keyword&&(n.keyword=e.keyword),e.tags&&e.tags.length>0&&(n.tags=e.tags.join(","));let r=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=Pn(this.client.baseUrl);return{playbooks:(r.playbooks??[]).map(o=>Rn(o,s)),has_next:r.has_next??!1}}async setVisibility(e){if(!vt.includes(e.visibility))throw new c("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${vt.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Pn(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let r=n[1].toLowerCase();return r==="prd"?"https://alva.ai":`https://${r}.alva.ai`}}catch{}return"https://alva.ai"}i(Pn,"webOriginFromApiBase");function Rn(t,e){let n=t.creator?.name??"",r=t.name??"",s=n&&r?`${n}/${r}`:r,o=n&&r?`/u/${n}/playbooks/${r}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:r,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}i(Rn,"toAgentPlaybook");var he=class{constructor(e){this.client=e}client;static{i(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var ge=class{constructor(e){this.client=e}client;static{i(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var At=[{skill:"arrays-data-api-crypto-futures-data",file:"binance-perp-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/perp/usdt/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"binance-spot-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/spot/usdt/kline"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"fear-greed-index",method:"GET",path:"/api/v1/crypto/fear-greed-index"},{skill:"arrays-data-api-crypto-futures-data",file:"funding-rate",method:"GET",path:"/api/v1/crypto/funding-rate"},{skill:"arrays-data-api-crypto-futures-data",file:"hyperliquid-perp-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/perp/usdc/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"hyperliquid-spot-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/spot/usdc/kline"},{skill:"arrays-data-api-crypto-futures-data",file:"long-short-ratio",method:"GET",path:"/api/v1/crypto/long-short-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-market-cap",method:"GET",path:"/api/v1/crypto/market-cap"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"market-metrics",method:"GET",path:"/api/v1/crypto/market-metrics"},{skill:"arrays-data-api-crypto-futures-data",file:"open-interest",method:"GET",path:"/api/v1/crypto/open-interest"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics",method:"GET",path:"/api/v1/crypto/screener/metrics"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics-timerange",method:"GET",path:"/api/v1/crypto/screener/metrics/timerange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-detail",method:"GET",path:"/api/v1/crypto/detail"},{skill:"arrays-data-api-etf-fundamentals",file:"country-weightings",method:"GET",path:"/api/v1/etf/country-weightings"},{skill:"arrays-data-api-etf-fundamentals",file:"holdings",method:"GET",path:"/api/v1/etf/holdings"},{skill:"arrays-data-api-etf-fundamentals",file:"info",method:"GET",path:"/api/v1/etf/info"},{skill:"arrays-data-api-etf-fundamentals",file:"sector-weightings",method:"GET",path:"/api/v1/etf/sector-weightings"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-historical",method:"GET",path:"/api/v1/macro/commodity/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-real-time",method:"GET",path:"/api/v1/macro/commodity/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-symbol-list",method:"GET",path:"/api/v1/macro/commodity/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"economic-indicators",method:"GET",path:"/api/v1/macro/economic-indicators"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-historical",method:"GET",path:"/api/v1/macro/forex/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-real-time",method:"GET",path:"/api/v1/macro/forex/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-symbol-list",method:"GET",path:"/api/v1/macro/forex/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-historical",method:"GET",path:"/api/v1/macro/index/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-real-time",method:"GET",path:"/api/v1/macro/index/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"rates",method:"GET",path:"/api/v1/macro/treasury-rates"},{skill:"arrays-data-api-equity-fundamentals",file:"company-balance-sheets",method:"GET",path:"/api/v1/stocks/company/balance-sheets"},{skill:"arrays-data-api-equity-fundamentals",file:"company-cashflow-statements",method:"GET",path:"/api/v1/stocks/company/cashflow-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail",method:"GET",path:"/api/v1/stocks/company/detail"},{skill:"arrays-data-api-equity-fundamentals",file:"company-income-statements",method:"GET",path:"/api/v1/stocks/company/income-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-kpi",method:"GET",path:"/api/v1/stocks/company/kpi"},{skill:"arrays-data-api-equity-events",file:"crowdfunding-offerings",method:"GET",path:"/api/v1/stocks/crowdfunding/offerings"},{skill:"arrays-data-api-equity-events",file:"dividends",method:"GET",path:"/api/v1/stocks/dividends"},{skill:"arrays-data-api-equity-events",file:"earnings-calendar",method:"GET",path:"/api/v1/stocks/earnings-calendar"},{skill:"arrays-data-api-equity-events",file:"equity-offering",method:"GET",path:"/api/v1/stocks/equity-offering"},{skill:"arrays-data-api-stock-metrics",file:"financial-metrics",method:"GET",path:"/api/v1/stocks/financial-metrics"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates",method:"GET",path:"/api/v1/stocks/fiscal-dates"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates-range",method:"GET",path:"/api/v1/stocks/fiscal-dates/range"},{skill:"arrays-data-api-equity-events",file:"ipo-calendar",method:"GET",path:"/api/v1/stocks/ipo-calendar"},{skill:"arrays-data-api-equity-events",file:"ipo-confirmed-calendar",method:"GET",path:"/api/v1/stocks/ipo-confirmed-calendar"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-kline",method:"GET",path:"/api/v1/stocks/kline"},{skill:"arrays-data-api-stock-metrics",file:"market-metrics",method:"GET",path:"/api/v1/stocks/market-metrics"},{skill:"arrays-data-api-equity-events",file:"mergers-acquisitions",method:"GET",path:"/api/v1/stocks/mergers-acquisitions"},{skill:"arrays-data-api-equity-fundamentals",file:"outstanding-shares",method:"GET",path:"/api/v1/stocks/outstanding-shares"},{skill:"arrays-data-api-stock-metrics",file:"ratings",method:"GET",path:"/api/v1/stocks/ratings"},{skill:"arrays-data-api-stock-screener",file:"basic-info-screener",method:"GET",path:"/api/v1/stocks/screener/basic-info/{sub}"},{skill:"arrays-data-api-stock-screener",file:"event-screener",method:"GET",path:"/api/v1/stocks/screener/events"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics",method:"GET",path:"/api/v1/stocks/screener/financial-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/financial-metrics/timerange"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics",method:"GET",path:"/api/v1/stocks/screener/technical-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/technical-metrics/timerange"},{skill:"arrays-data-api-equity-events",file:"sec-earnings-release",method:"GET",path:"/api/v1/stocks/sec-earnings-release"},{skill:"arrays-data-api-equity-fundamentals",file:"shares-float",method:"GET",path:"/api/v1/stocks/shares-float"},{skill:"arrays-data-api-equity-events",file:"splits",method:"GET",path:"/api/v1/stocks/splits"},{skill:"arrays-data-api-crypto-exchange-flow",file:"exchange-flows",method:"GET",path:"/api/v1/crypto/exchange-flows"},{skill:"arrays-data-api-company-crypto-holdings",file:"crypto-holdings",method:"GET",path:"/api/v1/crypto/holdings"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-inflow-cdd",method:"GET",path:"/api/v1/crypto/metrics/inflow-cdd"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-leverage-ratio",method:"GET",path:"/api/v1/crypto/metrics/leverage-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-miner-to-exchange",method:"GET",path:"/api/v1/crypto/metrics/miner-to-exchange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-mvrv",method:"GET",path:"/api/v1/crypto/metrics/mvrv"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-nupl",method:"GET",path:"/api/v1/crypto/metrics/nupl"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-puell-multiple",method:"GET",path:"/api/v1/crypto/metrics/puell-multiple"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-realized-price",method:"GET",path:"/api/v1/crypto/metrics/realized-price"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-sopr",method:"GET",path:"/api/v1/crypto/metrics/sopr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-ssr",method:"GET",path:"/api/v1/crypto/metrics/ssr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-whale-ratio",method:"GET",path:"/api/v1/crypto/metrics/whale-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-supply",method:"GET",path:"/api/v1/crypto/supply"},{skill:"arrays-data-api-crypto-futures-data",file:"taker-buy-sell-volume",method:"GET",path:"/api/v1/crypto/taker-buy-sell-volume"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"unlock-events",method:"GET",path:"/api/v1/crypto/unlock-events"},{skill:"arrays-data-api-etf-fundamentals",file:"flow",method:"GET",path:"/api/v1/etf/flow"},{skill:"arrays-data-api-options",file:"contracts",method:"GET",path:"/api/v1/options/contracts"},{skill:"arrays-data-api-options",file:"kline",method:"GET",path:"/api/v1/options/kline"},{skill:"arrays-data-api-options",file:"greeks",method:"GET",path:"/api/v1/options/greeks"},{skill:"arrays-data-api-options",file:"chain",method:"GET",path:"/api/v1/options/chain"},{skill:"arrays-data-api-equity-fundamentals",file:"company-executives",method:"GET",path:"/api/v1/stocks/company/executives"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-consensus",method:"GET",path:"/api/v1/stocks/company/price-target-consensus"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-news",method:"GET",path:"/api/v1/stocks/company/price-target-news"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-summary",method:"GET",path:"/api/v1/stocks/company/price-target-summary"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"congress-recent-trades",method:"GET",path:"/api/v1/stocks/congress/recent-trades"},{skill:"arrays-data-api-stock-metrics",file:"darkpool",method:"GET",path:"/api/v1/stocks/darkpool"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"estimates-guidance",method:"GET",path:"/api/v1/stocks/estimates-guidance"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"insider-transactions",method:"GET",path:"/api/v1/stocks/insider/transactions"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"institution-holder",method:"GET",path:"/api/v1/stocks/institution-holder"},{skill:"arrays-data-api-polymarket",file:"activity",method:"GET",path:"polymarket:/activity"},{skill:"arrays-data-api-polymarket",file:"book",method:"GET",path:"polymarket:/book"},{skill:"arrays-data-api-polymarket",file:"closed-positions",method:"GET",path:"polymarket:/closed-positions"},{skill:"arrays-data-api-polymarket",file:"events",method:"GET",path:"polymarket:/events"},{skill:"arrays-data-api-polymarket",file:"holders",method:"GET",path:"polymarket:/holders"},{skill:"arrays-data-api-polymarket",file:"markets",method:"GET",path:"polymarket:/markets"},{skill:"arrays-data-api-polymarket",file:"midpoint",method:"GET",path:"polymarket:/midpoint"},{skill:"arrays-data-api-polymarket",file:"oi",method:"GET",path:"polymarket:/oi"},{skill:"arrays-data-api-polymarket",file:"positions",method:"GET",path:"polymarket:/positions"},{skill:"arrays-data-api-polymarket",file:"price",method:"GET",path:"polymarket:/price"},{skill:"arrays-data-api-polymarket",file:"prices-history",method:"GET",path:"polymarket:/prices-history"},{skill:"arrays-data-api-polymarket",file:"public-search",method:"GET",path:"polymarket:/public-search"},{skill:"arrays-data-api-polymarket",file:"series",method:"GET",path:"polymarket:/series"},{skill:"arrays-data-api-polymarket",file:"sports",method:"GET",path:"polymarket:/sports"},{skill:"arrays-data-api-polymarket",file:"spread",method:"GET",path:"polymarket:/spread"},{skill:"arrays-data-api-polymarket",file:"tags",method:"GET",path:"polymarket:/tags"},{skill:"arrays-data-api-polymarket",file:"trades",method:"GET",path:"polymarket:/trades"},{skill:"arrays-data-api-polymarket",file:"value",method:"GET",path:"polymarket:/value"},{skill:"arrays-data-api-equity-events",file:"earnings-transcript",method:"GET",path:"/api/v1/stocks/earnings-transcript"},{skill:"arrays-data-api-news",file:"market-news",method:"GET",path:"/api/v1/stocks/market-news"},{skill:"arrays-data-api-social-feeds",file:"x-by-handle",method:"GET",path:"/api/v1/social-feeds/x/by-handle"},{skill:"arrays-data-api-social-feeds",file:"x-by-url",method:"GET",path:"/api/v1/social-feeds/x/by-url"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handle",method:"GET",path:"/api/v1/social-feeds/x/entities/handle/{twitter_handle}"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handles",method:"GET",path:"/api/v1/social-feeds/x/entities/handles"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail-non-us",method:"GET",path:"/api/v1/stocks/non-us/company/detail"},{skill:"arrays-data-api-social-feeds",file:"x-search",method:"GET",path:"/api/v1/social-feeds/x/search"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-non-us-kline",method:"GET",path:"/api/v1/stocks/non-us/kline"},{skill:"arrays-data-api-semiconductor-price",file:"dram-spot-price",method:"GET",path:"/api/v1/other/semiconductor/dram-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"dram-contract-price",method:"GET",path:"/api/v1/other/semiconductor/dram-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-spot-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-contract-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"memory-card-price",method:"GET",path:"/api/v1/other/semiconductor/memory-card-price"},{skill:"arrays-data-api-semiconductor-price",file:"dxi-index",method:"GET",path:"/api/v1/other/semiconductor/dxi-index"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"short-interest",method:"GET",path:"/api/v1/stocks/short-interest"},{skill:"arrays-data-api-social-feeds",file:"x-handles",method:"POST",path:"/api/v1/social-feeds/x/handles"}];function St(t,e){return At.find(n=>n.skill===t&&n.file===e)}i(St,"getSkillEndpointMetadata");function Ve(t){return At.filter(e=>e.skill===t)}i(Ve,"listSkillEndpointMetadata");var be=class{constructor(e){this.client=e}client;static{i(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...Tt(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!s)throw new Error(`empty skills summary response for "${e.name}"`);let o=Ve(e.name);return{...s,...Tt(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!s)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=St(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function Tt(t){let e=Ve(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}i(Tt,"metadataSummaryForSkill");function wt(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}i(wt,"normalizePlaybookSkillSummary");function Ct(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new c("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}i(Ct,"parsePlaybookSkillId");var ke=class{constructor(e){this.client=e}client;static{i(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(wt)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:r}=Ct(e),s=encodeURIComponent(n),o=encodeURIComponent(r),a=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!a)throw new c("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...wt(a),files:a.files??[]}}async file(e,n){let{username:r,name:s}=Ct(e),o=encodeURIComponent(r),l=encodeURIComponent(s),a=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${l}/files/${a}`)).data?.[0];if(!d)throw new c("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var Pe=class{constructor(e){this.client=e}client;static{i(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var Re=class{constructor(e){this.client=e}client;static{i(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var _e=class{constructor(e){this.client=e}client;static{i(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var Ee=class{constructor(e){this.client=e}client;static{i(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var ve=class{constructor(e){this.client=e}client;static{i(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var Ae=class{constructor(e){this.client=e}client;static{i(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var Se=class{constructor(e){this.client=e}client;static{i(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var Te=class{constructor(e){this.client=e}client;static{i(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:_n(e)})}};function _n(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}i(_n,"buildQuery");var we=class{constructor(e){this.client=e}client;static{i(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var Ce=class{constructor(e){this.client=e}client;static{i(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var U=class{constructor(e){this.client=e}client;static{i(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var qe=class{constructor(e){this.client=e}client;static{i(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:qt(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:qt(e)})}async getGroupChatHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-history",{query:{channel:e.channel,remote_chat_id:e.remote_chat_id,from_micros:String(e.from_micros),to_micros:String(e.to_micros)}})}};function qt(t){return`{"session_id":${It(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${It(t.target_id)}}`}i(qt,"mutationBody");function It(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new c("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new c("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}i(It,"idLiteral");var Ie=class{constructor(e){this.client=e}client;static{i(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var xe=class{constructor(e){this.client=e}client;static{i(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:vn(n.result)}}async getAllowance(e){this.client._requireAuth();let n=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return He(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>He(n)).filter(n=>n!==null)}}async createAllowance(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:En(n.allowance)}}async revokeAllowance(e){return this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}}),{ok:!0}}};function He(t){if(!t)return null;let e={id:t.id??"",consumer_uid:t.consumer_uid??t.consumerUid??"",playbook_id:t.playbook_id??t.playbookId??"",amount:t.amount??0,used:t.used??0,remaining:t.remaining??0},n=xt(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),r=xt(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),r!==void 0&&(e.updated_at_ms=r),e}i(He,"normalizeAllowance");function En(t){let e=He(t);if(!e)throw new Error("allowance response missing allowance");return e}i(En,"requireAllowance");function xt(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}if(typeof t!="object")return;let e=t,n=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,r=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(r)?r:0)/1e6)}i(xt,"timestampMs");function vn(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}i(vn,"parseResultPayload");var An=`
|
|
53
|
+
`.trim(),B=class{constructor(e){this.client=e;this.delivery=new de(e)}client;static{i(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=On(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Ee(e.id);if(!Mn(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(n))}`,{body:{version:e.version,cronjob_id:e.cronjob_id,description:e.description,changelog:e.changelog,agent_type:e.agent_type,trigger:e.trigger}})}stop(e){return this.client.feed.stop(e)}resume(e){return this.client.feed.resume(e)}delete(e){return this.client.feed.delete(e)}publish(e){return this.client.release.feed(e)}},de=class{constructor(e){this.client=e}client;static{i(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Ee(e.id),s=(await this.graphql(Gn,{automationId:n})).automation?.alertDelivery;if(!s)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=Ee(e.id),r=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!r&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=r?$n(e.alvaChannelIds??[]):void 0,l=(await this.graphql(Ln,{input:{automationId:n,...r?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:r,includeEmail:s})).updateAutomationAlertDelivery;if(!l)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return l}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!r)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(r.errors&&r.errors.length>0)throw new u("GRAPHQL_ERROR",jn(r.errors),400,{errors:r.errors});if(!r.data)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};function On(t){if(typeof t=="string")return Ee(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}i(On,"requireAutomationID");function Ee(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}i(Ee,"requireAutomationIDString");function Mn(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}i(Mn,"hasAutomationUpdate");function $n(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}i($n,"uniqueAlvaChannelIDs");function jn(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}i(jn,"graphQLErrorMessage");var $t=["public","private","paid"];var Te=class{constructor(e){this.client=e}client;static{i(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new u("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let r=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let a=await this.listByOwner({owner:r,cursor:o,limit:100}),l=a.items.find(c=>c.name===s);if(l)return l;if(!a.has_next||!a.next_cursor)return null;o=a.next_cursor}}throw new u("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let n={};e.cursor&&(n.cursor=e.cursor),e.current&&(n.current=e.current),e.limit!==void 0&&(n.limit=e.limit),e.dir&&(n.dir=e.dir),e.sort&&(n.sort=e.sort),e.keyword&&(n.keyword=e.keyword),e.tags&&e.tags.length>0&&(n.tags=e.tags.join(","));let r=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=Bn(this.client.baseUrl);return{playbooks:(r.playbooks??[]).map(o=>Qn(o,s)),has_next:r.has_next??!1}}async setVisibility(e){if(!$t.includes(e.visibility))throw new u("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${$t.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Bn(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let r=n[1].toLowerCase();return r==="prd"?"https://alva.ai":`https://${r}.alva.ai`}}catch{}return"https://alva.ai"}i(Bn,"webOriginFromApiBase");function Qn(t,e){let n=t.creator?.name??"",r=t.name??"",s=n&&r?`${n}/${r}`:r,o=n&&r?`/u/${n}/playbooks/${r}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:r,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}i(Qn,"toAgentPlaybook");var Ae=class{constructor(e){this.client=e}client;static{i(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var Ce=class{constructor(e){this.client=e}client;static{i(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var jt=[{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 Bt(t,e){return jt.find(n=>n.skill===t&&n.file===e)}i(Bt,"getSkillEndpointMetadata");function lt(t){return jt.filter(e=>e.skill===t)}i(lt,"listSkillEndpointMetadata");var Ie=class{constructor(e){this.client=e}client;static{i(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...Qt(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!s)throw new Error(`empty skills summary response for "${e.name}"`);let o=lt(e.name);return{...s,...Qt(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!s)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=Bt(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function Qt(t){let e=lt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}i(Qt,"metadataSummaryForSkill");function Wt(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}i(Wt,"normalizePlaybookSkillSummary");function Vt(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new u("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}i(Vt,"parsePlaybookSkillId");var qe=class{constructor(e){this.client=e}client;static{i(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(Wt)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:r}=Vt(e),s=encodeURIComponent(n),o=encodeURIComponent(r),l=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!l)throw new u("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...Wt(l),files:l.files??[]}}async file(e,n){let{username:r,name:s}=Vt(e),o=encodeURIComponent(r),a=encodeURIComponent(s),l=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${a}/files/${l}`)).data?.[0];if(!d)throw new u("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var xe=class{constructor(e){this.client=e}client;static{i(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var Ne=class{constructor(e){this.client=e}client;static{i(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var De=class{constructor(e){this.client=e}client;static{i(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var Ue=class{constructor(e){this.client=e}client;static{i(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var Fe=class{constructor(e){this.client=e}client;static{i(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var Ge=class{constructor(e){this.client=e}client;static{i(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var Le=class{constructor(e){this.client=e}client;static{i(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var Oe=class{constructor(e){this.client=e}client;static{i(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:Wn(e)})}};function Wn(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}i(Wn,"buildQuery");var Me=class{constructor(e){this.client=e}client;static{i(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var $e=class{constructor(e){this.client=e}client;static{i(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var Q=class{constructor(e){this.client=e}client;static{i(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var je=class{constructor(e){this.client=e}client;static{i(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:Yt(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:Yt(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 Yt(t){return`{"session_id":${Ht(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${Ht(t.target_id)}}`}i(Yt,"mutationBody");function Ht(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new u("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 u("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}i(Ht,"idLiteral");var Be=class{constructor(e){this.client=e}client;static{i(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var Qe=class{constructor(e){this.client=e}client;static{i(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:Yn(n.result)}}async getAllowance(e){this.client._requireAuth();let n=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return ut(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>ut(n)).filter(n=>n!==null)}}async createAllowance(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:Vn(n.allowance)}}async revokeAllowance(e){return this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}}),{ok:!0}}};function ut(t){if(!t)return null;let e={id:t.id??"",consumer_uid:t.consumer_uid??t.consumerUid??"",playbook_id:t.playbook_id??t.playbookId??"",amount:t.amount??0,used:t.used??0,remaining:t.remaining??0},n=zt(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),r=zt(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),r!==void 0&&(e.updated_at_ms=r),e}i(ut,"normalizeAllowance");function Vn(t){let e=ut(t);if(!e)throw new Error("allowance response missing allowance");return e}i(Vn,"requireAllowance");function zt(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}if(typeof t!="object")return;let e=t,n=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,r=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(r)?r:0)/1e6)}i(zt,"timestampMs");function Yn(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}i(Yn,"parseResultPayload");var Hn=`
|
|
54
54
|
query ToolkitCreditWallet {
|
|
55
55
|
viewer {
|
|
56
56
|
creditWallet {
|
|
@@ -60,7 +60,7 @@ query ToolkitCreditWallet {
|
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
|
-
`.trim(),
|
|
63
|
+
`.trim(),zn=`
|
|
64
64
|
query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
|
|
65
65
|
viewer {
|
|
66
66
|
creditWallet {
|
|
@@ -92,7 +92,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
|
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
|
-
`.trim();function
|
|
95
|
+
`.trim();function Jn(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}i(Jn,"graphQLErrorMessage");var We=class{constructor(e){this.client=e}client;static{i(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(Hn)).viewer?.creditWallet;if(!n)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return n}async items(e){this.client._requireAuth();let r=(await this.graphql(zn,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!r)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return r}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors&&r.errors.length>0)throw new u("GRAPHQL_ERROR",Jn(r.errors),400,{errors:r.errors});if(!r.data)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var Kn=["Q1","Q2","Q3","Q4"],Xn=["latest-completed","next-confirmed"],Zn=`
|
|
96
96
|
query ToolkitCompanyNarrative($ticker: String!) {
|
|
97
97
|
market {
|
|
98
98
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -118,7 +118,7 @@ query ToolkitCompanyNarrative($ticker: String!) {
|
|
|
118
118
|
}
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
|
-
`.trim(),
|
|
121
|
+
`.trim(),er=`
|
|
122
122
|
query ToolkitCompanyEarningsCatalog($ticker: String!) {
|
|
123
123
|
market {
|
|
124
124
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -149,7 +149,7 @@ query ToolkitCompanyEarningsCatalog($ticker: String!) {
|
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
151
|
}
|
|
152
|
-
`.trim(),
|
|
152
|
+
`.trim(),tr=`
|
|
153
153
|
query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
154
154
|
market {
|
|
155
155
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -219,9 +219,8 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
219
219
|
}
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
|
-
`.trim();function
|
|
222
|
+
`.trim();function nr(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}i(nr,"graphQLErrorMessage");function ct(t){let e=t.trim().toUpperCase();if(!e)throw new u("INVALID_ARGUMENT","ticker is required",400);return e}i(ct,"normalizedTicker");var W=class{constructor(e){this.client=e}client;static{i(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=ct(e),s=(await this.graphql(Zn,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);return{ticker:s.ticker,current:s.companyInsight,history:s.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let n=ct(e),s=(await this.graphql(er,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);if(!s.earningsPeriods)throw new u("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${s.ticker}`,404,{ticker:s.ticker});return s.earningsPeriods}async earnings(e){this.client._requireAuth();let n=ct(e.ticker),r=e.event,s=e.fiscalYear,o=e.fiscalQuarter;if(r!==void 0&&(s!==void 0||o!==void 0))throw new u("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(s===void 0!=(o===void 0))throw new u("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(r!==void 0&&!Xn.includes(r))throw new u("INVALID_ARGUMENT",`Unknown earnings event selector: ${r}`,400);if(s!==void 0&&(!Number.isInteger(s)||s<1900||s>9999))throw new u("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!Kn.includes(o))throw new u("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let l,c;if(s!==void 0&&o!==void 0)l=s,c=o;else{let P=r??"latest-completed",T=await this.earningsPeriods(n),G=this.selectPeriod(T,P,n);l=G.fiscalYear,c=G.fiscalQuarter}let p=(await this.graphql(tr,{ticker:n,input:{fiscalYear:l,fiscalQuarter:c}})).market?.entity;if(!p)throw this.notFound(n);if(!p.earnings)throw new u("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${p.ticker} FY${l} ${c}`,404,{ticker:p.ticker,fiscalYear:l,fiscalQuarter:c});return{ticker:p.ticker,...p.earnings}}selectPeriod(e,n,r){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let s=e.periods.filter(o=>o.status==="UPCOMING").sort((o,a)=>o.earningsDate.localeCompare(a.earningsDate));if(s.length>0)return s[0]}throw new u("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${n} earnings event is available for ${r}`,404,{ticker:r,event:n})}notFound(e){return new u("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(r.errors&&r.errors.length>0)throw new u("GRAPHQL_ERROR",nr(r.errors),400,{errors:r.errors});if(!r.data)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var Ve=`
|
|
223
223
|
id
|
|
224
|
-
channel { id }
|
|
225
224
|
name
|
|
226
225
|
rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
|
|
227
226
|
bounds { startsAtMs untilMs maxOccurrences }
|
|
@@ -233,22 +232,59 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
233
232
|
nextFireAtMs
|
|
234
233
|
createdAtMs
|
|
235
234
|
updatedAtMs
|
|
236
|
-
`,
|
|
235
|
+
`,rr=`
|
|
237
236
|
query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
|
|
238
237
|
viewer { channel(id: $channelId) {
|
|
239
238
|
schedules(input: { first: 64, after: $after }) {
|
|
240
|
-
edges { node { ${
|
|
239
|
+
edges { node { channel { id } ${Ve} } }
|
|
241
240
|
pageInfo { hasNextPage endCursor }
|
|
242
241
|
}
|
|
243
242
|
} }
|
|
244
|
-
}`.trim(),
|
|
243
|
+
}`.trim(),ir=`
|
|
245
244
|
mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
|
|
246
245
|
updateChannelSchedule(input: $input) {
|
|
247
|
-
schedule { ${
|
|
246
|
+
schedule { channel { id } ${Ve} }
|
|
248
247
|
deleted
|
|
249
248
|
}
|
|
250
|
-
}`.trim(),
|
|
249
|
+
}`.trim(),sr=`
|
|
250
|
+
query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
|
|
251
|
+
viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
|
|
252
|
+
edges { node { ${Ve} } }
|
|
253
|
+
pageInfo { hasNextPage endCursor }
|
|
254
|
+
} }
|
|
255
|
+
}`.trim(),or=`
|
|
256
|
+
mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
|
|
257
|
+
updateSessionSchedule(input: $input) {
|
|
258
|
+
schedule { ${Ve} }
|
|
259
|
+
deleted
|
|
260
|
+
}
|
|
261
|
+
}`.trim(),ar=`
|
|
251
262
|
query ToolkitAgentChannel {
|
|
252
263
|
viewer { channels { id kind } }
|
|
253
|
-
}`.trim(),Gn=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Ln=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Dn=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,On={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},L=class{constructor(e){this.client=e}client;static{i(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Xe(e.channelId),r=[],s=null,o=new Set;for(;;){let a=(await this.graphql(Fn,{channelId:n,after:s})).viewer?.channel?.schedules;if(!a?.edges)throw Ft();for(let d of a.edges){if(!d?.node)throw y();r.push(Ke(d.node))}if(a.pageInfo?.hasNextPage!==!0)return r;let u=a.pageInfo.endCursor;if(!u||o.has(u))throw y();o.add(u),s=u}}async put(e){this.client._requireAuth();let n={channelId:Xe(e.channelId),name:Gt(e.name),definition:{...Mn(e.rule,e.bounds),message:{text:Bn(e.text)}}},s=(await this.graphql(Je,{input:n})).updateChannelSchedule?.schedule;if(!s)throw y();return Ke(s)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.graphql(Je,{input:{...Nt(e),lifecycle:"REMOVED"}})).updateChannelSchedule?.deleted!==!0)throw y()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Un)).viewer?.channels?.find(r=>r.kind==="AGENT")?.id;if(!n)throw Ft();return n}async manage(e,n){this.client._requireAuth();let s=(await this.graphql(Je,{input:{...Nt(n),lifecycle:e}})).updateChannelSchedule?.schedule;if(!s)throw y();return Ke(s)}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors?.length){let s=r.errors.map(d=>d.extensions?.code),l=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=l?On[l]:void 0,u=l!==void 0&&a!==void 0?l:"GRAPHQL_ERROR";throw new c(u,r.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",a??502,{errors:r.errors})}if(!r.data)throw y();return r.data}};function Mn(t,e){let n=jn(e);switch(t.kind){case"after":if(n)throw h("after does not accept recurring bounds");let r=Date.now()+Lt(t.duration,1),s=Math.ceil(r/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw h("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw h("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:Ze(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Qn(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw h("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}i(Mn,"ruleInput");function jn(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=Ze(t.startsAt)),t.until!==void 0&&(e.untilMs=Ze(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw h("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}i(jn,"boundsInput");function Ke(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw y();let r=t.bounds??{},s=t.message??{},o={name:t.name,rule:$n(t.rule),bounds:{...r.startsAtMs!=null?{startsAt:T(r.startsAtMs,!0)}:{},...r.untilMs!=null?{until:T(r.untilMs,!0)}:{},...r.maxOccurrences!=null?{maxOccurrences:et(r.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:et(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:T(t.nextFireAtMs,!0)}:{},createdAt:T(t.createdAtMs),updatedAt:T(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw y();let a={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!a)throw y();o.failure={code:a,...t.failureAtMs!=null?{at:T(t.failureAtMs)}:{}}}return o}i(Ke,"fromWireSchedule");function $n(t){switch(t.kind){case"AT":if(t.atMs==null)throw y();return{kind:"at",timestamp:T(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw y();return{kind:"every",interval:`PT${et(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw y();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw y()}i($n,"fromWireRule");function Nt(t){return{channelId:Xe(t.channelId),name:Gt(t.name)}}i(Nt,"managementInput");function Xe(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw h("numeric channelId must be a positive safe integer; use a decimal string for larger IDs");let e=String(t);if(!/^[1-9]\d*$/.test(e))throw h("channelId must be a positive integer");return e}i(Xe,"channelID");function Gt(t){if(!Gn.test(t))throw h("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}i(Gt,"requireName");function Bn(t){let e=Wn(t);if(e===void 0||!t.trim()||e>16*1024)throw h("text must be 1..16384 UTF-8 bytes");return t}i(Bn,"requireText");function Qn(t){let e=Lt(t,60);if(e%1e3!==0)throw h("duration must resolve to whole seconds");return e/1e3}i(Qn,"durationSeconds");function Lt(t,e){let n=Dn.exec(t);if(!n||n.slice(1,5).every(d=>d===void 0)||t.includes("T")&&n.slice(2,5).every(d=>d===void 0))throw h("duration must be a positive ISO 8601 day/time duration");let[r,s,o,l]=n.slice(1,5).map(d=>BigInt(d??"0")),a=((r*24n+s)*60n+o)*60n+l;if(a<BigInt(e))throw h(`duration must be at least ${e} whole seconds`);let u=Number(a*1000n);if(!Number.isSafeInteger(u))throw h("duration is out of range");return u}i(Lt,"durationMilliseconds");function Ze(t){let e=Ln.exec(t);if(!e)throw h("timestamp must be RFC3339 with a timezone");let[n,r,s,o,l,a]=e.slice(1,7).map(Number),u=Number(e[8]??0),d=Number(e[9]??0),p=new Date(Date.UTC(n,r,0)).getUTCDate(),_=Date.parse(t);if(!Number.isFinite(_)||n<1||n>9999||r<1||r>12||s<1||s>p||o>23||l>59||a>59||u>23||d>59)throw h("timestamp must be RFC3339 with a timezone");return _}i(Ze,"timestampMilliseconds");function T(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw y();let n=new Date(t);if(Number.isNaN(n.getTime()))throw y();return n.toISOString()}i(T,"timestampString");function et(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw h(`${e} exceeds JavaScript safe integer range`);return n}i(et,"safeInteger");function h(t){return new c("INVALID_ARGUMENT",t,400)}i(h,"invalid");function Wn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}i(Wn,"utf8Size");function Ft(){return new c("NOT_FOUND","channel schedule target not found",404)}i(Ft,"scheduleNotFound");function y(){return new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}i(y,"scheduleEmptyResponse");function A(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(A,"isRecord");function m(t){return typeof t=="string"&&t.trim()!==""?t:void 0}i(m,"stringValue");function Fe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(Fe,"numberValue");function Ge(t){return t===void 0?void 0:t.trim().toUpperCase()}i(Ge,"upper");function Ot(t){return t.split("_")}i(Ot,"pairParts");function Yn(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Ot(e)[1]?.toLowerCase()??""}i(Yn,"inferInstrumentType");function Vn(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}i(Vn,"inferUnderlyingType");function Dt(t,e){let n=m(t.trading_pair)??m(t.tradingPair)??m(t.symbol);if(n===void 0)return;let r=m(t.type),s=Ot(n),o=m(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),l=m(t.market)??m(t.exchange)??s[0]??"",a=m(t.quote)??s[s.length-1]??"",u=m(t.instrument_type)??m(t.instrumentType)??Yn(r,n),d=m(t.underlying_type)??m(t.underlyingType)??Vn(r);return{symbol:o,tradingPair:n,market:l,instrumentType:u,...d===void 0?{}:{underlyingType:d},quote:a,...r===void 0?{}:{type:r},...m(t.description)===void 0?{}:{description:m(t.description)},...Fe(t.fee_rate)===void 0?Fe(t.feeRate)===void 0?{}:{feeRate:Fe(t.feeRate)}:{feeRate:Fe(t.fee_rate)},...m(t.symbol_icon_url)===void 0?m(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:m(t.symbolIconUrl)}:{symbolIconUrl:m(t.symbol_icon_url)}}}i(Dt,"normalizeCandidate");function Hn(t){if(!A(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>A(s)?[Dt(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let r=[];for(let s of n){if(!A(s))continue;let o=m(s.symbol),l=s.trading_pairs;if(Array.isArray(l)){for(let a of l)if(!(!A(a)||!Array.isArray(a.pairs)))for(let u of a.pairs){if(!A(u))continue;let d=Dt({...u,instrument_type:u.instrument_type??a.instrument_type},o);d!==void 0&&r.push(d)}}}return r}i(Hn,"flattenResponse");function zn(t,e){let n=e.trim();return t.tradingPair===n?!0:Ge(t.symbol)===Ge(n)}i(zn,"matchesQuery");function Ue(t,e){return e===void 0||Ge(t)===Ge(e)}i(Ue,"matchesFilter");function Jn(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}i(Jn,"dedupe");function Kn(t){let e=A(t)?t:{};return{market:typeof e.market=="string"?e.market:void 0,instrumentType:typeof e.instrumentType=="string"?e.instrumentType:void 0,underlyingType:typeof e.underlyingType=="string"?e.underlyingType:void 0,quote:typeof e.quote=="string"?e.quote:void 0}}i(Kn,"resolveFilters");function Xn(t,e){let n=t.split("_"),r=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,l=n.at(-1);return!r||!s||!o||!l?{symbol:t,...e}:{symbol:o,market:e.market??r,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??l}}i(Xn,"pairSearchParams");var D=class{constructor(e){this.client=e}client;static{i(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=A(e)?e.symbol:void 0,r=typeof n=="string"?n.trim():"";if(!r)throw new c("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:r,strict:!0}}),o=Jn(Hn(s)).filter(a=>zn(a,r)).filter(a=>Ue(a.market,e.market)).filter(a=>Ue(a.instrumentType,e.instrumentType)).filter(a=>Ue(a.underlyingType,e.underlyingType)).filter(a=>Ue(a.quote,e.quote)),l=e.limit;return l!==void 0&&o.length>l?{query:r,candidates:o.slice(0,l),truncated:!0}:{query:r,candidates:o}}async resolve(e){let n=A(e)?e:{},r=typeof n.pair=="string"?n.pair.trim():void 0,s=Kn(e),o=r===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Xn(r,s),l=await this.search(o),a=r===void 0?l.candidates:l.candidates.filter(u=>u.tradingPair===r);if(a.length!==1)throw new c(a.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",a.length===0?`no canonical trading pair matched "${r??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,a.length===0?404:409,{query:r??o.symbol,candidateCount:a.length,candidates:a.slice(0,50),...a.length>50?{truncated:!0}:{}});return a[0]}};var Zn="https://api-llm.prd.alva.ai",er="https://data-tools.prd.space.id";function tt(t){return typeof t=="object"&&t!==null}i(tt,"isRecord");function Le(t,e){if(!tt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}i(Le,"stringField");function tr(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let r=Le(t,"code");r&&(e.code=r)}else if(tt(t)){let r=Le(t,"code"),s=Le(t,"name"),o=Le(t,"message");r&&(e.code=r),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(r=>!!r);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}i(tr,"describeCause");function nr(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",n={};t instanceof Error?(n.name=t.name,n.message=t.message):n.message=String(t);let{message:r,details:s}=tr(tt(t)?t.cause:void 0);return s&&(n.cause=s),{message:r?`${e}; cause: ${r}`:e,details:n}}i(nr,"describeFetchFailure");var De=class{static{i(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;_fs;_run;_deploy;_serviceAccount;_release;_feed;_forYou;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_tradingPairs;constructor(e){this.baseUrl=e.baseUrl??Zn,this.arraysBaseUrl=e.arraysBaseUrl??er,this.viewer_token=e.viewer_token,this.pbsvToken=e.pbsvToken,this.apiKey=e.apiKey,this.gaClientId=e.gaClientId,this.gaSessionId=e.gaSessionId,this.utmParams=e.utmParams,this.signal=e.signal,this.originSessionId=e.originSessionId,this.originSessionKind=e.originSessionKind}get fs(){return this._fs??=new oe(this)}get run(){return this._run??=new ae(this)}get deploy(){return this._deploy??=new le(this)}get serviceAccount(){return this._serviceAccount??=new ce(this)}get release(){return this._release??=new ue(this)}get feed(){return this._feed??=new pe(this)}get automation(){return this._automation??=new F(this)}get playbooks(){return this._playbooks??=new ye(this)}get secrets(){return this._secrets??=new he(this)}get sdk(){return this._sdk??=new ge(this)}get dataSkills(){return this._dataSkills??=new be(this)}get playbookSkills(){return this._playbookSkills??=new ke(this)}get comments(){return this._comments??=new Pe(this)}get remix(){return this._remix??=new Re(this)}get screenshot(){return this._screenshot??=new _e(this)}get user(){return this._user??=new Ee(this)}get trading(){return this._trading??=new ve(this)}get portfolio(){return this._portfolio??=new Ae(this)}get arraysJwt(){return this._arraysJwt??=new Se(this)}get notifications(){return this._notifications??=new Te(this)}get notificationPreferences(){return this._notificationPreferences??=new we(this)}get subscriptions(){return this._subscriptions??=new Ce(this)}get alerts(){return this._alerts??=new U(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new qe(this)}get feedback(){return this._feedback??=new Ie(this)}get functions(){return this._functions??=new xe(this)}get credits(){return this._credits??=new Ne(this)}get markets(){return this._markets??=new G(this)}get tradingPairs(){return this._tradingPairs??=new D(this)}get schedules(){return this._schedules??=new L(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new c("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get forYou(){return this._forYou??=new N(this)}async _request(e,n,r){let o=`${r?.baseUrl??this.baseUrl}${n}`;if(r?.query){let P=new URLSearchParams;for(let[E,Oe]of Object.entries(r.query))Oe!=null&&P.set(E,String(Oe));let C=P.toString();C&&(o+=`?${C}`)}let l={};r?.noAuth||(this.pbsvToken?(l.Authorization=`Bearer ${this.pbsvToken}`,l["X-Pbsv"]="1"):this.viewer_token?l["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(l["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(l["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(l["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(l["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!r?.noAuth&&(l["X-Alva-Origin-Session-Id"]=this.originSessionId);let a;r?.rawBody!==void 0?(l["Content-Type"]="application/octet-stream",a=r.rawBody):r?.jsonBody!==void 0?(l["Content-Type"]="application/json",a=r.jsonBody):r?.body!==void 0&&(l["Content-Type"]="application/json",a=JSON.stringify(r.body));let u,d=r?.timeoutMs,p=r?.signal??this.signal;if(p?.aborted)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let _=d!==void 0?new AbortController:void 0,O=!1,w,te;_&&d!==void 0&&(p&&(te=i(()=>_.abort(p.reason),"abortListener"),p.addEventListener("abort",te,{once:!0})),w=setTimeout(()=>{O=!0,_.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let nt={method:e,headers:l,body:a,signal:_?.signal??p};d!==void 0&&(nt.timeout=d);try{u=await fetch(o,nt)}catch(P){if(p?.aborted&&!O)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(O)throw new c("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let C=nr(P);throw new c("NETWORK_ERROR",C.message,0,{method:e,path:n,...C.details})}finally{te&&p&&p.removeEventListener("abort",te),w!==void 0&&clearTimeout(w)}if(!u.ok){let P="";try{P=await Promise.resolve(u.text())}catch{P=""}if((u.headers.get("content-type")??"").includes("application/json")&&P)try{let E=JSON.parse(P);if(E.error)throw new c(E.error.code??"UNKNOWN",E.error.message??`HTTP ${u.status}`,u.status)}catch(E){if(E instanceof c)throw E}throw new c("UNKNOWN",`HTTP ${u.status}: ${P.slice(0,200)}`,u.status)}if(u.status===204)return;let rt=(u.headers.get("content-type")??"").toLowerCase();return rt.includes("application/json")||rt.includes("+json")?u.json():u.arrayBuffer()}};var rr="0.28.0-beta.0";We();return Wt(ir);})();
|
|
264
|
+
}`.trim(),lr=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,ur=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,cr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,dr=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,pr={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},V=class{constructor(e){this.client=e}client;static{i(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=pt(e),r="inboxPath"in n,s=[],o=null,a=new Set;for(;;){let l=await this.graphql(r?sr:rr,{...n,after:o}),c=r?l.viewer?.sessionSchedules:l.viewer?.channel?.schedules;if(!c?.edges)throw Kt();for(let p of c.edges){if(!p?.node)throw g();s.push(dt(p.node))}if(c.pageInfo?.hasNextPage!==!0)return s;let d=c.pageInfo.endCursor;if(!d||a.has(d))throw g();a.add(d),o=d}}async put(e){this.client._requireAuth();let n={...pt(e),name:Xt(e.name),definition:{...mr(e.rule,e.bounds),message:{text:gr(e.text)}}},r=(await this.update(n))?.schedule;if(!r)throw g();return dt(r)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.update({...Jt(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw g()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(ar)).viewer?.channels?.find(r=>r.kind==="AGENT")?.id;if(!n)throw Kt();return n}async manage(e,n){this.client._requireAuth();let r=(await this.update({...Jt(n),lifecycle:e}))?.schedule;if(!r)throw g();return dt(r)}async update(e){let n="inboxPath"in e,r=await this.graphql(n?or:ir,{input:e});return n?r.updateSessionSchedule:r.updateChannelSchedule}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors?.length){let s=r.errors.map(d=>d.extensions?.code),a=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,l=a?pr[a]:void 0,c=a!==void 0&&l!==void 0?a:"GRAPHQL_ERROR";throw new u(c,r.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",l??502,{errors:r.errors})}if(!r.data)throw g();return r.data}};function mr(t,e){let n=hr(e);switch(t.kind){case"after":if(n)throw m("after does not accept recurring bounds");let r=Date.now()+Zt(t.duration,1),s=Math.ceil(r/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw m("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw m("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:mt(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:br(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw m("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}i(mr,"ruleInput");function hr(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=mt(t.startsAt)),t.until!==void 0&&(e.untilMs=mt(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw m("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}i(hr,"boundsInput");function dt(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw g();let r=t.bounds??{},s=t.message??{},o={name:t.name,rule:fr(t.rule),bounds:{...r.startsAtMs!=null?{startsAt:D(r.startsAtMs,!0)}:{},...r.untilMs!=null?{until:D(r.untilMs,!0)}:{},...r.maxOccurrences!=null?{maxOccurrences:ht(r.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:ht(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:D(t.nextFireAtMs,!0)}:{},createdAt:D(t.createdAtMs),updatedAt:D(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw g();let l={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!l)throw g();o.failure={code:l,...t.failureAtMs!=null?{at:D(t.failureAtMs)}:{}}}return o}i(dt,"fromWireSchedule");function fr(t){switch(t.kind){case"AT":if(t.atMs==null)throw g();return{kind:"at",timestamp:D(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw g();return{kind:"every",interval:`PT${ht(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw g();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw g()}i(fr,"fromWireRule");function Jt(t){return{...pt(t),name:Xt(t.name)}}i(Jt,"managementInput");function pt(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw m("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:yr(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?en(e):void 0;if(typeof e!="string"||n===void 0||n>2048||!e.startsWith("/")||e.includes("\0")||e.slice(1).split("/").some(s=>s===""||s==="."||s===".."))throw m("inboxPath must be a canonical absolute ALFS Inbox path");let r=e.endsWith(".inbox.jsonl")?e.slice(0,-12)+".jsonl":e.endsWith(".inbox")&&!e.endsWith(".jsonl.inbox")?e.slice(0,-6):void 0;if(r===void 0||/\.inbox(?:\.jsonl)?$/.test(r)||/\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(r)||r.endsWith("/.jsonl"))throw m("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}i(pt,"targetInput");function yr(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw m("numeric channelId must be a positive safe integer; use a decimal string for larger IDs");let e=String(t);if(!/^[1-9]\d*$/.test(e))throw m("channelId must be a positive integer");return e}i(yr,"channelID");function Xt(t){if(!lr.test(t))throw m("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}i(Xt,"requireName");function gr(t){let e=en(t);if(e===void 0||!t.trim()||e>16*1024)throw m("text must be 1..16384 UTF-8 bytes");return t}i(gr,"requireText");function br(t){let e=Zt(t,60);if(e%1e3!==0)throw m("duration must resolve to whole seconds");return e/1e3}i(br,"durationSeconds");function Zt(t,e){let n=dr.exec(t);if(!n||n.slice(1,5).every(d=>d===void 0)||t.includes("T")&&n.slice(2,5).every(d=>d===void 0))throw m("duration must be a positive ISO 8601 day/time duration");let[r,s,o,a]=n.slice(1,5).map(d=>BigInt(d??"0")),l=((r*24n+s)*60n+o)*60n+a;if(l<BigInt(e))throw m(`duration must be at least ${e} whole seconds`);let c=Number(l*1000n);if(!Number.isSafeInteger(c))throw m("duration is out of range");return c}i(Zt,"durationMilliseconds");function mt(t,e=!1){let n=(e?cr:ur).exec(t);if(!n)throw m("timestamp must be RFC3339 with a timezone");let[r,s,o,a,l,c]=n.slice(1,7).map(Number),d=Number(n[8]??0),p=Number(n[9]??0),P=new Date(Date.UTC(r,s,0)).getUTCDate(),T=Date.parse(t);if(!Number.isFinite(T)||r<1||r>9999||s<1||s>12||o<1||o>P||a>23||l>59||c>59||d>23||p>59)throw m("timestamp must be RFC3339 with a timezone");return T}i(mt,"timestampMilliseconds");function D(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw g();let n=new Date(t);if(Number.isNaN(n.getTime()))throw g();return n.toISOString()}i(D,"timestampString");function ht(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw m(`${e} exceeds JavaScript safe integer range`);return n}i(ht,"safeInteger");function m(t){return new u("INVALID_ARGUMENT",t,400)}i(m,"invalid");function en(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}i(en,"utf8Size");function Kt(){return new u("NOT_FOUND","channel schedule target not found",404)}i(Kt,"scheduleNotFound");function g(){return new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}i(g,"scheduleEmptyResponse");var _r={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},Pr=`
|
|
265
|
+
mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
|
|
266
|
+
updateStewardDelivery(input: $input) { delivery { deliveryId state } }
|
|
267
|
+
}`.trim(),Rr=`
|
|
268
|
+
mutation ToolkitStewardForward($input: UpdateStewardDeliveryInput!) {
|
|
269
|
+
updateStewardDelivery(input: $input) { delivery { deliveryId state channelMessageId } }
|
|
270
|
+
}`.trim(),kr=`
|
|
271
|
+
mutation ToolkitStewardSend($input: PostStewardMessageInput!) {
|
|
272
|
+
postStewardMessage(input: $input) { message { channelMessageId requestId } }
|
|
273
|
+
}`.trim(),wr=`
|
|
274
|
+
query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInput) {
|
|
275
|
+
viewer {
|
|
276
|
+
stewardDigestPending(inboxPath: $inboxPath, input: $input) {
|
|
277
|
+
edges {
|
|
278
|
+
cursor
|
|
279
|
+
node { deliveryId feedEntryId source { kind id } decisionReason consumedAtMs }
|
|
280
|
+
}
|
|
281
|
+
pageInfo { hasNextPage endCursor }
|
|
282
|
+
windowSinceMs
|
|
283
|
+
windowUntilMs
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}`.trim(),vr=`
|
|
287
|
+
mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
|
|
288
|
+
completeStewardBrief(input: $input) { ok }
|
|
289
|
+
}`.trim(),Sr=new Set(["immediate","digest","suppress"]),Er=/^[1-9][0-9]{0,18}$/;function R(t){return new u("INVALID_ARGUMENT",t,400)}i(R,"invalid");function pe(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw R("steward commands require the steward Session Inbox path");return t.inboxPath}i(pe,"requireInboxPath");function ft(t,e="delivery id"){if(!Er.test(t))throw R(`${e} must be a positive integer`);return t}i(ft,"requireDeliveryId");function tn(t){if(t.length===0)throw R("at least one delivery id is required");let e=new Set;for(let n of t){if(ft(n),e.has(n))throw R(`duplicate delivery id ${n}`);e.add(n)}return[...e]}i(tn,"requireDeliveryIds");function Tr(t){if(!Sr.has(t))throw R("decision must be one of immediate, digest, suppress");return t}i(Tr,"requireDecision");function Ar(){let t=globalThis.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();let e=new Uint8Array(16);if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let r=0;r<e.length;r+=1)e[r]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}i(Ar,"generateRequestId");function nn(t){if(t===void 0)return Ar();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw R("request id must be a UUID");return t}i(nn,"requireRequestId");function I(){return new u("EMPTY_RESPONSE","steward response was empty",502)}i(I,"emptyResponse");var Y=class{constructor(e){this.client=e}client;static{i(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw R("a decision reason is required");let s=(await this.graphql(Pr,{input:{inboxPath:pe(e),deliveryId:ft(e.deliveryId),decision:{decision:Tr(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw I();return{state:s.state}}async forward(e){this.client._requireAuth();let r=(await this.graphql(Rr,{input:{inboxPath:pe(e),deliveryId:ft(e.deliveryId),forward:{requestId:nn(e.requestId)}}})).updateStewardDelivery?.delivery;if(!r||!r.channelMessageId)throw I();return{channelMessageId:r.channelMessageId,state:r.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw R("a message body is required");let r=(await this.graphql(kr,{input:{inboxPath:pe(e),requestId:nn(e.requestId),body:e.body,deliveryIds:tn(e.deliveryIds)}})).postStewardMessage?.message;if(!r)throw I();return r}async pending(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw R("first must be an integer between 1 and 100");let r={first:n};if(e.after!==void 0&&e.after!=="")r.after=e.after;else{for(let[p,P]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(P!==void 0&&(!Number.isSafeInteger(P)||P<=0))throw R(`${p} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw R("untilMs must be after sinceMs");e.sinceMs!==void 0&&(r.sinceMs=e.sinceMs),e.untilMs!==void 0&&(r.untilMs=e.untilMs)}let o=(await this.graphql(wr,{inboxPath:pe(e),input:r})).viewer?.stewardDigestPending;if(!o||!Array.isArray(o.edges))throw I();let a=o.windowSinceMs??0,l=o.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(l)||a<=0||l<=a)throw I();let c=o.edges.map(p=>p.node),d=o.pageInfo?.hasNextPage===!0&&o.pageInfo.endCursor?o.pageInfo.endCursor:null;return{items:c,nextCursor:d,windowSinceMs:a,windowUntilMs:l}}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw R("a digest run id is required");if((await this.graphql(vr,{input:{inboxPath:pe(e),deliveryIds:tn(e.deliveryIds),digestRunId:n}})).completeStewardBrief?.ok!==!0)throw I();return{ok:!0}}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!r||typeof r!="object")throw I();if(r.errors?.length){let s=r.errors.map(l=>l.extensions?.code),o=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=o?_r[o]:void 0;throw new u(o!==void 0&&a!==void 0?o:"GRAPHQL_ERROR",r.errors.map(l=>l.message).filter(l=>typeof l=="string").join("; ")||"GraphQL request failed",a??502,{errors:r.errors})}if(!r.data)throw I();return r.data}};function q(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(q,"isRecord");function h(t){return typeof t=="string"&&t.trim()!==""?t:void 0}i(h,"stringValue");function Ye(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(Ye,"numberValue");function ze(t){return t===void 0?void 0:t.trim().toUpperCase()}i(ze,"upper");function sn(t){return t.split("_")}i(sn,"pairParts");function Cr(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":sn(e)[1]?.toLowerCase()??""}i(Cr,"inferInstrumentType");function Ir(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}i(Ir,"inferUnderlyingType");function rn(t,e){let n=h(t.trading_pair)??h(t.tradingPair)??h(t.symbol);if(n===void 0)return;let r=h(t.type),s=sn(n),o=h(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=h(t.market)??h(t.exchange)??s[0]??"",l=h(t.quote)??s[s.length-1]??"",c=h(t.instrument_type)??h(t.instrumentType)??Cr(r,n),d=h(t.underlying_type)??h(t.underlyingType)??Ir(r);return{symbol:o,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:l,...r===void 0?{}:{type:r},...h(t.description)===void 0?{}:{description:h(t.description)},...Ye(t.fee_rate)===void 0?Ye(t.feeRate)===void 0?{}:{feeRate:Ye(t.feeRate)}:{feeRate:Ye(t.fee_rate)},...h(t.symbol_icon_url)===void 0?h(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:h(t.symbolIconUrl)}:{symbolIconUrl:h(t.symbol_icon_url)}}}i(rn,"normalizeCandidate");function qr(t){if(!q(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>q(s)?[rn(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let r=[];for(let s of n){if(!q(s))continue;let o=h(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let l of a)if(!(!q(l)||!Array.isArray(l.pairs)))for(let c of l.pairs){if(!q(c))continue;let d=rn({...c,instrument_type:c.instrument_type??l.instrument_type},o);d!==void 0&&r.push(d)}}}return r}i(qr,"flattenResponse");function xr(t,e){let n=e.trim();return t.tradingPair===n?!0:ze(t.symbol)===ze(n)}i(xr,"matchesQuery");function He(t,e){return e===void 0||ze(t)===ze(e)}i(He,"matchesFilter");function Nr(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}i(Nr,"dedupe");function Dr(t){let e=q(t)?t:{};return{market:typeof e.market=="string"?e.market:void 0,instrumentType:typeof e.instrumentType=="string"?e.instrumentType:void 0,underlyingType:typeof e.underlyingType=="string"?e.underlyingType:void 0,quote:typeof e.quote=="string"?e.quote:void 0}}i(Dr,"resolveFilters");function Ur(t,e){let n=t.split("_"),r=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!r||!s||!o||!a?{symbol:t,...e}:{symbol:o,market:e.market??r,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}i(Ur,"pairSearchParams");var H=class{constructor(e){this.client=e}client;static{i(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=q(e)?e.symbol:void 0,r=typeof n=="string"?n.trim():"";if(!r)throw new u("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:r,strict:!0}}),o=Nr(qr(s)).filter(l=>xr(l,r)).filter(l=>He(l.market,e.market)).filter(l=>He(l.instrumentType,e.instrumentType)).filter(l=>He(l.underlyingType,e.underlyingType)).filter(l=>He(l.quote,e.quote)),a=e.limit;return a!==void 0&&o.length>a?{query:r,candidates:o.slice(0,a),truncated:!0}:{query:r,candidates:o}}async resolve(e){let n=q(e)?e:{},r=typeof n.pair=="string"?n.pair.trim():void 0,s=Dr(e),o=r===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Ur(r,s),a=await this.search(o),l=r===void 0?a.candidates:a.candidates.filter(c=>c.tradingPair===r);if(l.length!==1)throw new u(l.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",l.length===0?`no canonical trading pair matched "${r??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,l.length===0?404:409,{query:r??o.symbol,candidateCount:l.length,candidates:l.slice(0,50),...l.length>50?{truncated:!0}:{}});return l[0]}};var Fr=9223372036854775807n,Gr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Lr=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,on=new TextEncoder,J=class{constructor(e){this.client=e}client;static{i(this,"ThesesResource")}async create(e){this.client._requireAuth();let n=Or(e);return Je(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){return this.client._requireAuth(),$r(await this.client._request("GET",`/api/v1/theses/${x(e,"id")}`))}async update(e,n){this.client._requireAuth();let r=Mr(n);return Je(await this.client._request("PUT",`/api/v1/theses/${x(e,"id")}`,{body:r}))}async close(e,n){this.client._requireAuth();let r={expected_author_version_id:x(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(r.note=F(n.note,"note")),Je(await this.client._request("POST",`/api/v1/theses/${x(e,"id")}/close`,{body:r}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${x(e,"id")}`);if(n===void 0)return{};if(!U(n)||Object.keys(n).length!==0)throw f("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=Ke(e.body),r=e.mode===void 0?"reformat":jr(e.mode),s=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:r}});if(!U(s)||typeof s.body!="string")throw f("rewrite response must contain a string body");return{body:un(s.body)}}};function Or(t){return{request_id:an(t.request_id),body:Ke(t.body),title:yt(t.title??""),entity_ids:ln(t.entity_ids??[],"entity_ids"),visibility:gt(t.visibility??"public")}}i(Or,"createBody");function Mr(t){return{request_id:an(t.request_id),expected_author_version_id:x(t.expected_author_version_id,"expected_author_version_id"),body:Ke(t.body),title:yt(t.title??""),entity_ids:ln(t.entity_ids??[],"entity_ids"),visibility:gt(t.visibility),editorial:t.editorial??!1}}i(Mr,"updateBody");function Je(t){if(!U(t)||!U(t.thesis))throw f("response must contain thesis");let e=t.thesis;return{thesis:{id:z(e.id,"thesis.id"),author_version_id:z(e.author_version_id,"thesis.author_version_id"),material_version_id:z(e.material_version_id,"thesis.material_version_id"),title:Yr(e.title),body:un(e.body),entity_ids:Br(e.entity_ids,"thesis.entity_ids"),visibility:Vr(e.visibility),closed:Wr(e.closed,"thesis.closed"),closing_note:Qr(e.closing_note),author_kind:E(e.author_kind,"thesis.author_kind"),author_ref:E(e.author_ref,"thesis.author_ref")}}}i(Je,"thesisResponse");function $r(t){let e=Je(t);if(!U(t)||!U(t.author))throw f("response must contain author");let n=t.author,r={id:z(n.id,"author.id"),kind:E(n.kind,"author.kind"),display_name:E(n.display_name,"author.display_name"),avatar_url:E(n.avatar_url,"author.avatar_url"),username:E(n.username,"author.username")};if(!Array.isArray(t.entities))throw f("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw f("entities must match thesis.entity_ids");let s=t.entities.map((o,a)=>{if(!U(o))throw f(`entities[${a}] must be an object`);let l={id:z(o.id,`entities[${a}].id`),ticker:E(o.ticker,`entities[${a}].ticker`),name:E(o.name,`entities[${a}].name`),icon_url:E(o.icon_url,`entities[${a}].icon_url`),kind:E(o.kind,`entities[${a}].kind`)};if(l.id!==e.thesis.entity_ids[a])throw f("entities must preserve thesis.entity_ids order");return l});return{thesis:e.thesis,author:r,entities:s}}i($r,"thesisGetResponse");function an(t){if(!Gr.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw _("request_id must be a non-zero RFC 4122 UUID");return t}i(an,"requireRequestID");function x(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw _(`${e} must be a positive int64 decimal string`);if(BigInt(t)>Fr)throw _(`${e} must be a positive int64 decimal string`);return t}i(x,"requireID");function ln(t,e){if(!Array.isArray(t))throw _(`${e} must be an array`);if(t.length>20)throw _(`${e} must contain at most 20 IDs`);return t.map((n,r)=>x(n,`${e}[${r}]`))}i(ln,"requireIDs");function Ke(t){let e=F(t,"body");if(e.trim().length===0)throw _("body must not be blank");if(on.encode(e).byteLength>65536)throw _("body must be at most 65536 UTF-8 bytes");return e}i(Ke,"requireBody");function yt(t){let e=F(t,"title");if(on.encode(e).byteLength>500)throw _("title must be at most 500 UTF-8 bytes");return e}i(yt,"requireTitle");function gt(t){let e=F(t,"visibility");if(e!=="public"&&e!=="private")throw _("visibility must be public or private");return e}i(gt,"requireVisibility");function jr(t){let e=F(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw _("mode must be reformat, shorten, or enrich")}i(jr,"requireRewriteMode");function F(t,e){if(typeof t!="string")throw _(`${e} must be a string`);if(Lr.test(t))throw _(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw _(`${e} must not contain NUL`);return t}i(F,"requireText");function z(t,e){if(typeof t=="number")throw f(`${e} must be a decimal string; numeric IDs are unsafe`);try{return x(t,e)}catch{throw f(`${e} must be a positive int64 decimal string`)}}i(z,"responseID");function Br(t,e){if(!Array.isArray(t))throw f(`${e} must be an array`);if(t.length>20)throw f(`${e} must contain at most 20 IDs`);return t.map((n,r)=>z(n,`${e}[${r}]`))}i(Br,"responseIDs");function E(t,e){try{return F(t,e)}catch{throw f(`${e} must be valid text`)}}i(E,"responseText");function Qr(t){try{return F(t,"note")}catch{throw f("thesis.closing_note must be valid text")}}i(Qr,"responseClosingNote");function Wr(t,e){if(typeof t!="boolean")throw f(`${e} must be boolean`);return t}i(Wr,"responseBoolean");function Vr(t){try{return gt(t)}catch{throw f("thesis.visibility must be public or private")}}i(Vr,"responseVisibility");function un(t){try{return Ke(t)}catch{throw f("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}i(un,"responseBody");function Yr(t){try{return yt(t)}catch{throw f("response title must be valid text at most 500 UTF-8 bytes")}}i(Yr,"responseTitle");function U(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(U,"isRecord");function _(t){return new u("INVALID_ARGUMENT",t,400)}i(_,"invalidArgument");function f(t){return new u("INVALID_RESPONSE",t,502)}i(f,"invalidResponse");var Hr="https://api-llm.prd.alva.ai",zr="https://data-tools.prd.space.id";function bt(t){return typeof t=="object"&&t!==null}i(bt,"isRecord");function Xe(t,e){if(!bt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}i(Xe,"stringField");function Jr(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=Xe(t,"code");r&&(e.code=r)}else if(bt(t)){let r=Xe(t,"code"),s=Xe(t,"name"),o=Xe(t,"message");r&&(e.code=r),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(r=>!!r);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}i(Jr,"describeCause");function Kr(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",n={};t instanceof Error?(n.name=t.name,n.message=t.message):n.message=String(t);let{message:r,details:s}=Jr(bt(t)?t.cause:void 0);return s&&(n.cause=s),{message:r?`${e}; cause: ${r}`:e,details:n}}i(Kr,"describeFetchFailure");var Ze=class{static{i(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_forYou;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_steward;_tradingPairs;_theses;constructor(e){this.baseUrl=e.baseUrl??Hr,this.arraysBaseUrl=e.arraysBaseUrl??zr,this.viewer_token=e.viewer_token,this.pbsvToken=e.pbsvToken,this.apiKey=e.apiKey,this.gaClientId=e.gaClientId,this.gaSessionId=e.gaSessionId,this.utmParams=e.utmParams,this.signal=e.signal,this.originSessionId=e.originSessionId,this.originSessionKind=e.originSessionKind,this.originInboxPath=e.originInboxPath}get fs(){return this._fs??=new be(this)}get run(){return this._run??=new _e(this)}get deploy(){return this._deploy??=new Pe(this)}get serviceAccount(){return this._serviceAccount??=new Re(this)}get release(){return this._release??=new ke(this)}get feed(){return this._feed??=new ve(this)}get automation(){return this._automation??=new B(this)}get playbooks(){return this._playbooks??=new Te(this)}get secrets(){return this._secrets??=new Ae(this)}get sdk(){return this._sdk??=new Ce(this)}get dataSkills(){return this._dataSkills??=new Ie(this)}get playbookSkills(){return this._playbookSkills??=new qe(this)}get comments(){return this._comments??=new xe(this)}get remix(){return this._remix??=new Ne(this)}get screenshot(){return this._screenshot??=new De(this)}get user(){return this._user??=new Ue(this)}get trading(){return this._trading??=new Fe(this)}get portfolio(){return this._portfolio??=new Ge(this)}get arraysJwt(){return this._arraysJwt??=new Le(this)}get notifications(){return this._notifications??=new Oe(this)}get notificationPreferences(){return this._notificationPreferences??=new Me(this)}get subscriptions(){return this._subscriptions??=new $e(this)}get alerts(){return this._alerts??=new Q(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new je(this)}get feedback(){return this._feedback??=new Be(this)}get functions(){return this._functions??=new Qe(this)}get credits(){return this._credits??=new We(this)}get markets(){return this._markets??=new W(this)}get tradingPairs(){return this._tradingPairs??=new H(this)}get schedules(){return this._schedules??=new V(this)}get steward(){return this._steward??=new Y(this)}get theses(){return this._theses??=new J(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new u("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get forYou(){return this._forYou??=new j(this)}async _request(e,n,r){let o=`${r?.baseUrl??this.baseUrl}${n}`;if(r?.query){let v=new URLSearchParams;for(let[A,et]of Object.entries(r.query))et!=null&&v.set(A,String(et));let L=v.toString();L&&(o+=`?${L}`)}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 l;r?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",l=r.rawBody):r?.jsonBody!==void 0?(a["Content-Type"]="application/json",l=r.jsonBody):r?.body!==void 0&&(a["Content-Type"]="application/json",l=JSON.stringify(r.body));let c,d=r?.timeoutMs,p=r?.signal??this.signal;if(p?.aborted)throw new u("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let P=d!==void 0?new AbortController:void 0,T=!1,G,me;P&&d!==void 0&&(p&&(me=i(()=>P.abort(p.reason),"abortListener"),p.addEventListener("abort",me,{once:!0})),G=setTimeout(()=>{T=!0,P.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let _t={method:e,headers:a,body:l,signal:P?.signal??p};d!==void 0&&(_t.timeout=d);try{c=await fetch(o,_t)}catch(v){if(p?.aborted&&!T)throw new u("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(T)throw new u("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let L=Kr(v);throw new u("NETWORK_ERROR",L.message,0,{method:e,path:n,...L.details})}finally{me&&p&&p.removeEventListener("abort",me),G!==void 0&&clearTimeout(G)}if(!c.ok){let v="";try{v=await Promise.resolve(c.text())}catch{v=""}if((c.headers.get("content-type")??"").includes("application/json")&&v)try{let A=JSON.parse(v);if(A.error)throw new u(A.error.code??"UNKNOWN",A.error.message??`HTTP ${c.status}`,c.status)}catch(A){if(A instanceof u)throw A}throw new u("UNKNOWN",`HTTP ${c.status}: ${v.slice(0,200)}`,c.status)}if(c.status===204)return;let Pt=(c.headers.get("content-type")??"").toLowerCase();return Pt.includes("application/json")||Pt.includes("+json")?c.json():c.arrayBuffer()}};var Xr="0.28.1-beta.0";ot();return fn(Zr);})();
|
|
254
290
|
//# sourceMappingURL=browser.global.js.map
|