@alva-ai/toolkit 0.28.1-beta.0 → 0.29.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 +2 -1
- package/dist/browser.global.js +24 -24
- package/dist/browser.global.js.map +1 -1
- package/dist/cli.d.ts +52 -0
- package/dist/cli.js +247 -8
- package/dist/cli.js.map +1 -1
- package/dist/dispatch.d.ts +52 -0
- package/dist/dispatch.js +80 -8
- package/dist/dispatch.js.map +1 -1
- package/dist/index.cjs +188 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +53 -1
- package/dist/index.d.ts +53 -1
- package/dist/index.js +188 -3
- 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 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=`
|
|
1
|
+
"use strict";var AlvaToolkit=(()=>{var fe=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var fn=Object.prototype.hasOwnProperty;var r=(t,e)=>fe(t,"name",{value:e,configurable:!0});var yn=(t,e)=>{for(var n in e)fe(t,n,{get:e[n],enumerable:!0})},gn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of hn(e))!fn.call(t,s)&&s!==n&&fe(t,s,{get:()=>e[s],enumerable:!(i=mn(e,s))||i.enumerable});return t};var bn=t=>gn(fe({},"__esModule",{value:!0}),t);var ir={};yn(ir,{AlertsResource:()=>V,AlvaClient:()=>nt,AlvaError:()=>u,AutomationAlertDeliveryResource:()=>pe,AutomationResource:()=>Q,CliUsageError:()=>be,ForYouResource:()=>B,MarketsResource:()=>W,PBSV_UPDATE_MESSAGE:()=>vt,SUBSCRIBE_MANAGE_MESSAGE:()=>qt,SUBSCRIBE_PROPOSE_MESSAGE:()=>Ct,SUBSCRIBE_RESULT_MESSAGE:()=>It,SchedulesResource:()=>Y,StewardResource:()=>H,ThesesResource:()=>K,TradingPairsResource:()=>z,UDF_AUTH_REQUIRED_MESSAGE:()=>At,UDF_CONSENT_REQUEST_MESSAGE:()=>Tt,UDF_CONSENT_RESPONSE_MESSAGE:()=>Et,UdfAuthRequiredError:()=>$,UdfConsentDeniedError:()=>ne,UdfConsentRequiredError:()=>te,UdfConsentTimeoutError:()=>ie,UdfError:()=>b,UdfExecutionError:()=>le,UdfFunctionDisabledError:()=>oe,UdfFunctionNotFoundError:()=>se,UdfInsufficientCredits:()=>re,UdfPidMismatchError:()=>D,UdfRateLimitedError:()=>ae,UdfTokenExpiredError:()=>Z,UdfTokenInvalidError:()=>ee,UdfTransportError:()=>j,VERSION:()=>nr,getViewerToken:()=>ue,installPlaybookRuntime:()=>ut,mapUdfErrorResponse:()=>at,playbookIdFromToken:()=>ot,subscribe:()=>Gt,udf:()=>Lt});var b=class extends Error{static{r(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:i={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=i,this.status=s}},$=class extends b{static{r(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},Z=class extends b{static{r(this,"UdfTokenExpiredError")}},ee=class extends b{static{r(this,"UdfTokenInvalidError")}},D=class extends b{static{r(this,"UdfPidMismatchError")}},te=class extends b{static{r(this,"UdfConsentRequiredError")}},ne=class extends b{static{r(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},ie=class extends b{static{r(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},re=class extends b{static{r(this,"UdfInsufficientCredits")}},se=class extends b{static{r(this,"UdfFunctionNotFoundError")}},oe=class extends b{static{r(this,"UdfFunctionDisabledError")}},ae=class extends b{static{r(this,"UdfRateLimitedError")}},le=class extends b{static{r(this,"UdfExecutionError")}},j=class extends b{static{r(this,"UdfTransportError")}},vt="alva:pbsv:update",Tt="alva:udf:consent-request",Et="alva:udf:consent-response",At="alva:udf:auth-required",Ct="alva:subscribe:propose",It="alva:subscribe:result",qt="alva:subscribe:manage",xt="https://api-llm.prd.alva.ai",Dt=300*1e3,X=null,T=null,st=xt,C=null,R=null,wt=!1,ye=new Map,ge=new Map,_n=r(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Pn=r(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),ot=r(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Pn(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),ue=r(()=>X,"getViewerToken"),M=r(()=>!!ue(),"isAuthenticated"),Rn=r(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),kn=r(t=>{let e=new URLSearchParams(t.location.search);X=e.get("_pbsv"),T=e.get("parent_origin"),st=(e.get("api_origin")||xt).replace(/\/$/,""),C=ot(X),X&&Rn(t)},"parseBootParams"),Nt=r(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Sn=r(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),wn=r(t=>{let e=t;return{...e,result:Sn(e.result)}},"normalizeInvokeResponse"),Ut=r(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),at=r((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,s=Ut(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new Z(i,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new ee(i,o);case"PBSV_PID_MISMATCH":return new D(i,o);case"CONSENT_REQUIRED":return new te(i,o);case"INSUFFICIENT_CREDITS":return new re(i,o);case"FUNCTION_NOT_FOUND":return new se(i,o);case"FUNCTION_DISABLED":return new oe(i,o);case"RESOURCE_EXHAUSTED":return new ae(i,o);case"EXECUTION_FAILED":return new le(i,o);default:return new j(i,o)}},"mapUdfErrorResponse"),vn=r(t=>{if(!R||!T||t.origin!==T||t.source!==R.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===vt){typeof e.token=="string"&&e.token.length>0&&(X=e.token,C=ot(e.token));return}if(e.type===It){if(typeof e.request_id!="string")return;let i=ge.get(e.request_id);if(!i)return;clearTimeout(i.timer),ge.delete(e.request_id),i.resolve(_n(e.status));return}if(e.type!==Et||typeof e.request_id!="string")return;let n=ye.get(e.request_id);n&&(clearTimeout(n.timer),ye.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Ft=r(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Tn=r(()=>{if(!C)return null;let t=Number(C);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),En=r(async(t,e)=>{if(!R||!T)return"denied";let n=T,i=Ft();return new Promise(s=>{let o=setTimeout(()=>{ye.delete(i),s("timeout")},Dt);ye.set(i,{resolve:s,timer:o}),R?.parent.postMessage({type:Tt,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),An=r(async t=>{if(!R||!T)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let i=T,s=Ft();return new Promise(o=>{let a=setTimeout(()=>{ge.delete(s),o("timeout")},Dt);ge.set(s,{resolve:o,timer:a}),R?.parent.postMessage({type:Ct,request_id:s,playbook_id:C,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Cn=r(()=>{!R||!T||R.parent.postMessage({type:qt,playbook_id:C},T)},"manageSubscriptions"),Gt={propose:An,manage:Cn},In=r(t=>{!R||!T||R.parent.postMessage({type:At,function_name:t},T)},"requestAuthentication"),lt=r(async(t,e,n=!1)=>{let i=ue();if(!i)throw new $;if(!C)throw new D("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=Tn();if(!s)throw new D("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${st}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new j("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Nt(o);if(o.ok)return wn(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let l=Ut(a),c=typeof l.playbook_id=="string"?l.playbook_id:C,d=typeof l.min_allowance_suggested=="number"?l.min_allowance_suggested:1,p=await En(c,d);if(p==="granted")return lt(t,e,!0);throw p==="timeout"?new ie:new ne}throw at(a,o.status)},"call"),qn=r(async()=>{let t=ue();if(!t)throw new $;if(!C)throw new D("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${st}/api/v1/service/functions`);e.searchParams.set("playbook_id",C);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await Nt(n);if(!n.ok)throw at(i,n.status);let s=i.functions;return Array.isArray(s)?s:[]},"list"),rt=r((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),xn=r(t=>{if(typeof t!="string")return t;let n=R?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),Dn=r((t,e)=>{if(!R)throw new Error("Playbook runtime is not installed.");let n=xn(t),i=R.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=M()?s:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),M()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!M()){In(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=o,rt(i,"alva:udf-button:loading",{functionName:e.functionName});try{let l=await lt(e.functionName,e.params??{});rt(i,"alva:udf-button:result",{functionName:e.functionName,result:l})}catch(l){rt(i,"alva:udf-button:error",{functionName:e.functionName,error:l})}finally{i.disabled=!1,i.textContent=M()?s:a,M()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),Lt={call:lt,list:qn,getViewerToken:ue,isAuthenticated:M,renderButton:Dn,UdfError:b,UdfAuthRequiredError:$,UdfTokenExpiredError:Z,UdfTokenInvalidError:ee,UdfPidMismatchError:D,UdfConsentRequiredError:te,UdfConsentDeniedError:ne,UdfConsentTimeoutError:ie,UdfInsufficientCredits:re,UdfFunctionNotFoundError:se,UdfFunctionDisabledError:oe,UdfRateLimitedError:ae,UdfExecutionError:le,UdfTransportError:j},ut=r(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||wt)return;R=e,wt=!0,kn(e),e.addEventListener("message",vn);let n=e,i=n.alva||{};n.alva={...i,udf:Lt,subscribe:Gt}},"installPlaybookRuntime");var u=class extends Error{static{r(this,"AlvaError")}code;status;details;constructor(e,n,i,s){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=s}},be=class extends Error{static{r(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function Ot(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}r(Ot,"isArrayBuffer");var Mt=1;function Nn(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,s=0,o=0;if(n>=194&&n<=223)i=1,s=128,o=n&31;else if(n>=224&&n<=239)i=2,s=2048,o=n&15;else if(n>=240&&n<=244)i=3,s=65536,o=n&7;else return!1;if(e+i>=t.length)return!1;for(let a=1;a<=i;a+=1){let 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+=i+1}return!0}r(Nn,"isValidUtf8");var _e=class{constructor(e){this.client=e}client;static{r(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!Ot(n)||!Nn(new Uint8Array(n)))return n;let i=new TextDecoder("utf-8").decode(n);try{return JSON.parse(i)}catch{return i}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:Mt}:{}}})}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:Mt}:{}},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 $t="9007199254740991";function jt(t,e,n,i){let s=t.length+e,o=n.length+i;if(s!==o)return s>o;for(let a=0;a<s;a++){let l=a<t.length?t[a]:"0",c=a<n.length?n[a]:"0";if(l!==c)return l>c}return!1}r(jt,"scaledIntegerGreater");function Un(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,i=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+i).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=s-i.length;return a>=0?jt(o,a,$t,0):jt(o,0,$t,-a)}r(Un,"numberOutsideSafeRange");function Fn(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(Un(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}r(Fn,"validateJSONNumberTokens");function ct(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((i,s)=>ct(i,`${e}[${s}]`,n));else{let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);ct(o.value,`${e}.${s}`,n)}}n.delete(t)}}r(ct,"assertPlainJSONData");function ce(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");ct(t,"args",new Set);let e=JSON.stringify(t);return Bt(e),e}r(ce,"serializeStructuredArgs");function Bt(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Fn(t)}r(Bt,"validateSerializedArgs");function de(t,e,n){let i=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Bt(n),i.push([e,n])),`{${i.map(([s,o])=>{let a=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}r(de,"objectWithRawJSONField");var Pe=class{constructor(e){this.client=e}client;static{r(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,ce(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let i={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:i}:{jsonBody:de(i,"args",n)},timeoutMs:e.timeout_ms})}};var Re=class{constructor(e){this.client=e}client;static{r(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,ce(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let i={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:i}:{jsonBody:de(i,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,ce(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:i,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...n===void 0?{body:s}:{jsonBody:de(s,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var ke=class{constructor(e){this.client=e}client;static{r(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var Se=class{constructor(e){this.client=e}client;static{r(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url,confirm_bundled_feed_exposure:e.confirm_bundled_feed_exposure}})}};var ve=class{constructor(e){this.client=e}client;static{r(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=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}r(we,"requireFeedID");var Gn=`
|
|
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 E(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(E,"record");function Ln(t){if(!E(t))throw new Error("For You parameters must be an object");let e=t.first===void 0?20:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw new Error("first must be an integer between 1 and 50");for(let n of["after","newerThan"]){let i=t[n];if(i!==void 0&&(typeof i!="string"||!i.trim()))throw new Error(`${n} must be a non-empty cursor`)}if(t.feedId!==void 0&&!Te(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}r(Ln,"validateForYouListParams");function Te(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}r(Te,"isPositiveInt64");function G(){throw new u("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}r(G,"invalidResponse");function On(t){if(!E(t)||!Array.isArray(t.edges)||!E(t.pageInfo))return G();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return G();for(let s of t.edges){if(!E(s)||typeof s.cursor!="string"||!s.cursor.trim()||!E(s.node))return G();let o=s.node;if(typeof o.id!="string"||!o.id.startsWith("FeedEntry:")||!Te(o.id.slice(10))||!E(o.feed)||!Te(o.feed.id)||!E(o.major)||typeof o.major.id!="string"||!Te(o.major.feedId)||typeof o.title!="string"||typeof o.body!="string")return G()}let n=t.edges[0],i=t.edges[t.edges.length-1];return e.startCursor!==(n?.cursor??"")||e.endCursor!==(i?.cursor??"")||t.edges.length===0&&e.hasNextPage?G():t}r(On,"connection");var B=class{constructor(e){this.client=e}client;static{r(this,"ForYouResource")}async list(e={}){Ln(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Gn,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});if(!E(n))return G();if(n.errors!==void 0){if(!Array.isArray(n.errors))return G();if(n.errors.length>0){let i=n.errors.flatMap(s=>E(s)&&typeof s.message=="string"?[s.message]:[]);throw new u("GRAPHQL_ERROR",i.join("; ")||"GraphQL request failed",400,{errors:n.errors})}}if(!E(n.data)||!E(n.data.viewer)||n.data.viewer.forYou==null)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.forYou",502);return On(n.data.viewer.forYou)}};var Mn=`
|
|
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(),$n=`
|
|
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(),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=`
|
|
53
|
+
`.trim(),Q=class{constructor(e){this.client=e;this.delivery=new pe(e)}client;static{r(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=jn(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(!Bn(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)}},pe=class{constructor(e){this.client=e}client;static{r(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Ee(e.id),s=(await this.graphql(Mn,{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),i=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!i&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=i?Qn(e.alvaChannelIds??[]):void 0,l=(await this.graphql($n,{input:{automationId:n,...i?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,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 i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(i.errors&&i.errors.length>0)throw new u("GRAPHQL_ERROR",Vn(i.errors),400,{errors:i.errors});if(!i.data)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};function jn(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}r(jn,"requireAutomationID");function Ee(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}r(Ee,"requireAutomationIDString");function Bn(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}r(Bn,"hasAutomationUpdate");function Qn(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}r(Qn,"uniqueAlvaChannelIDs");function Vn(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}r(Vn,"graphQLErrorMessage");var Qt=["public","private","paid"];var Ae=class{constructor(e){this.client=e}client;static{r(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new u("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let i=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let a=await this.listByOwner({owner:i,cursor:o,limit:100}),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 i=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=Wn(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(o=>Yn(o,s)),has_next:i.has_next??!1}}async setVisibility(e){if(!Qt.includes(e.visibility))throw new u("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${Qt.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Wn(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let i=n[1].toLowerCase();return i==="prd"?"https://alva.ai":`https://${i}.alva.ai`}}catch{}return"https://alva.ai"}r(Wn,"webOriginFromApiBase");function Yn(t,e){let n=t.creator?.name??"",i=t.name??"",s=n&&i?`${n}/${i}`:i,o=n&&i?`/u/${n}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}r(Yn,"toAgentPlaybook");var Ce=class{constructor(e){this.client=e}client;static{r(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var Ie=class{constructor(e){this.client=e}client;static{r(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var Vt=[{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 Wt(t,e){return Vt.find(n=>n.skill===t&&n.file===e)}r(Wt,"getSkillEndpointMetadata");function dt(t){return Vt.filter(e=>e.skill===t)}r(dt,"listSkillEndpointMetadata");var qe=class{constructor(e){this.client=e}client;static{r(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...Yt(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=dt(e.name);return{...s,...Yt(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=Wt(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function Yt(t){let e=dt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}r(Yt,"metadataSummaryForSkill");function Ht(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}r(Ht,"normalizePlaybookSkillSummary");function zt(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]}}r(zt,"parsePlaybookSkillId");var xe=class{constructor(e){this.client=e}client;static{r(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(Ht)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=zt(e),s=encodeURIComponent(n),o=encodeURIComponent(i),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{...Ht(l),files:l.files??[]}}async file(e,n){let{username:i,name:s}=zt(e),o=encodeURIComponent(i),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 De=class{constructor(e){this.client=e}client;static{r(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var Ne=class{constructor(e){this.client=e}client;static{r(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var Ue=class{constructor(e){this.client=e}client;static{r(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var Fe=class{constructor(e){this.client=e}client;static{r(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var Ge=class{constructor(e){this.client=e}client;static{r(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var Le=class{constructor(e){this.client=e}client;static{r(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var Oe=class{constructor(e){this.client=e}client;static{r(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var Me=class{constructor(e){this.client=e}client;static{r(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:Hn(e)})}};function Hn(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}r(Hn,"buildQuery");var $e=class{constructor(e){this.client=e}client;static{r(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var je=class{constructor(e){this.client=e}client;static{r(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var V=class{constructor(e){this.client=e}client;static{r(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var Be=class{constructor(e){this.client=e}client;static{r(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:Jt(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:Jt(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 Jt(t){return`{"session_id":${Kt(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${Kt(t.target_id)}}`}r(Jt,"mutationBody");function Kt(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}r(Kt,"idLiteral");var Qe=class{constructor(e){this.client=e}client;static{r(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var Ve=class{constructor(e){this.client=e}client;static{r(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:Jn(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 pt(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>pt(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:zn(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 pt(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),i=Xt(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),i!==void 0&&(e.updated_at_ms=i),e}r(pt,"normalizeAllowance");function zn(t){let e=pt(t);if(!e)throw new Error("allowance response missing allowance");return e}r(zn,"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,i=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}r(Xt,"timestampMs");function Jn(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}r(Jn,"parseResultPayload");var Kn=`
|
|
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(),Xn=`
|
|
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 Zn(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}r(Zn,"graphQLErrorMessage");var We=class{constructor(e){this.client=e}client;static{r(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(Kn)).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 i=(await this.graphql(Xn,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!i)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return i}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new u("GRAPHQL_ERROR",Zn(i.errors),400,{errors:i.errors});if(!i.data)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var ei=["Q1","Q2","Q3","Q4"],ti=["latest-completed","next-confirmed"],ni=`
|
|
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(),ii=`
|
|
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(),ri=`
|
|
153
153
|
query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
154
154
|
market {
|
|
155
155
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -219,7 +219,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
219
219
|
}
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
|
-
`.trim();function
|
|
222
|
+
`.trim();function si(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}r(si,"graphQLErrorMessage");function mt(t){let e=t.trim().toUpperCase();if(!e)throw new u("INVALID_ARGUMENT","ticker is required",400);return e}r(mt,"normalizedTicker");var W=class{constructor(e){this.client=e}client;static{r(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=mt(e),s=(await this.graphql(ni,{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=mt(e),s=(await this.graphql(ii,{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=mt(e.ticker),i=e.event,s=e.fiscalYear,o=e.fiscalQuarter;if(i!==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(i!==void 0&&!ti.includes(i))throw new u("INVALID_ARGUMENT",`Unknown earnings event selector: ${i}`,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&&!ei.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=i??"latest-completed",S=await this.earningsPeriods(n),q=this.selectPeriod(S,P,n);l=q.fiscalYear,c=q.fiscalQuarter}let p=(await this.graphql(ri,{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,i){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let s=e.periods.filter(o=>o.status==="UPCOMING").sort((o,a)=>o.earningsDate.localeCompare(a.earningsDate));if(s.length>0)return s[0]}throw new u("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${n} earnings event is available for ${i}`,404,{ticker:i,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 i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new u("GRAPHQL_ERROR",si(i.errors),400,{errors:i.errors});if(!i.data)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var Ye=`
|
|
223
223
|
id
|
|
224
224
|
name
|
|
225
225
|
rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
|
|
@@ -232,45 +232,45 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
232
232
|
nextFireAtMs
|
|
233
233
|
createdAtMs
|
|
234
234
|
updatedAtMs
|
|
235
|
-
`,
|
|
235
|
+
`,oi=`
|
|
236
236
|
query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
|
|
237
237
|
viewer { channel(id: $channelId) {
|
|
238
238
|
schedules(input: { first: 64, after: $after }) {
|
|
239
|
-
edges { node { channel { id } ${
|
|
239
|
+
edges { node { channel { id } ${Ye} } }
|
|
240
240
|
pageInfo { hasNextPage endCursor }
|
|
241
241
|
}
|
|
242
242
|
} }
|
|
243
|
-
}`.trim(),
|
|
243
|
+
}`.trim(),ai=`
|
|
244
244
|
mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
|
|
245
245
|
updateChannelSchedule(input: $input) {
|
|
246
|
-
schedule { channel { id } ${
|
|
246
|
+
schedule { channel { id } ${Ye} }
|
|
247
247
|
deleted
|
|
248
248
|
}
|
|
249
|
-
}`.trim(),
|
|
249
|
+
}`.trim(),li=`
|
|
250
250
|
query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
|
|
251
251
|
viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
|
|
252
|
-
edges { node { ${
|
|
252
|
+
edges { node { ${Ye} } }
|
|
253
253
|
pageInfo { hasNextPage endCursor }
|
|
254
254
|
} }
|
|
255
|
-
}`.trim(),
|
|
255
|
+
}`.trim(),ui=`
|
|
256
256
|
mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
|
|
257
257
|
updateSessionSchedule(input: $input) {
|
|
258
|
-
schedule { ${
|
|
258
|
+
schedule { ${Ye} }
|
|
259
259
|
deleted
|
|
260
260
|
}
|
|
261
|
-
}`.trim(),
|
|
261
|
+
}`.trim(),ci=`
|
|
262
262
|
query ToolkitAgentChannel {
|
|
263
263
|
viewer { channels { id kind } }
|
|
264
|
-
}`.trim(),
|
|
264
|
+
}`.trim(),di=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,pi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,mi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,hi=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,fi={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},Y=class{constructor(e){this.client=e}client;static{r(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=ft(e),i="inboxPath"in n,s=[],o=null,a=new Set;for(;;){let l=await this.graphql(i?li:oi,{...n,after:o}),c=i?l.viewer?.sessionSchedules:l.viewer?.channel?.schedules;if(!c?.edges)throw en();for(let p of c.edges){if(!p?.node)throw _();s.push(ht(p.node))}if(c.pageInfo?.hasNextPage!==!0)return s;let d=c.pageInfo.endCursor;if(!d||a.has(d))throw _();a.add(d),o=d}}async put(e){this.client._requireAuth();let n={...ft(e),name:tn(e.name),definition:{...yi(e.rule,e.bounds),message:{text:Pi(e.text)}}},i=(await this.update(n))?.schedule;if(!i)throw _();return ht(i)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.update({...Zt(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw _()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(ci)).viewer?.channels?.find(i=>i.kind==="AGENT")?.id;if(!n)throw en();return n}async manage(e,n){this.client._requireAuth();let i=(await this.update({...Zt(n),lifecycle:e}))?.schedule;if(!i)throw _();return ht(i)}async update(e){let n="inboxPath"in e,i=await this.graphql(n?ui:ai,{input:e});return n?i.updateSessionSchedule:i.updateChannelSchedule}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors?.length){let s=i.errors.map(d=>d.extensions?.code),a=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,l=a?fi[a]:void 0,c=a!==void 0&&l!==void 0?a:"GRAPHQL_ERROR";throw new u(c,i.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",l??502,{errors:i.errors})}if(!i.data)throw _();return i.data}};function yi(t,e){let n=gi(e);switch(t.kind){case"after":if(n)throw h("after does not accept recurring bounds");let i=Date.now()+nn(t.duration,1),s=Math.ceil(i/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:yt(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Ri(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}:{}}}}r(yi,"ruleInput");function gi(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=yt(t.startsAt)),t.until!==void 0&&(e.untilMs=yt(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}r(gi,"boundsInput");function ht(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw _();let i=t.bounds??{},s=t.message??{},o={name:t.name,rule:bi(t.rule),bounds:{...i.startsAtMs!=null?{startsAt:L(i.startsAtMs,!0)}:{},...i.untilMs!=null?{until:L(i.untilMs,!0)}:{},...i.maxOccurrences!=null?{maxOccurrences:gt(i.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:gt(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:L(t.nextFireAtMs,!0)}:{},createdAt:L(t.createdAtMs),updatedAt:L(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw _();let l={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!l)throw _();o.failure={code:l,...t.failureAtMs!=null?{at:L(t.failureAtMs)}:{}}}return o}r(ht,"fromWireSchedule");function bi(t){switch(t.kind){case"AT":if(t.atMs==null)throw _();return{kind:"at",timestamp:L(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw _();return{kind:"every",interval:`PT${gt(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw _();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw _()}r(bi,"fromWireRule");function Zt(t){return{...ft(t),name:tn(t.name)}}r(Zt,"managementInput");function ft(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw h("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:_i(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?rn(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 h("inboxPath must be a canonical absolute ALFS Inbox path");let i=e.endsWith(".inbox.jsonl")?e.slice(0,-12)+".jsonl":e.endsWith(".inbox")&&!e.endsWith(".jsonl.inbox")?e.slice(0,-6):void 0;if(i===void 0||/\.inbox(?:\.jsonl)?$/.test(i)||/\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(i)||i.endsWith("/.jsonl"))throw h("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}r(ft,"targetInput");function _i(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}r(_i,"channelID");function tn(t){if(!di.test(t))throw h("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}r(tn,"requireName");function Pi(t){let e=rn(t);if(e===void 0||!t.trim()||e>16*1024)throw h("text must be 1..16384 UTF-8 bytes");return t}r(Pi,"requireText");function Ri(t){let e=nn(t,60);if(e%1e3!==0)throw h("duration must resolve to whole seconds");return e/1e3}r(Ri,"durationSeconds");function nn(t,e){let n=hi.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[i,s,o,a]=n.slice(1,5).map(d=>BigInt(d??"0")),l=((i*24n+s)*60n+o)*60n+a;if(l<BigInt(e))throw h(`duration must be at least ${e} whole seconds`);let c=Number(l*1000n);if(!Number.isSafeInteger(c))throw h("duration is out of range");return c}r(nn,"durationMilliseconds");function yt(t,e=!1){let n=(e?mi:pi).exec(t);if(!n)throw h("timestamp must be RFC3339 with a timezone");let[i,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(i,s,0)).getUTCDate(),S=Date.parse(t);if(!Number.isFinite(S)||i<1||i>9999||s<1||s>12||o<1||o>P||a>23||l>59||c>59||d>23||p>59)throw h("timestamp must be RFC3339 with a timezone");return S}r(yt,"timestampMilliseconds");function L(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw _();let n=new Date(t);if(Number.isNaN(n.getTime()))throw _();return n.toISOString()}r(L,"timestampString");function gt(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw h(`${e} exceeds JavaScript safe integer range`);return n}r(gt,"safeInteger");function h(t){return new u("INVALID_ARGUMENT",t,400)}r(h,"invalid");function rn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}r(rn,"utf8Size");function en(){return new u("NOT_FOUND","channel schedule target not found",404)}r(en,"scheduleNotFound");function _(){return new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}r(_,"scheduleEmptyResponse");var ki={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},Si=`
|
|
265
265
|
mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
|
|
266
266
|
updateStewardDelivery(input: $input) { delivery { deliveryId state } }
|
|
267
|
-
}`.trim(),
|
|
267
|
+
}`.trim(),wi=`
|
|
268
268
|
mutation ToolkitStewardForward($input: UpdateStewardDeliveryInput!) {
|
|
269
269
|
updateStewardDelivery(input: $input) { delivery { deliveryId state channelMessageId } }
|
|
270
|
-
}`.trim(),
|
|
270
|
+
}`.trim(),vi=`
|
|
271
271
|
mutation ToolkitStewardSend($input: PostStewardMessageInput!) {
|
|
272
272
|
postStewardMessage(input: $input) { message { channelMessageId requestId } }
|
|
273
|
-
}`.trim(),
|
|
273
|
+
}`.trim(),Ti=`
|
|
274
274
|
query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInput) {
|
|
275
275
|
viewer {
|
|
276
276
|
stewardDigestPending(inboxPath: $inboxPath, input: $input) {
|
|
@@ -283,8 +283,8 @@ query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInp
|
|
|
283
283
|
windowUntilMs
|
|
284
284
|
}
|
|
285
285
|
}
|
|
286
|
-
}`.trim(),
|
|
286
|
+
}`.trim(),Ei=`
|
|
287
287
|
mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
|
|
288
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);})();
|
|
289
|
+
}`.trim(),Ai=new Set(["immediate","digest","suppress"]),Ci=/^[1-9][0-9]{0,18}$/;function w(t){return new u("INVALID_ARGUMENT",t,400)}r(w,"invalid");function me(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw w("steward commands require the steward Session Inbox path");return t.inboxPath}r(me,"requireInboxPath");function bt(t,e="delivery id"){if(!Ci.test(t))throw w(`${e} must be a positive integer`);return t}r(bt,"requireDeliveryId");function sn(t){if(t.length===0)throw w("at least one delivery id is required");let e=new Set;for(let n of t){if(bt(n),e.has(n))throw w(`duplicate delivery id ${n}`);e.add(n)}return[...e]}r(sn,"requireDeliveryIds");function Ii(t){if(!Ai.has(t))throw w("decision must be one of immediate, digest, suppress");return t}r(Ii,"requireDecision");function qi(){let t=globalThis.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();let e=new Uint8Array(16);if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let i=0;i<e.length;i+=1)e[i]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}r(qi,"generateRequestId");function on(t){if(t===void 0)return qi();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 w("request id must be a UUID");return t}r(on,"requireRequestId");function N(){return new u("EMPTY_RESPONSE","steward response was empty",502)}r(N,"emptyResponse");var H=class{constructor(e){this.client=e}client;static{r(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw w("a decision reason is required");let s=(await this.graphql(Si,{input:{inboxPath:me(e),deliveryId:bt(e.deliveryId),decision:{decision:Ii(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw N();return{state:s.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(wi,{input:{inboxPath:me(e),deliveryId:bt(e.deliveryId),forward:{requestId:on(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw N();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw w("a message body is required");let i=(await this.graphql(vi,{input:{inboxPath:me(e),requestId:on(e.requestId),body:e.body,deliveryIds:sn(e.deliveryIds)}})).postStewardMessage?.message;if(!i)throw N();return i}async pending(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw w("first must be an integer between 1 and 100");let i={first:n};if(e.after!==void 0&&e.after!=="")i.after=e.after;else{for(let[p,P]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(P!==void 0&&(!Number.isSafeInteger(P)||P<=0))throw w(`${p} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw w("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let o=(await this.graphql(Ti,{inboxPath:me(e),input:i})).viewer?.stewardDigestPending;if(!o||!Array.isArray(o.edges))throw N();let a=o.windowSinceMs??0,l=o.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(l)||a<=0||l<=a)throw N();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 w("a digest run id is required");if((await this.graphql(Ei,{input:{inboxPath:me(e),deliveryIds:sn(e.deliveryIds),digestRunId:n}})).completeStewardBrief?.ok!==!0)throw N();return{ok:!0}}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i||typeof i!="object")throw N();if(i.errors?.length){let s=i.errors.map(l=>l.extensions?.code),o=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=o?ki[o]:void 0;throw new u(o!==void 0&&a!==void 0?o:"GRAPHQL_ERROR",i.errors.map(l=>l.message).filter(l=>typeof l=="string").join("; ")||"GraphQL request failed",a??502,{errors:i.errors})}if(!i.data)throw N();return i.data}};function U(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(U,"isRecord");function f(t){return typeof t=="string"&&t.trim()!==""?t:void 0}r(f,"stringValue");function He(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}r(He,"numberValue");function Je(t){return t===void 0?void 0:t.trim().toUpperCase()}r(Je,"upper");function ln(t){return t.split("_")}r(ln,"pairParts");function xi(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":ln(e)[1]?.toLowerCase()??""}r(xi,"inferInstrumentType");function Di(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}r(Di,"inferUnderlyingType");function an(t,e){let n=f(t.trading_pair)??f(t.tradingPair)??f(t.symbol);if(n===void 0)return;let i=f(t.type),s=ln(n),o=f(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=f(t.market)??f(t.exchange)??s[0]??"",l=f(t.quote)??s[s.length-1]??"",c=f(t.instrument_type)??f(t.instrumentType)??xi(i,n),d=f(t.underlying_type)??f(t.underlyingType)??Di(i);return{symbol:o,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:l,...i===void 0?{}:{type:i},...f(t.description)===void 0?{}:{description:f(t.description)},...He(t.fee_rate)===void 0?He(t.feeRate)===void 0?{}:{feeRate:He(t.feeRate)}:{feeRate:He(t.fee_rate)},...f(t.symbol_icon_url)===void 0?f(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:f(t.symbolIconUrl)}:{symbolIconUrl:f(t.symbol_icon_url)}}}r(an,"normalizeCandidate");function Ni(t){if(!U(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>U(s)?[an(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let s of n){if(!U(s))continue;let o=f(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let l of a)if(!(!U(l)||!Array.isArray(l.pairs)))for(let c of l.pairs){if(!U(c))continue;let d=an({...c,instrument_type:c.instrument_type??l.instrument_type},o);d!==void 0&&i.push(d)}}}return i}r(Ni,"flattenResponse");function Ui(t,e){let n=e.trim();return t.tradingPair===n?!0:Je(t.symbol)===Je(n)}r(Ui,"matchesQuery");function ze(t,e){return e===void 0||Je(t)===Je(e)}r(ze,"matchesFilter");function Fi(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}r(Fi,"dedupe");function Gi(t){let e=U(t)?t:{};return{market:typeof e.market=="string"?e.market:void 0,instrumentType:typeof e.instrumentType=="string"?e.instrumentType:void 0,underlyingType:typeof e.underlyingType=="string"?e.underlyingType:void 0,quote:typeof e.quote=="string"?e.quote:void 0}}r(Gi,"resolveFilters");function Li(t,e){let n=t.split("_"),i=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!s||!o||!a?{symbol:t,...e}:{symbol:o,market:e.market??i,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}r(Li,"pairSearchParams");var z=class{constructor(e){this.client=e}client;static{r(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=U(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new u("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),o=Fi(Ni(s)).filter(l=>Ui(l,i)).filter(l=>ze(l.market,e.market)).filter(l=>ze(l.instrumentType,e.instrumentType)).filter(l=>ze(l.underlyingType,e.underlyingType)).filter(l=>ze(l.quote,e.quote)),a=e.limit;return a!==void 0&&o.length>a?{query:i,candidates:o.slice(0,a),truncated:!0}:{query:i,candidates:o}}async resolve(e){let n=U(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,s=Gi(e),o=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Li(i,s),a=await this.search(o),l=i===void 0?a.candidates:a.candidates.filter(c=>c.tradingPair===i);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 "${i??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,l.length===0?404:409,{query:i??o.symbol,candidateCount:l.length,candidates:l.slice(0,50),...l.length>50?{truncated:!0}:{}});return l[0]}};var Oi=9223372036854775807n,Mi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$i=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,un=new TextEncoder,K=class{constructor(e){this.client=e}client;static{r(this,"ThesesResource")}async create(e){this.client._requireAuth();let n=ji(e);return J(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){return this.client._requireAuth(),Qi(await this.client._request("GET",`/api/v1/theses/${v(e,"id")}`))}async getVersion(e,n){this.client._requireAuth();let i=v(e,"id"),s=v(n,"author_version_id"),o=J(await this.client._request("GET",`/api/v1/theses/${i}/versions/${s}`));if(o.thesis.id!==i||o.thesis.author_version_id!==s)throw m("version response must match the requested thesis and author version");return o}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw y("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw y("cursor must be a string");return Vi(await this.client._request("GET",`/api/v1/theses/${v(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=Bi(n);return J(await this.client._request("PUT",`/api/v1/theses/${v(e,"id")}`,{body:i}))}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw y("params is required");let i=v(e,"id"),s=et(n.visibility),o=J(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:s}}));if(o.thesis.id!==i||o.thesis.visibility!==s)throw m("visibility response must match the requested thesis and visibility");return o}async close(e,n){this.client._requireAuth();let i={expected_author_version_id:v(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(i.note=F(n.note,"note")),J(await this.client._request("POST",`/api/v1/theses/${v(e,"id")}/close`,{body:i}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${v(e,"id")}`);if(n===void 0)return{};if(!k(n)||Object.keys(n).length!==0)throw m("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=Ze(e.body),i=e.mode===void 0?"reformat":Yi(e.mode),s=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:i}});if(!k(s)||typeof s.body!="string")throw m("rewrite response must contain a string body");return{body:pn(s.body)}}};function ji(t){let e={request_id:cn(t.request_id),body:Ze(t.body),title:Pt(t.title??""),entity_ids:dn(t.entity_ids??[],"entity_ids"),visibility:et(t.visibility??"public")};return t.tickers!==void 0&&(e.tickers=Wi(t.tickers)),e}r(ji,"createBody");function Bi(t){return{request_id:cn(t.request_id),expected_author_version_id:v(t.expected_author_version_id,"expected_author_version_id"),body:Ze(t.body),title:Pt(t.title??""),entity_ids:dn(t.entity_ids??[],"entity_ids"),visibility:et(t.visibility),editorial:t.editorial??!1}}r(Bi,"updateBody");function J(t){if(!k(t)||!k(t.thesis))throw m("response must contain thesis");let e=t.thesis;return{thesis:{id:I(e.id,"thesis.id"),author_version_id:I(e.author_version_id,"thesis.author_version_id"),material_version_id:I(e.material_version_id,"thesis.material_version_id"),title:Ki(e.title),body:pn(e.body),entity_ids:Hi(e.entity_ids,"thesis.entity_ids"),visibility:Ji(e.visibility),closed:Xe(e.closed,"thesis.closed"),closing_note:zi(e.closing_note),author_kind:g(e.author_kind,"thesis.author_kind"),author_ref:g(e.author_ref,"thesis.author_ref")}}}r(J,"thesisResponse");function Qi(t){let e=J(t);if(!k(t)||!k(t.author))throw m("response must contain author");let n=t.author,i={id:I(n.id,"author.id"),kind:g(n.kind,"author.kind"),display_name:g(n.display_name,"author.display_name"),avatar_url:g(n.avatar_url,"author.avatar_url"),username:g(n.username,"author.username")};if(!Array.isArray(t.entities))throw m("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw m("entities must match thesis.entity_ids");let s=t.entities.map((o,a)=>{if(!k(o))throw m(`entities[${a}] must be an object`);let l={id:I(o.id,`entities[${a}].id`),ticker:g(o.ticker,`entities[${a}].ticker`),name:g(o.name,`entities[${a}].name`),icon_url:g(o.icon_url,`entities[${a}].icon_url`),kind:g(o.kind,`entities[${a}].kind`)};if(l.id!==e.thesis.entity_ids[a])throw m("entities must preserve thesis.entity_ids order");return l});return{thesis:e.thesis,author:i,entities:s}}r(Qi,"thesisGetResponse");function Vi(t,e,n){if(!k(t)||!k(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw m("invalid Signal history response");let i=t.research,s={state:g(i.state,"research.state"),pending_work:Ke(i.pending_work,"research.pending_work"),read_complete:Xe(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(s.last_attempt_ms=Ke(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(s.last_completed_ms=Ke(i.last_completed_ms,"research.last_completed_ms"));let o=t.entries.map(l=>{if(!k(l)||!k(l.signal)||!k(l.signal.source))throw m("entry must include a Signal and source");let c=l.signal,d=c.source,p=I(c.thesis_id,"signal.thesis_id");if(p!==e)throw m("Signal belongs to another Thesis");let P=_t(l.cursor,"entry.cursor"),S={title:g(d.title,"source.title")};d.url!==void 0&&(S.url=g(d.url,"source.url")),d.published_at_ms!==void 0&&(S.published_at_ms=Ke(d.published_at_ms,"source.published_at_ms"));let q={id:I(c.id,"signal.id"),thesis_id:p,author_version_id:I(c.author_version_id,"signal.author_version_id"),statement_snapshot:_t(c.statement_snapshot,"signal.statement_snapshot"),stance:g(c.stance,"signal.stance"),explanation:g(c.explanation,"signal.explanation"),information_kind:g(c.information_kind,"signal.information_kind"),source:S};if(c.evidence_excerpt!==void 0){if(!k(c.evidence_excerpt))throw m("invalid evidence excerpt");q.evidence_excerpt={text:_t(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:Xe(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:Xe(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:I(l.feed_entry_id,"feed_entry_id"),cursor:P,signal:q}}),a=g(t.next_cursor,"next_cursor");if(a&&a!==o[o.length-1]?.cursor)throw m("next_cursor must match the final entry");return{research:s,entries:o,next_cursor:a}}r(Vi,"thesisSignalsResponse");function Ke(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw m(e+" must be a nonnegative safe integer");return t}r(Ke,"responseNonnegativeInteger");function _t(t,e){let n=g(t,e);if(!n.trim())throw m(e+" must be nonempty");return n}r(_t,"responseNonemptyText");function cn(t){if(!Mi.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw y("request_id must be a non-zero RFC 4122 UUID");return t}r(cn,"requireRequestID");function v(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw y(`${e} must be a positive int64 decimal string`);if(BigInt(t)>Oi)throw y(`${e} must be a positive int64 decimal string`);return t}r(v,"requireID");function dn(t,e){if(!Array.isArray(t))throw y(`${e} must be an array`);if(t.length>20)throw y(`${e} must contain at most 20 IDs`);return t.map((n,i)=>v(n,`${e}[${i}]`))}r(dn,"requireIDs");function Wi(t){if(!Array.isArray(t))throw y("tickers must be an array");if(t.length>100)throw y("tickers must contain at most 100 values");return t.map((e,n)=>{let i=F(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw y(`tickers[${n}] must be non-empty`);return i})}r(Wi,"requireTickers");function Ze(t){let e=F(t,"body");if(e.trim().length===0)throw y("body must not be blank");if(un.encode(e).byteLength>65536)throw y("body must be at most 65536 UTF-8 bytes");return e}r(Ze,"requireBody");function Pt(t){let e=F(t,"title");if(un.encode(e).byteLength>500)throw y("title must be at most 500 UTF-8 bytes");return e}r(Pt,"requireTitle");function et(t){let e=F(t,"visibility");if(e!=="public"&&e!=="private")throw y("visibility must be public or private");return e}r(et,"requireVisibility");function Yi(t){let e=F(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw y("mode must be reformat, shorten, or enrich")}r(Yi,"requireRewriteMode");function F(t,e){if(typeof t!="string")throw y(`${e} must be a string`);if($i.test(t))throw y(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw y(`${e} must not contain NUL`);return t}r(F,"requireText");function I(t,e){if(typeof t=="number")throw m(`${e} must be a decimal string; numeric IDs are unsafe`);try{return v(t,e)}catch{throw m(`${e} must be a positive int64 decimal string`)}}r(I,"responseID");function Hi(t,e){if(!Array.isArray(t))throw m(`${e} must be an array`);if(t.length>20)throw m(`${e} must contain at most 20 IDs`);return t.map((n,i)=>I(n,`${e}[${i}]`))}r(Hi,"responseIDs");function g(t,e){try{return F(t,e)}catch{throw m(`${e} must be valid text`)}}r(g,"responseText");function zi(t){try{return F(t,"note")}catch{throw m("thesis.closing_note must be valid text")}}r(zi,"responseClosingNote");function Xe(t,e){if(typeof t!="boolean")throw m(`${e} must be boolean`);return t}r(Xe,"responseBoolean");function Ji(t){try{return et(t)}catch{throw m("thesis.visibility must be public or private")}}r(Ji,"responseVisibility");function pn(t){try{return Ze(t)}catch{throw m("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}r(pn,"responseBody");function Ki(t){try{return Pt(t)}catch{throw m("response title must be valid text at most 500 UTF-8 bytes")}}r(Ki,"responseTitle");function k(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(k,"isRecord");function y(t){return new u("INVALID_ARGUMENT",t,400)}r(y,"invalidArgument");function m(t){return new u("INVALID_RESPONSE",t,502)}r(m,"invalidResponse");var Xi="https://api-llm.prd.alva.ai",Zi="https://data-tools.prd.space.id";function Rt(t){return typeof t=="object"&&t!==null}r(Rt,"isRecord");function tt(t,e){if(!Rt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}r(tt,"stringField");function er(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let i=tt(t,"code");i&&(e.code=i)}else if(Rt(t)){let i=tt(t,"code"),s=tt(t,"name"),o=tt(t,"message");i&&(e.code=i),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(i=>!!i);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}r(er,"describeCause");function tr(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",n={};t instanceof Error?(n.name=t.name,n.message=t.message):n.message=String(t);let{message:i,details:s}=er(Rt(t)?t.cause:void 0);return s&&(n.cause=s),{message:i?`${e}; cause: ${i}`:e,details:n}}r(tr,"describeFetchFailure");var nt=class{static{r(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_forYou;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_steward;_tradingPairs;_theses;constructor(e){this.baseUrl=e.baseUrl??Xi,this.arraysBaseUrl=e.arraysBaseUrl??Zi,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 _e(this)}get run(){return this._run??=new Pe(this)}get deploy(){return this._deploy??=new Re(this)}get serviceAccount(){return this._serviceAccount??=new ke(this)}get release(){return this._release??=new Se(this)}get feed(){return this._feed??=new ve(this)}get automation(){return this._automation??=new Q(this)}get playbooks(){return this._playbooks??=new Ae(this)}get secrets(){return this._secrets??=new Ce(this)}get sdk(){return this._sdk??=new Ie(this)}get dataSkills(){return this._dataSkills??=new qe(this)}get playbookSkills(){return this._playbookSkills??=new xe(this)}get comments(){return this._comments??=new De(this)}get remix(){return this._remix??=new Ne(this)}get screenshot(){return this._screenshot??=new Ue(this)}get user(){return this._user??=new Fe(this)}get trading(){return this._trading??=new Ge(this)}get portfolio(){return this._portfolio??=new Le(this)}get arraysJwt(){return this._arraysJwt??=new Oe(this)}get notifications(){return this._notifications??=new Me(this)}get notificationPreferences(){return this._notificationPreferences??=new $e(this)}get subscriptions(){return this._subscriptions??=new je(this)}get alerts(){return this._alerts??=new V(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new Be(this)}get feedback(){return this._feedback??=new Qe(this)}get functions(){return this._functions??=new Ve(this)}get credits(){return this._credits??=new We(this)}get markets(){return this._markets??=new W(this)}get tradingPairs(){return this._tradingPairs??=new z(this)}get schedules(){return this._schedules??=new Y(this)}get steward(){return this._steward??=new H(this)}get theses(){return this._theses??=new K(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 B(this)}async _request(e,n,i){let o=`${i?.baseUrl??this.baseUrl}${n}`;if(i?.query){let A=new URLSearchParams;for(let[x,it]of Object.entries(i.query))it!=null&&A.set(x,String(it));let O=A.toString();O&&(o+=`?${O}`)}let a={};i?.noAuth||(this.pbsvToken?(a.Authorization=`Bearer ${this.pbsvToken}`,a["X-Pbsv"]="1"):this.viewer_token?a["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(a["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(a["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(a["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(a["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!i?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let l;i?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",l=i.rawBody):i?.jsonBody!==void 0?(a["Content-Type"]="application/json",l=i.jsonBody):i?.body!==void 0&&(a["Content-Type"]="application/json",l=JSON.stringify(i.body));let c,d=i?.timeoutMs,p=i?.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,S=!1,q,he;P&&d!==void 0&&(p&&(he=r(()=>P.abort(p.reason),"abortListener"),p.addEventListener("abort",he,{once:!0})),q=setTimeout(()=>{S=!0,P.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let kt={method:e,headers:a,body:l,signal:P?.signal??p};d!==void 0&&(kt.timeout=d);try{c=await fetch(o,kt)}catch(A){if(p?.aborted&&!S)throw new u("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(S)throw new u("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let O=tr(A);throw new u("NETWORK_ERROR",O.message,0,{method:e,path:n,...O.details})}finally{he&&p&&p.removeEventListener("abort",he),q!==void 0&&clearTimeout(q)}if(!c.ok){let A="";try{A=await Promise.resolve(c.text())}catch{A=""}if((c.headers.get("content-type")??"").includes("application/json")&&A)try{let x=JSON.parse(A);if(x.error)throw new u(x.error.code??"UNKNOWN",x.error.message??`HTTP ${c.status}`,c.status)}catch(x){if(x instanceof u)throw x}throw new u("UNKNOWN",`HTTP ${c.status}: ${A.slice(0,200)}`,c.status)}if(c.status===204)return;let St=(c.headers.get("content-type")??"").toLowerCase();return St.includes("application/json")||St.includes("+json")?c.json():c.arrayBuffer()}};var nr="0.29.0";ut();return bn(ir);})();
|
|
290
290
|
//# sourceMappingURL=browser.global.js.map
|