@graphysdk/agents-sdk 1.6.2-beta.1782204737314 → 1.7.0-beta.1782310277218
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/dist/index.cjs +1 -1
- package/dist/index.d.ts +103 -8
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("zod");class n extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const r=e=>"progress"===e.type,a=e=>"complete"===e.type,o=e=>"error"===e.type;function i(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class s{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return r(e)}static isCompleteEvent(e){return a(e)}static isErrorEvent(e){return o(e)}stream(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,r);return this.parseSSE(e)})}fetch(t,i,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,u,d;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const z=yield this.makeRequest(t,i,c),y=z.headers.get("content-type");if(null==y?void 0:y.includes("text/event-stream")){try{for(var h,f=!0,b=e.__asyncValues(this.parseSSE(z));!(l=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(r(e)&&s&&s(e),a(e))return e.data;if(o(e)){const r=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${r}ms`,e.error),new n(e.error,{code:e.code,retryable:null!==(d=e.retryable)&&void 0!==d&&d})}}}catch(e){m={error:e}}finally{try{f||l||!(p=b.return)||(yield p.call(b))}finally{if(m)throw m.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${i}ms`),new n("Stream ended without completion")}return yield z.json()}catch(e){const r=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${r}ms`,e),e instanceof n)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,r);return yield e.json()})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new n("Response body is null");const r=t.body.getReader(),a=new TextDecoder;let o="",s="",c="";try{for(;;){const{done:t,value:n}=yield e.__await(r.read());if(t)break;o+=a.decode(n,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const t of l)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))c+=(c?"\n":"")+t.slice(6);else if(""===t.trim()&&c){try{const t=i(s,JSON.parse(c));if(null===t){s="",c="";continue}if(yield yield e.__await(t),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",c)}s="",c=""}}}finally{r.releaseLock()}})}makeRequest(t,r,a){return e.__awaiter(this,arguments,void 0,function*(e,t,r,a=1,o="POST"){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const i=new URL(e,this.baseUrl);if(i.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${a}/${this.retryConfig.attempts}: ${i}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();r&&r.addEventListener("abort",l);try{const c=yield fetch(i,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!c.ok){let i,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(i=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===i)&&(c.status>=500||429===c.status),m=new n(s,{status:c.status,code:i,retryable:l});if(l&&a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${n}ms (attempt ${a+1})`),yield this.sleep(n),this.makeRequest(e,t,r,a+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(i){if(i instanceof n)throw i;if(i instanceof Error&&"AbortError"===i.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),i;if(a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${n}ms`),yield this.sleep(n),this.makeRequest(e,t,r,a+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,i),new n("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",l)}})}makeMultipartRequest(t,r,a){return e.__awaiter(this,arguments,void 0,function*(e,t,r,a=1){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");const i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),c=()=>i.abort();r&&r.addEventListener("abort",c);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:i.signal});if(!s.ok){let o,i=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const c=s.status>=500||429===s.status,l=new n(i,{status:s.status,code:o,retryable:c});if(c&&a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,r,a+1)}throw l}return s}catch(o){if(o instanceof n)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,r,a+1)}throw new n("Network error",{retryable:!0})}finally{clearTimeout(s),r&&r.removeEventListener("abort",c)}})}}const c=t.z.object({inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional(),wallClockMs:t.z.number()}),l=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()}),m=t.z.object({limits:t.z.object({maxWallClockMs:t.z.number().optional(),maxTotalTokens:t.z.number().optional(),maxCostUsd:t.z.number().optional(),trackUsage:t.z.boolean().optional()}),consumed:l,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});t.z.object({inputTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),modelName:t.z.string(),inputCachedTokens:t.z.number().optional(),inputUncachedTokens:t.z.number().optional(),cost:t.z.number().optional(),latencyMs:t.z.number().optional(),effort:t.z.string().optional(),providerReasoning:t.z.string().optional()});const p={usage:c.optional(),budget:m.optional()},u=t.z.enum(["EN_GB","EN_US"]),d=t.z.custom(e=>null!=e&&"object"==typeof e),g=t.z.enum(["low","medium","high"]),h=t.z.enum(["none","low","medium","high"]),f=t.z.enum(["agentic","fast"]),b=3e5,z=5e5,y=t.z.object({maxWallClockMs:t.z.number().positive().max(b).optional(),maxTotalTokens:t.z.number().int().positive().max(z).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),x=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()});t.z.object({limits:y,consumed:x,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});const v=t.z.object({callId:t.z.string().max(256).optional(),locale:u.optional(),effort:g.optional(),storytellingEffort:h.optional().default("low"),budget:y.optional(),executionMode:f.optional(),enforceTableRowCap:t.z.boolean().optional()}),_=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),S=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),w=1e4,T=t.z.enum(["comparison","relationship","distribution","composition"]),E=t.z.object({config:d,userPrompt:t.z.string().max(w).optional().default(""),metadata:v.optional(),chartFamily:T.optional()}),C=E.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),j=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),k=t.z.object({dataPrepPrompt:t.z.string(),chartType:j,summary:t.z.string()}),A=E.extend({userPrompt:t.z.string().max(w),mutationReceipt:_.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),R=t.z.object({response:t.z.object({message:t.z.string()}),config:d,run:S.optional()}).extend(p),$=t.z.object({suggestions:t.z.array(k),run:S.optional()}).extend(p),M=t.z.object({finding:t.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:t.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:t.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:t.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:t.z.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:T.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),O=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(M).describe("Child findings, sorted by quadrant score desc.")}),D=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(O),run:S.optional()}).extend(p);E.extend({mutationReceipt:_.optional()});const P=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:d,run:S.optional()}).extend(p),U=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:d,mutationReceipt:_.optional(),warnings:t.z.array(t.z.string()).optional(),run:S.optional()}).extend(p),I=t.z.enum(["explore","mutate","narrate","annotate"]),B=t.z.object({agent:I,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),G=E.extend({userPrompt:t.z.string().max(w),stages:t.z.array(I).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),F=U.extend({reasoning:t.z.array(B),stories:t.z.array(O).optional()}),X=t.z.enum(["high","medium","low"]),N=t.z.object({confidence:X,needsUserInput:t.z.boolean(),warnings:t.z.array(t.z.string()),cellConfidence:t.z.array(t.z.object({rowIndex:t.z.number().int().nonnegative(),columnKey:t.z.string(),confidence:X,quote:t.z.string().optional()})).optional()}),q=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),L=5e5,K=2097152,H=7340032,W=6291456,Y=8388608,J=W,V=Y,Q=12582912;function Z(e){return 4*Math.ceil(e/3)}const ee=Z(K),te=Z(H),ne=Z(W),re=Z(Y),ae=Z(J),oe=Z(V),ie=Z(Q);function se(e){return e.replace(/\s+/g,"")}function ce(e){const t=se(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const le=/^image\/(png|jpeg|jpg|webp|gif)$/i,me=t.z.object({mimeType:t.z.string().min(1).refine(e=>le.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(ee).refine(ce,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),pe=t.z.enum(["image","document","spreadsheet"]),ue=me.extend({kind:t.z.literal("image")}),de=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(ne).refine(ce,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ge=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(ae).refine(ce,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),he=t.z.discriminatedUnion("kind",[ue,de,ge]),fe=t.z.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),be=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),kind:pe,mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().positive(),expiresAt:t.z.string().datetime()}),ze=t.z.object({sourceText:t.z.string().max(L).default(""),images:t.z.array(me).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(he).max(12).optional(),attachmentRefs:t.z.array(fe).max(12).optional(),metadata:v.optional()}).superRefine((e,t)=>{var n,r,a;const o=e.sourceText.trim(),i=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(r=e.attachments)&&void 0!==r?r:[],c=null!==(a=e.attachmentRefs)&&void 0!==a?a:[];if(i.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(c.length>0&&s.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or inline `attachments`, not both.",path:["attachmentRefs"]});if(c.length>0&&i.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or deprecated `images`, not both.",path:["attachmentRefs"]});if(0===o.length&&0===i.length&&0===s.length&&0===c.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(c.length>0)return;if(i.length>0){i.reduce((e,t)=>e+se(t.dataBase64).length,0)>te&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let l=0,m=0,p=0,u=0,d=0,g=0,h=0;for(const e of s){const t=se(e.dataBase64).length;switch(h+=t,e.kind){case"image":l+=1,u+=t;break;case"document":m+=1,d+=t;break;case"spreadsheet":p+=1,g+=t}}l>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),p>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&p<=2;s.length>0&&f&&(u>te&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>re&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>oe&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>ie&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const ye=t.z.object({response:t.z.object({message:t.z.string()}),config:d,extractMeta:N.nullable(),lastAccuracyEvaluation:q.optional(),run:S.optional()}).extend(p),xe=t.z.object({config:d,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:S.optional()}).extend(p),ve=$,_e=t.z.enum(["deal-breaker","pro","con","family","continuity"]),Se=t.z.object({kind:_e,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),we=t.z.enum(["ok","disqualified"]),Te=t.z.object({rank:t.z.number().int().positive(),type:j,score:t.z.number(),verdict:we,factors:t.z.array(Se)}),Ee=t.z.object({config:d,chartFamily:T.optional(),metadata:v.optional()}),Ce=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),je=t.z.object({kind:Ce,message:t.z.string()}),ke=t.z.enum(["sum","avg","count","min","max"]),Ae=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:ke,chartType:j,score:t.z.number(),message:t.z.string()}),Re=t.z.object({ranking:t.z.array(Te),observations:t.z.array(je).optional().default([]),suggestions:t.z.array(Ae).optional().default([]),run:S.optional()}),$e=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),Me=t.z.object({config:d.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:$e.optional(),userPrompt:t.z.string().optional(),metadata:v.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Oe=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),De=t.z.enum(["info","low","medium","high"]),Pe=t.z.object({category:Oe,severity:De,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),Ue=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Pe)}),Ie=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),Be=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),Ge=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:Ue.nullable(),chartVisionAudit:Be.nullable().optional().default(null),rubricScores:Ie.nullable().optional().default(null),run:S.optional()}).extend(p),Fe="/api/v0";exports.AggregationFunctionSchema=ke,exports.AggregationSuggestionSchema=Ae,exports.AiChartTypeEnum=j,exports.AttachmentUploadResponseSchema=be,exports.ChartCritiqueIssueCategorySchema=Oe,exports.ChartCritiqueIssueSchema=Pe,exports.ChartCritiqueIssueSeveritySchema=De,exports.ChartCritiqueReportSchema=Ue,exports.ChartFamilySchema=T,exports.ChartFitEntrySchema=Te,exports.ChartFitFactorKindSchema=_e,exports.ChartFitFactorSchema=Se,exports.ChartFitVerdictSchema=we,exports.ChartJudgeRubricSchema=$e,exports.DataObservationKindSchema=Ce,exports.DataObservationSchema=je,exports.EvaluateParamsSchema=Ee,exports.EvaluateResponseSchema=Re,exports.ExecutionModeSchema=f,exports.ExploreFindingSchema=M,exports.ExploreStorySchema=O,exports.ExtractAccuracyEvaluationSchema=q,exports.ExtractAttachmentInputSchema=he,exports.ExtractAttachmentKindSchema=pe,exports.ExtractConfidenceSchema=X,exports.ExtractFromProseParamsSchema=ze,exports.ExtractFromProseResponseSchema=ye,exports.ExtractMetaSchema=N,exports.GenerateAnnotationsResponseSchema=P,exports.GenerateExplorationResponseSchema=D,exports.GenerateGraphResponseSchema=xe,exports.GenerateGraphSuggestionsResponseSchema=ve,exports.GenerateMutationResponseSchema=U,exports.GenerateNarrativeParamsSchema=A,exports.GenerateNarrativeResponseSchema=R,exports.GeneratePipelineParamsSchema=G,exports.GeneratePipelineResponseSchema=F,exports.GenerateSuggestionsParamsSchema=C,exports.GenerateSuggestionsResponseSchema=$,exports.GraphGenerationRequestSchema=E,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,o=e.__rest(t,["storytellingOptions"]),i=yield this.client.fetch(`${Fe}/generate`,o,n,r),s=xe.parse(i);return this.stripStorytelling(s,a)})}generateGraphStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:r}=t,a=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${Fe}/generate`,a,n);return this.wrapStreamWithStorytellingStripping(o,r)})}generateNarrative(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/narrate`,t,n,r);return R.parse(e)})}generateNarrativeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/narrate`,t,n)})}generateSuggestions(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/suggestions`,t,n,r);return $.parse(e)})}generateSuggestionsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/suggestions`,t,n)})}generateExploration(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/explore`,t,n,r);return D.parse(e)})}generateExplorationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/explore`,t,n)})}generateAnnotations(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/annotate`,t,n,r);return P.parse(e)})}generateAnnotationsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/annotate`,t,n)})}generateMutation(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/mutate`,t,n,r);return U.parse(e)})}generateMutationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/mutate`,t,n)})}generatePipeline(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/pipeline`,t,n,r);return F.parse(e)})}generatePipelineStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/pipeline`,t,n)})}evaluate(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/evaluate`,t,void 0,n);return Re.parse(e)})}judge(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/judge`,t,void 0,n);return Ge.parse(e)})}judgeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/judge`,t,n)})}extractFromProse(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/extract`,t,n,r);return ye.parse(e)})}extractFromProseStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/extract`,t,n)})}uploadAttachment(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=new FormData,a=null==n?void 0:n.filename;"undefined"!=typeof File&&t instanceof File?e.append("file",t):a?e.append("file",t,a):e.append("file",t,"upload"),a&&e.append("filename",a);const o=yield this.client.uploadMultipart(`${Fe}/attachments`,e,r);return be.parse(o)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,n){return e.__asyncGenerator(this,arguments,function*(){var r,o,i,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(r=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(a(t)){const r=this.stripStorytelling(t.data,n);yield yield e.__await(Object.assign(Object.assign({},t),{data:r}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||r||!(i=m.return)||(yield e.__await(i.call(m)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=n,exports.InvocationBudgetSchema=y,exports.InvocationEffortSchema=g,exports.JudgeParamsSchema=Me,exports.JudgeResponseSchema=Ge,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=z,exports.MAX_BUDGET_WALL_CLOCK_MS=b,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=Q,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=Y,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=W,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=H,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=K,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=V,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=J,exports.MAX_SOURCE_TEXT_LENGTH=L,exports.MAX_USER_PROMPT_LENGTH=w,exports.MetadataSchema=v,exports.MutateNarrationReceiptSchema=_,exports.PipelineAgentNameSchema=I,exports.PipelineStageReasoningSchema=B,exports.RubricScoresSchema=Ie,exports.RunContextSchema=S,exports.StorytellingEffortSchema=h,exports.SuggestionSchema=k,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:se(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:se(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:se(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isAgentCompleteEvent=e=>"agent_complete"===e.type,exports.isCompleteEvent=a,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof n,exports.isLlmStepEvent=e=>"llm_step"===e.type,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=r,exports.isReasoningEvent=e=>"reasoning"===e.type,exports.isSessionBudgetEvent=e=>"session_budget"===e.type,exports.isToolCallEvent=e=>"tool_call"===e.type,exports.isToolCompleteEvent=e=>"tool_complete"===e.type,exports.isToolErrorEvent=e=>"tool_error"===e.type;
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("zod");class n extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const r=e=>"progress"===e.type,a=e=>"complete"===e.type,o=e=>"error"===e.type;function i(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class s{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return r(e)}static isCompleteEvent(e){return a(e)}static isErrorEvent(e){return o(e)}stream(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,r);return this.parseSSE(e)})}fetch(t,i,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,u,d;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const y=yield this.makeRequest(t,i,c),z=y.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var h,f=!0,b=e.__asyncValues(this.parseSSE(y));!(l=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(r(e)&&s&&s(e),a(e))return e.data;if(o(e)){const r=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${r}ms`,e.error),new n(e.error,{code:e.code,retryable:null!==(d=e.retryable)&&void 0!==d&&d})}}}catch(e){m={error:e}}finally{try{f||l||!(p=b.return)||(yield p.call(b))}finally{if(m)throw m.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${i}ms`),new n("Stream ended without completion")}return yield y.json()}catch(e){const r=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${r}ms`,e),e instanceof n)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,r);return yield e.json()})}get(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,void 0,n,1,"GET");return yield e.json()})}postJson(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,r,1,"POST");return yield e.json()})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new n("Response body is null");const r=t.body.getReader(),a=new TextDecoder;let o="",s="",c="";try{for(;;){const{done:t,value:n}=yield e.__await(r.read());if(t)break;o+=a.decode(n,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const t of l)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))c+=(c?"\n":"")+t.slice(6);else if(""===t.trim()&&c){try{const t=i(s,JSON.parse(c));if(null===t){s="",c="";continue}if(yield yield e.__await(t),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",c)}s="",c=""}}}finally{r.releaseLock()}})}makeRequest(t,r,a){return e.__awaiter(this,arguments,void 0,function*(e,t,r,a=1,o="POST"){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const i=new URL(e,this.baseUrl);if(i.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${a}/${this.retryConfig.attempts}: ${i}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();r&&r.addEventListener("abort",l);try{const c=yield fetch(i,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!c.ok){let i,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(i=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===i)&&(c.status>=500||429===c.status),m=new n(s,{status:c.status,code:i,retryable:l});if(l&&a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${n}ms (attempt ${a+1})`),yield this.sleep(n),this.makeRequest(e,t,r,a+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(i){if(i instanceof n)throw i;if(i instanceof Error&&"AbortError"===i.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),i;if(a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${n}ms`),yield this.sleep(n),this.makeRequest(e,t,r,a+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,i),new n("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",l)}})}makeMultipartRequest(t,r,a){return e.__awaiter(this,arguments,void 0,function*(e,t,r,a=1){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");const i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),c=()=>i.abort();r&&r.addEventListener("abort",c);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:i.signal});if(!s.ok){let o,i=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const c=s.status>=500||429===s.status,l=new n(i,{status:s.status,code:o,retryable:c});if(c&&a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,r,a+1)}throw l}return s}catch(o){if(o instanceof n)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,r,a+1)}throw new n("Network error",{retryable:!0})}finally{clearTimeout(s),r&&r.removeEventListener("abort",c)}})}}const c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function l(e,t){var n;const r=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return r||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function m(e,t){var n;const r=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(r)return r;const a=e.type.trim();if(a.length>0)return a;const o=l(e,t);if(o){const e=function(e){const t=e.lastIndexOf(".");if(t<0)return;const n=e.slice(t).toLowerCase();return c[n]}(o);if(e)return e}throw new Error("uploadAttachment requires a MIME type: set `file.type`, pass `options.mimeType`, or use a filename with a supported extension (.png, .jpg, .pdf, .xlsx, …)")}const p=t.z.object({inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional(),wallClockMs:t.z.number()}),u=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()}),d=t.z.object({limits:t.z.object({maxWallClockMs:t.z.number().optional(),maxTotalTokens:t.z.number().optional(),maxCostUsd:t.z.number().optional(),trackUsage:t.z.boolean().optional()}),consumed:u,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});t.z.object({inputTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),modelName:t.z.string(),inputCachedTokens:t.z.number().optional(),inputUncachedTokens:t.z.number().optional(),cost:t.z.number().optional(),latencyMs:t.z.number().optional(),effort:t.z.string().optional(),providerReasoning:t.z.string().optional()});const g={usage:p.optional(),budget:d.optional()},h=t.z.enum(["EN_GB","EN_US"]),f=t.z.custom(e=>null!=e&&"object"==typeof e),b=t.z.enum(["low","medium","high"]),y=t.z.enum(["none","low","medium","high"]),z=t.z.enum(["agentic","fast"]),x=3e5,v=5e5,_=t.z.object({maxWallClockMs:t.z.number().positive().max(x).optional(),maxTotalTokens:t.z.number().int().positive().max(v).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),w=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()});t.z.object({limits:_,consumed:w,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});const S=t.z.object({callId:t.z.string().max(256).optional(),locale:h.optional(),effort:b.optional(),storytellingEffort:y.optional().default("low"),budget:_.optional(),executionMode:z.optional(),enforceTableRowCap:t.z.boolean().optional()}),T=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),E=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),C=1e4,j=t.z.enum(["comparison","relationship","distribution","composition"]),A=t.z.object({config:f,userPrompt:t.z.string().max(C).optional().default(""),metadata:S.optional(),chartFamily:j.optional()}),k=A.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),R=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),$=t.z.object({dataPrepPrompt:t.z.string(),chartType:R,summary:t.z.string()}),M=A.extend({userPrompt:t.z.string().max(C),mutationReceipt:T.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),O=t.z.object({response:t.z.object({message:t.z.string()}),config:f,run:E.optional()}).extend(g),U=t.z.object({suggestions:t.z.array($),run:E.optional()}).extend(g),P=t.z.object({finding:t.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:t.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:t.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:t.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:t.z.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:j.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),D=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(P).describe("Child findings, sorted by quadrant score desc.")}),I=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(D),run:E.optional()}).extend(g);A.extend({mutationReceipt:T.optional()});const B=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:f,run:E.optional()}).extend(g),G=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:f,mutationReceipt:T.optional(),warnings:t.z.array(t.z.string()).optional(),run:E.optional()}).extend(g),F=t.z.enum(["explore","mutate","narrate","annotate"]),X=t.z.object({agent:F,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),q=A.extend({userPrompt:t.z.string().max(C),stages:t.z.array(F).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),N=G.extend({reasoning:t.z.array(X),stories:t.z.array(D).optional()}),L=t.z.enum(["high","medium","low"]),K=t.z.object({confidence:L,needsUserInput:t.z.boolean(),warnings:t.z.array(t.z.string()),cellConfidence:t.z.array(t.z.object({rowIndex:t.z.number().int().nonnegative(),columnKey:t.z.string(),confidence:L,quote:t.z.string().optional()})).optional()}),H=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),W=5e5,Y=2097152,J=7340032,V=6291456,Q=8388608,Z=V,ee=Q,te=12582912,ne=12,re=52428800;function ae(e){return 4*Math.ceil(e/3)}const oe=ae(Y),ie=ae(J),se=ae(V),ce=ae(Q),le=ae(Z),me=ae(ee),pe=ae(te);function ue(e){return e.replace(/\s+/g,"")}function de(e){const t=ue(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const ge=/^image\/(png|jpeg|jpg|webp|gif)$/i,he=t.z.object({mimeType:t.z.string().min(1).refine(e=>ge.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(oe).refine(de,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),fe=t.z.enum(["image","document","spreadsheet"]),be=he.extend({kind:t.z.literal("image")}),ye=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(se).refine(de,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ze=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(le).refine(de,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),xe=t.z.discriminatedUnion("kind",[be,ye,ze]),ve=t.z.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),_e=t.z.enum(["pending","ready","failed"]),we=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),status:_e,kind:fe.optional(),mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().nonnegative(),uploadExpiresAt:t.z.string().datetime().optional(),completedAt:t.z.string().datetime().optional(),expiresAt:t.z.string().datetime()}),Se=we.extend({status:t.z.literal("ready"),kind:fe,sizeBytes:t.z.number().int().positive()}),Te=t.z.object({mimeType:t.z.string().min(1),filename:t.z.string().max(512).optional(),sizeBytes:t.z.number().int().positive().max(re).optional()}),Ee=t.z.object({files:t.z.array(Te).min(1).max(ne)}),Ce=we.extend({status:t.z.literal("pending"),uploadUrl:t.z.string().url()}),je=t.z.object({uploads:t.z.array(Ce)}),Ae=t.z.object({sourceText:t.z.string().max(W).default(""),images:t.z.array(he).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(xe).max(ne).optional(),attachmentRefs:t.z.array(ve).max(ne).optional(),metadata:S.optional()}).superRefine((e,t)=>{var n,r,a;const o=e.sourceText.trim(),i=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(r=e.attachments)&&void 0!==r?r:[],c=null!==(a=e.attachmentRefs)&&void 0!==a?a:[];if(i.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===o.length&&0===i.length&&0===s.length&&0===c.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(i.length+s.length+c.length>ne)return void t.addIssue({code:"custom",message:"Too many attachments (max 12 across inline payloads and attachmentRefs)",path:["attachmentRefs"]});if(c.length>0&&0===s.length&&0===i.length)return;if(i.length>0){i.reduce((e,t)=>e+ue(t.dataBase64).length,0)>ie&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let l=0,m=0,p=0,u=0,d=0,g=0,h=0;for(const e of s){const t=ue(e.dataBase64).length;switch(h+=t,e.kind){case"image":l+=1,u+=t;break;case"document":m+=1,d+=t;break;case"spreadsheet":p+=1,g+=t}}l>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),p>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&p<=2;s.length>0&&f&&(u>ie&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ce&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>me&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>pe&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const ke=t.z.object({response:t.z.object({message:t.z.string()}),config:f,extractMeta:K.nullable(),lastAccuracyEvaluation:H.optional(),run:E.optional()}).extend(g),Re=t.z.object({config:f,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:E.optional()}).extend(g),$e=U,Me=t.z.enum(["deal-breaker","pro","con","family","continuity"]),Oe=t.z.object({kind:Me,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),Ue=t.z.enum(["ok","disqualified"]),Pe=t.z.object({rank:t.z.number().int().positive(),type:R,score:t.z.number(),verdict:Ue,factors:t.z.array(Oe)}),De=t.z.object({config:f,chartFamily:j.optional(),metadata:S.optional()}),Ie=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),Be=t.z.object({kind:Ie,message:t.z.string()}),Ge=t.z.enum(["sum","avg","count","min","max"]),Fe=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:Ge,chartType:R,score:t.z.number(),message:t.z.string()}),Xe=t.z.object({ranking:t.z.array(Pe),observations:t.z.array(Be).optional().default([]),suggestions:t.z.array(Fe).optional().default([]),run:E.optional()}),qe=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),Ne=t.z.object({config:f.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:qe.optional(),userPrompt:t.z.string().optional(),metadata:S.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Le=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Ke=t.z.enum(["info","low","medium","high"]),He=t.z.object({category:Le,severity:Ke,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),We=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(He)}),Ye=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),Je=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),Ve=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:We.nullable(),chartVisionAudit:Je.nullable().optional().default(null),rubricScores:Ye.nullable().optional().default(null),run:E.optional()}).extend(g),Qe="/api/v0";exports.AggregationFunctionSchema=Ge,exports.AggregationSuggestionSchema=Fe,exports.AiChartTypeEnum=R,exports.AttachmentResponseSchema=we,exports.AttachmentUploadResponseSchema=Se,exports.AttachmentUploadSlotResponseSchema=Ce,exports.ChartCritiqueIssueCategorySchema=Le,exports.ChartCritiqueIssueSchema=He,exports.ChartCritiqueIssueSeveritySchema=Ke,exports.ChartCritiqueReportSchema=We,exports.ChartFamilySchema=j,exports.ChartFitEntrySchema=Pe,exports.ChartFitFactorKindSchema=Me,exports.ChartFitFactorSchema=Oe,exports.ChartFitVerdictSchema=Ue,exports.ChartJudgeRubricSchema=qe,exports.CreateAttachmentUploadsParamsSchema=Ee,exports.CreateAttachmentUploadsResponseSchema=je,exports.DataObservationKindSchema=Ie,exports.DataObservationSchema=Be,exports.EvaluateParamsSchema=De,exports.EvaluateResponseSchema=Xe,exports.ExecutionModeSchema=z,exports.ExploreFindingSchema=P,exports.ExploreStorySchema=D,exports.ExtractAccuracyEvaluationSchema=H,exports.ExtractAttachmentInputSchema=xe,exports.ExtractAttachmentKindSchema=fe,exports.ExtractConfidenceSchema=L,exports.ExtractFromProseParamsSchema=Ae,exports.ExtractFromProseResponseSchema=ke,exports.ExtractMetaSchema=K,exports.GenerateAnnotationsResponseSchema=B,exports.GenerateExplorationResponseSchema=I,exports.GenerateGraphResponseSchema=Re,exports.GenerateGraphSuggestionsResponseSchema=$e,exports.GenerateMutationResponseSchema=G,exports.GenerateNarrativeParamsSchema=M,exports.GenerateNarrativeResponseSchema=O,exports.GeneratePipelineParamsSchema=q,exports.GeneratePipelineResponseSchema=N,exports.GenerateSuggestionsParamsSchema=k,exports.GenerateSuggestionsResponseSchema=U,exports.GraphGenerationRequestSchema=A,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,o=e.__rest(t,["storytellingOptions"]),i=yield this.client.fetch(`${Qe}/generate`,o,n,r),s=Re.parse(i);return this.stripStorytelling(s,a)})}generateGraphStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:r}=t,a=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${Qe}/generate`,a,n);return this.wrapStreamWithStorytellingStripping(o,r)})}generateNarrative(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/narrate`,t,n,r);return O.parse(e)})}generateNarrativeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/narrate`,t,n)})}generateSuggestions(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/suggestions`,t,n,r);return U.parse(e)})}generateSuggestionsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/suggestions`,t,n)})}generateExploration(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/explore`,t,n,r);return I.parse(e)})}generateExplorationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/explore`,t,n)})}generateAnnotations(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/annotate`,t,n,r);return B.parse(e)})}generateAnnotationsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/annotate`,t,n)})}generateMutation(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/mutate`,t,n,r);return G.parse(e)})}generateMutationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/mutate`,t,n)})}generatePipeline(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/pipeline`,t,n,r);return N.parse(e)})}generatePipelineStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/pipeline`,t,n)})}evaluate(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/evaluate`,t,void 0,n);return Xe.parse(e)})}judge(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/judge`,t,void 0,n);return Ve.parse(e)})}judgeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/judge`,t,n)})}extractFromProse(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/extract`,t,n,r);return ke.parse(e)})}extractFromProseStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/extract`,t,n)})}uploadAttachment(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=m(t,r),o=l(t,r),{uploads:i}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},o?{filename:o}:{}),t.size>0?{sizeBytes:t.size}:{})]},a),s=i[0];if(!s)throw new n("Attachment upload slot was not returned");const c=yield fetch(s.uploadUrl,{method:"PUT",headers:{"Content-Type":e},body:t,signal:a});if(!c.ok)throw new n(`Attachment upload failed (HTTP ${c.status})`,{status:c.status,retryable:c.status>=500});const p=yield this.completeAttachmentUpload(s.id,a);return Se.parse(p)})}createAttachmentUploads(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Qe}/attachment-uploads`,t,n);return je.parse(e)})}completeAttachmentUpload(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Qe}/attachments/${t}/complete`,{},n);return we.parse(e)})}getAttachment(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.get(`${Qe}/attachments/${t}`,n);return we.parse(e)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,n){return e.__asyncGenerator(this,arguments,function*(){var r,o,i,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(r=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(a(t)){const r=this.stripStorytelling(t.data,n);yield yield e.__await(Object.assign(Object.assign({},t),{data:r}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||r||!(i=m.return)||(yield e.__await(i.call(m)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=n,exports.InvocationBudgetSchema=_,exports.InvocationEffortSchema=b,exports.JudgeParamsSchema=Ne,exports.JudgeResponseSchema=Ve,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=v,exports.MAX_BUDGET_WALL_CLOCK_MS=x,exports.MAX_EXTRACT_ATTACHMENTS=ne,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=te,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=Q,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=V,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=J,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=Y,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=ee,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=Z,exports.MAX_SOURCE_TEXT_LENGTH=W,exports.MAX_STAGED_FILE_BYTES=re,exports.MAX_USER_PROMPT_LENGTH=C,exports.MetadataSchema=S,exports.MutateNarrationReceiptSchema=T,exports.PipelineAgentNameSchema=F,exports.PipelineStageReasoningSchema=X,exports.RubricScoresSchema=Ye,exports.RunContextSchema=E,exports.StorytellingEffortSchema=y,exports.SuggestionSchema=$,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ue(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ue(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ue(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isAgentCompleteEvent=e=>"agent_complete"===e.type,exports.isCompleteEvent=a,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof n,exports.isLlmStepEvent=e=>"llm_step"===e.type,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=r,exports.isReasoningEvent=e=>"reasoning"===e.type,exports.isSessionBudgetEvent=e=>"session_budget"===e.type,exports.isToolCallEvent=e=>"tool_call"===e.type,exports.isToolCompleteEvent=e=>"tool_complete"===e.type,exports.isToolErrorEvent=e=>"tool_error"===e.type;
|
package/dist/index.d.ts
CHANGED
|
@@ -395,6 +395,16 @@ declare const isToolCallEvent: <T>(event: SSEEvent<T>) => event is ToolCallEvent
|
|
|
395
395
|
declare const isToolCompleteEvent: <T>(event: SSEEvent<T>) => event is ToolCompleteEvent;
|
|
396
396
|
declare const isToolErrorEvent: <T>(event: SSEEvent<T>) => event is ToolErrorEvent;
|
|
397
397
|
|
|
398
|
+
type UploadAttachmentOptions = {
|
|
399
|
+
/** Display name hint (especially for spreadsheets). */
|
|
400
|
+
filename?: string;
|
|
401
|
+
/**
|
|
402
|
+
* MIME type for the presigned upload slot. Required when `file.type` is empty and the
|
|
403
|
+
* filename has no recognized extension.
|
|
404
|
+
*/
|
|
405
|
+
mimeType?: string;
|
|
406
|
+
};
|
|
407
|
+
|
|
398
408
|
declare const InvocationEffortSchema: z.ZodEnum<{
|
|
399
409
|
low: "low";
|
|
400
410
|
medium: "medium";
|
|
@@ -1358,6 +1368,7 @@ declare const MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES: number;
|
|
|
1358
1368
|
declare const MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES: number;
|
|
1359
1369
|
/** Max entries in `attachments[]` (images + PDFs + spreadsheets). Mirrors agents-api. */
|
|
1360
1370
|
declare const MAX_EXTRACT_ATTACHMENTS: number;
|
|
1371
|
+
declare const MAX_STAGED_FILE_BYTES: number;
|
|
1361
1372
|
declare const extractImagePartSchema: z.ZodObject<{
|
|
1362
1373
|
mimeType: z.ZodString;
|
|
1363
1374
|
dataBase64: z.ZodString;
|
|
@@ -1384,20 +1395,91 @@ declare const ExtractAttachmentInputSchema: z.ZodDiscriminatedUnion<[z.ZodObject
|
|
|
1384
1395
|
filename: z.ZodOptional<z.ZodString>;
|
|
1385
1396
|
}, z.core.$strip>], "kind">;
|
|
1386
1397
|
type ExtractAttachmentInput = z.infer<typeof ExtractAttachmentInputSchema>;
|
|
1398
|
+
declare const AttachmentResponseSchema: z.ZodObject<{
|
|
1399
|
+
id: z.ZodString;
|
|
1400
|
+
uri: z.ZodString;
|
|
1401
|
+
status: z.ZodEnum<{
|
|
1402
|
+
pending: "pending";
|
|
1403
|
+
ready: "ready";
|
|
1404
|
+
failed: "failed";
|
|
1405
|
+
}>;
|
|
1406
|
+
kind: z.ZodOptional<z.ZodEnum<{
|
|
1407
|
+
image: "image";
|
|
1408
|
+
document: "document";
|
|
1409
|
+
spreadsheet: "spreadsheet";
|
|
1410
|
+
}>>;
|
|
1411
|
+
mimeType: z.ZodString;
|
|
1412
|
+
filename: z.ZodOptional<z.ZodString>;
|
|
1413
|
+
sizeBytes: z.ZodNumber;
|
|
1414
|
+
uploadExpiresAt: z.ZodOptional<z.ZodString>;
|
|
1415
|
+
completedAt: z.ZodOptional<z.ZodString>;
|
|
1416
|
+
expiresAt: z.ZodString;
|
|
1417
|
+
}, z.core.$strip>;
|
|
1418
|
+
type AttachmentResponse = z.infer<typeof AttachmentResponseSchema>;
|
|
1419
|
+
/** Multipart upload response (`POST /v0/attachments`). */
|
|
1387
1420
|
declare const AttachmentUploadResponseSchema: z.ZodObject<{
|
|
1388
1421
|
id: z.ZodString;
|
|
1389
1422
|
uri: z.ZodString;
|
|
1423
|
+
mimeType: z.ZodString;
|
|
1424
|
+
filename: z.ZodOptional<z.ZodString>;
|
|
1425
|
+
uploadExpiresAt: z.ZodOptional<z.ZodString>;
|
|
1426
|
+
completedAt: z.ZodOptional<z.ZodString>;
|
|
1427
|
+
expiresAt: z.ZodString;
|
|
1428
|
+
status: z.ZodLiteral<"ready">;
|
|
1390
1429
|
kind: z.ZodEnum<{
|
|
1391
1430
|
image: "image";
|
|
1392
1431
|
document: "document";
|
|
1393
1432
|
spreadsheet: "spreadsheet";
|
|
1394
1433
|
}>;
|
|
1434
|
+
sizeBytes: z.ZodNumber;
|
|
1435
|
+
}, z.core.$strip>;
|
|
1436
|
+
type AttachmentUploadResponse = z.infer<typeof AttachmentUploadResponseSchema>;
|
|
1437
|
+
declare const CreateAttachmentUploadsParamsSchema: z.ZodObject<{
|
|
1438
|
+
files: z.ZodArray<z.ZodObject<{
|
|
1439
|
+
mimeType: z.ZodString;
|
|
1440
|
+
filename: z.ZodOptional<z.ZodString>;
|
|
1441
|
+
sizeBytes: z.ZodOptional<z.ZodNumber>;
|
|
1442
|
+
}, z.core.$strip>>;
|
|
1443
|
+
}, z.core.$strip>;
|
|
1444
|
+
type CreateAttachmentUploadsParams = z.infer<typeof CreateAttachmentUploadsParamsSchema>;
|
|
1445
|
+
declare const AttachmentUploadSlotResponseSchema: z.ZodObject<{
|
|
1446
|
+
id: z.ZodString;
|
|
1447
|
+
uri: z.ZodString;
|
|
1448
|
+
kind: z.ZodOptional<z.ZodEnum<{
|
|
1449
|
+
image: "image";
|
|
1450
|
+
document: "document";
|
|
1451
|
+
spreadsheet: "spreadsheet";
|
|
1452
|
+
}>>;
|
|
1395
1453
|
mimeType: z.ZodString;
|
|
1396
1454
|
filename: z.ZodOptional<z.ZodString>;
|
|
1397
1455
|
sizeBytes: z.ZodNumber;
|
|
1456
|
+
uploadExpiresAt: z.ZodOptional<z.ZodString>;
|
|
1457
|
+
completedAt: z.ZodOptional<z.ZodString>;
|
|
1398
1458
|
expiresAt: z.ZodString;
|
|
1459
|
+
status: z.ZodLiteral<"pending">;
|
|
1460
|
+
uploadUrl: z.ZodString;
|
|
1399
1461
|
}, z.core.$strip>;
|
|
1400
|
-
type
|
|
1462
|
+
type AttachmentUploadSlotResponse = z.infer<typeof AttachmentUploadSlotResponseSchema>;
|
|
1463
|
+
declare const CreateAttachmentUploadsResponseSchema: z.ZodObject<{
|
|
1464
|
+
uploads: z.ZodArray<z.ZodObject<{
|
|
1465
|
+
id: z.ZodString;
|
|
1466
|
+
uri: z.ZodString;
|
|
1467
|
+
kind: z.ZodOptional<z.ZodEnum<{
|
|
1468
|
+
image: "image";
|
|
1469
|
+
document: "document";
|
|
1470
|
+
spreadsheet: "spreadsheet";
|
|
1471
|
+
}>>;
|
|
1472
|
+
mimeType: z.ZodString;
|
|
1473
|
+
filename: z.ZodOptional<z.ZodString>;
|
|
1474
|
+
sizeBytes: z.ZodNumber;
|
|
1475
|
+
uploadExpiresAt: z.ZodOptional<z.ZodString>;
|
|
1476
|
+
completedAt: z.ZodOptional<z.ZodString>;
|
|
1477
|
+
expiresAt: z.ZodString;
|
|
1478
|
+
status: z.ZodLiteral<"pending">;
|
|
1479
|
+
uploadUrl: z.ZodString;
|
|
1480
|
+
}, z.core.$strip>>;
|
|
1481
|
+
}, z.core.$strip>;
|
|
1482
|
+
type CreateAttachmentUploadsResponse = z.infer<typeof CreateAttachmentUploadsResponseSchema>;
|
|
1401
1483
|
/**
|
|
1402
1484
|
* Request body for `POST /v0/extract`. Mirrors `ExtractFromProseRequestSchema` in agents-api.
|
|
1403
1485
|
*
|
|
@@ -3477,19 +3559,32 @@ declare class GraphyAiSdk {
|
|
|
3477
3559
|
} | undefined;
|
|
3478
3560
|
}>>>;
|
|
3479
3561
|
/**
|
|
3480
|
-
* Uploads a file to the staged attachment store
|
|
3562
|
+
* Uploads a file to the staged attachment store via the presigned flow
|
|
3563
|
+
* (`POST /v0/attachment-uploads` → PUT `uploadUrl` → `POST /v0/attachments/{id}/complete`).
|
|
3481
3564
|
*
|
|
3482
3565
|
* @param file - File or Blob to upload (browser `File` or Node `Blob`).
|
|
3483
|
-
* @param options - Optional filename
|
|
3566
|
+
* @param options - Optional filename and mimeType overrides when `file` lacks metadata.
|
|
3484
3567
|
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
3485
3568
|
* @returns Staged attachment metadata including `graphy://attachments/{id}` URI.
|
|
3486
3569
|
*/
|
|
3487
|
-
uploadAttachment(file: Blob, options?:
|
|
3488
|
-
|
|
3489
|
-
|
|
3570
|
+
uploadAttachment(file: Blob, options?: UploadAttachmentOptions, signal?: AbortSignal): Promise<AttachmentUploadResponse>;
|
|
3571
|
+
/**
|
|
3572
|
+
* Mints presigned upload slots (`POST /v0/attachment-uploads`).
|
|
3573
|
+
*
|
|
3574
|
+
* @returns Pending upload slots with `uploadUrl`, `uri`, and lifetime fields.
|
|
3575
|
+
*/
|
|
3576
|
+
createAttachmentUploads(params: CreateAttachmentUploadsParams, signal?: AbortSignal): Promise<CreateAttachmentUploadsResponse>;
|
|
3577
|
+
/**
|
|
3578
|
+
* Finalizes a presigned upload after PUTting bytes to `uploadUrl`.
|
|
3579
|
+
*/
|
|
3580
|
+
completeAttachmentUpload(attachmentId: string, signal?: AbortSignal): Promise<AttachmentResponse>;
|
|
3581
|
+
/**
|
|
3582
|
+
* Polls staged attachment status (`GET /v0/attachments/{id}`).
|
|
3583
|
+
*/
|
|
3584
|
+
getAttachment(attachmentId: string, signal?: AbortSignal): Promise<AttachmentResponse>;
|
|
3490
3585
|
private stripStorytelling;
|
|
3491
3586
|
private wrapStreamWithStorytellingStripping;
|
|
3492
3587
|
}
|
|
3493
3588
|
|
|
3494
|
-
export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, AttachmentUploadResponseSchema, ChartCritiqueIssueCategorySchema, ChartCritiqueIssueSchema, ChartCritiqueIssueSeveritySchema, ChartCritiqueReportSchema, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, ChartJudgeRubricSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeParamsSchema, GenerateNarrativeResponseSchema, GeneratePipelineParamsSchema, GeneratePipelineResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, JudgeParamsSchema, JudgeResponseSchema, MAX_BUDGET_COST_USD, MAX_BUDGET_TOTAL_TOKENS, MAX_BUDGET_WALL_CLOCK_MS, MAX_EXTRACT_ATTACHMENTS, MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES, MAX_EXTRACT_DOCUMENTS, MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES, MAX_EXTRACT_DOCUMENT_DECODED_BYTES, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, MutateNarrationReceiptSchema, PipelineAgentNameSchema, PipelineStageReasoningSchema, RubricScoresSchema, RunContextSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isAgentCompleteEvent, isCompleteEvent, isErrorEvent, isGraphyApiError, isLlmStepEvent, isPreviewEvent, isProgressEvent, isReasoningEvent, isSessionBudgetEvent, isToolCallEvent, isToolCompleteEvent, isToolErrorEvent };
|
|
3495
|
-
export type { AgentCompleteEvent, AggregationFunction, AggregationSuggestion, AiChartType, AttachmentUploadResponse, BudgetReport, ChartCritiqueIssue, ChartCritiqueIssueCategory, ChartCritiqueIssueSeverity, ChartCritiqueReport, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, ChartJudgeRubric, ClientConfig, CompleteEvent, DataObservation, DataObservationKind, ErrorEvent, EvaluateParams, EvaluateResponse, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GeneratePipelineParams, GeneratePipelineResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, InvocationUsageSummary, JudgeParams, JudgeResponse, LlmStepEvent, Logger, Metadata, MutateNarrationReceipt, PipelineAgentName, PipelineStageReasoning, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, RubricScores, RunContext, SSEEvent, SessionBudgetEvent, StorytellingEffort, StorytellingOptions, Suggestion, ToolCallEvent, ToolCompleteEvent, ToolErrorEvent, UsageMetadata };
|
|
3589
|
+
export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, AttachmentResponseSchema, AttachmentUploadResponseSchema, AttachmentUploadSlotResponseSchema, ChartCritiqueIssueCategorySchema, ChartCritiqueIssueSchema, ChartCritiqueIssueSeveritySchema, ChartCritiqueReportSchema, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, ChartJudgeRubricSchema, CreateAttachmentUploadsParamsSchema, CreateAttachmentUploadsResponseSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeParamsSchema, GenerateNarrativeResponseSchema, GeneratePipelineParamsSchema, GeneratePipelineResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, JudgeParamsSchema, JudgeResponseSchema, MAX_BUDGET_COST_USD, MAX_BUDGET_TOTAL_TOKENS, MAX_BUDGET_WALL_CLOCK_MS, MAX_EXTRACT_ATTACHMENTS, MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES, MAX_EXTRACT_DOCUMENTS, MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES, MAX_EXTRACT_DOCUMENT_DECODED_BYTES, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_STAGED_FILE_BYTES, MAX_USER_PROMPT_LENGTH, MetadataSchema, MutateNarrationReceiptSchema, PipelineAgentNameSchema, PipelineStageReasoningSchema, RubricScoresSchema, RunContextSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isAgentCompleteEvent, isCompleteEvent, isErrorEvent, isGraphyApiError, isLlmStepEvent, isPreviewEvent, isProgressEvent, isReasoningEvent, isSessionBudgetEvent, isToolCallEvent, isToolCompleteEvent, isToolErrorEvent };
|
|
3590
|
+
export type { AgentCompleteEvent, AggregationFunction, AggregationSuggestion, AiChartType, AttachmentResponse, AttachmentUploadResponse, AttachmentUploadSlotResponse, BudgetReport, ChartCritiqueIssue, ChartCritiqueIssueCategory, ChartCritiqueIssueSeverity, ChartCritiqueReport, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, ChartJudgeRubric, ClientConfig, CompleteEvent, CreateAttachmentUploadsParams, CreateAttachmentUploadsResponse, DataObservation, DataObservationKind, ErrorEvent, EvaluateParams, EvaluateResponse, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GeneratePipelineParams, GeneratePipelineResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, InvocationUsageSummary, JudgeParams, JudgeResponse, LlmStepEvent, Logger, Metadata, MutateNarrationReceipt, PipelineAgentName, PipelineStageReasoning, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, RubricScores, RunContext, SSEEvent, SessionBudgetEvent, StorytellingEffort, StorytellingOptions, Suggestion, ToolCallEvent, ToolCompleteEvent, ToolErrorEvent, UploadAttachmentOptions, UsageMetadata };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e,__asyncValues as t,__asyncGenerator as n,__await as i,__rest as o}from"tslib";import{z as r}from"zod";class a extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const s=e=>e instanceof a,l=e=>"progress"===e.type,c=e=>"complete"===e.type,m=e=>"error"===e.type,u=e=>"preview"===e.type,d=e=>"reasoning"===e.type,p=e=>"llm_step"===e.type,g=e=>"session_budget"===e.type,h=e=>"agent_complete"===e.type,f=e=>"tool_call"===e.type,b=e=>"tool_complete"===e.type,y=e=>"tool_error"===e.type;function v(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class w{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return l(e)}static isCompleteEvent(e){return c(e)}static isErrorEvent(e){return m(e)}stream(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i);return this.parseSSE(e)})}fetch(n,i,o,r){return e(this,void 0,void 0,function*(){var e,s,u,d,p;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${n}`);try{const y=yield this.makeRequest(n,i,r),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,b=t(this.parseSSE(y));!(e=(h=yield b.next()).done);f=!0){d=h.value,f=!1;const e=d;if(l(e)&&o&&o(e),c(e))return e.data;if(m(e)){const t=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${n} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(p=e.retryable)&&void 0!==p&&p})}}}catch(e){s={error:e}}finally{try{f||e||!(u=b.return)||(yield u.call(b))}finally{if(s)throw s.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${n} ${i}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${n} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${n} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,i);return yield e.json()})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return n(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),n=new TextDecoder;let o="",r="",s="";try{for(;;){const{done:e,value:a}=yield i(t.read());if(e)break;o+=n.decode(a,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const e of l)if(e.startsWith("event: "))r=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=v(r,JSON.parse(s));if(null===e){r="",s="";continue}if(yield yield i(e),"complete"===r||"error"===r)return yield i(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}r="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1,o="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const r=new URL(e,this.baseUrl);if(r.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${r}`);const s=new AbortController,l=setTimeout(()=>s.abort(),this.timeout),c=()=>s.abort();n&&n.addEventListener("abort",c);try{const l=yield fetch(r,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!l.ok){let r,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(r=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===r)&&(l.status>=500||429===l.status),m=new a(s,{status:l.status,code:r,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(r){if(r instanceof a)throw r;if(r instanceof Error&&"AbortError"===r.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),r;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,r),new a("Network error",{retryable:!0})}finally{clearTimeout(l),n&&n.removeEventListener("abort",c)}})}makeMultipartRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeout),l=()=>r.abort();n&&n.addEventListener("abort",l);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:r.signal});if(!s.ok){let o,r=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?r=t.message:"string"==typeof t.error&&(r=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=s.status>=500||429===s.status,c=new a(r,{status:s.status,code:o,retryable:l});if(l&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw c}return s}catch(o){if(o instanceof a)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw new a("Network error",{retryable:!0})}finally{clearTimeout(s),n&&n.removeEventListener("abort",l)}})}}const x=r.object({inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional(),wallClockMs:r.number()}),j=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()}),k=r.object({limits:r.object({maxWallClockMs:r.number().optional(),maxTotalTokens:r.number().optional(),maxCostUsd:r.number().optional(),trackUsage:r.boolean().optional()}),consumed:j,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});r.object({inputTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),modelName:r.string(),inputCachedTokens:r.number().optional(),inputUncachedTokens:r.number().optional(),cost:r.number().optional(),latencyMs:r.number().optional(),effort:r.string().optional(),providerReasoning:r.string().optional()});const T={usage:x.optional(),budget:k.optional()},$=r.enum(["EN_GB","EN_US"]),S=r.custom(e=>null!=e&&"object"==typeof e),C=r.enum(["low","medium","high"]),R=r.enum(["none","low","medium","high"]),E=r.enum(["agentic","fast"]),U=3e5,I=5e5,O=10,A=r.object({maxWallClockMs:r.number().positive().max(U).optional(),maxTotalTokens:r.number().int().positive().max(I).optional(),maxCostUsd:r.number().positive().max(10).optional(),trackUsage:r.boolean().optional()}),P=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()});r.object({limits:A,consumed:P,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});const M=r.object({callId:r.string().max(256).optional(),locale:$.optional(),effort:C.optional(),storytellingEffort:R.optional().default("low"),budget:A.optional(),executionMode:E.optional(),enforceTableRowCap:r.boolean().optional()}),B=r.object({steps:r.array(r.string()),postProcess:r.object({measureRelevance:r.enum(["prompt-named","derived","magnitude"]).optional(),grain:r.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:r.string().optional(),comparison:r.string().optional()}).optional(),droppedMeasures:r.array(r.string()).optional(),rowCount:r.number().int().nonnegative(),totalRowCountBeforeSlice:r.number().int().positive().optional(),displayedRowCount:r.number().int().nonnegative().optional(),columnKeys:r.array(r.string()),activeFilters:r.array(r.string()).optional(),grainSummary:r.string().optional()}),F=r.object({runId:r.string(),trackingId:r.string(),callId:r.string().optional()}),q=1e4,D=r.enum(["comparison","relationship","distribution","composition"]),_=r.object({config:S,userPrompt:r.string().max(q).optional().default(""),metadata:M.optional(),chartFamily:D.optional()}),N=_.extend({maxSuggestionCount:r.number().int().min(1).max(4).optional()}),K=r.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),L=r.object({dataPrepPrompt:r.string(),chartType:K,summary:r.string()}),W=_.extend({userPrompt:r.string().max(q),mutationReceipt:B.optional(),exploreFindingSummary:r.string().max(500).optional()}),G=r.object({response:r.object({message:r.string()}),config:S,run:F.optional()}).extend(T),z=r.object({suggestions:r.array(L),run:F.optional()}).extend(T),H=r.object({finding:r.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:r.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:r.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:r.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:r.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:D.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:r.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),J=r.object({topic:r.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:r.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:r.number().int().min(1).describe("Number of findings in this story."),findings:r.array(H).describe("Child findings, sorted by quadrant score desc.")}),X=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),stories:r.array(J),run:F.optional()}).extend(T);_.extend({mutationReceipt:B.optional()});const Q=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:S,run:F.optional()}).extend(T),V=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:S,mutationReceipt:B.optional(),warnings:r.array(r.string()).optional(),run:F.optional()}).extend(T),Y=r.enum(["explore","mutate","narrate","annotate"]),Z=r.object({agent:Y,summary:r.string(),steps:r.array(r.string()).optional()}),ee=_.extend({userPrompt:r.string().max(q),stages:r.array(Y).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:r.string().max(500).optional()}),te=V.extend({reasoning:r.array(Z),stories:r.array(J).optional()}),ne=r.enum(["high","medium","low"]),ie=r.object({confidence:ne,needsUserInput:r.boolean(),warnings:r.array(r.string()),cellConfidence:r.array(r.object({rowIndex:r.number().int().nonnegative(),columnKey:r.string(),confidence:ne,quote:r.string().optional()})).optional()}),oe=r.object({score:r.number().min(0).max(1),issues:r.array(r.string()),sufficient:r.boolean(),summary:r.string()}),re=5e5,ae=8,se=2097152,le=7340032,ce=2,me=6291456,ue=8388608,de=2,pe=me,ge=ue,he=12582912,fe=12;function be(e){return 4*Math.ceil(e/3)}const ye=be(se),ve=be(le),we=be(me),xe=be(ue),je=be(pe),ke=be(ge),Te=be(he);function $e(e){return e.replace(/\s+/g,"")}function Se(e){const t=$e(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const Ce=/^image\/(png|jpeg|jpg|webp|gif)$/i,Re=r.object({mimeType:r.string().min(1).refine(e=>Ce.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:r.string().min(1).max(ye).refine(Se,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Ee=r.enum(["image","document","spreadsheet"]),Ue=Re.extend({kind:r.literal("image")}),Ie=r.object({kind:r.literal("document"),mimeType:r.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:r.string().min(1).max(we).refine(Se,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Oe=r.object({kind:r.literal("spreadsheet"),mimeType:r.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:r.string().min(1).max(je).refine(Se,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:r.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),Ae=r.discriminatedUnion("kind",[Ue,Ie,Oe]),Pe=r.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),Me=r.object({id:r.string().uuid(),uri:r.string(),kind:Ee,mimeType:r.string(),filename:r.string().optional(),sizeBytes:r.number().int().positive(),expiresAt:r.string().datetime()}),Be=r.object({sourceText:r.string().max(re).default(""),images:r.array(Re).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:r.array(Ae).max(12).optional(),attachmentRefs:r.array(Pe).max(12).optional(),metadata:M.optional()}).superRefine((e,t)=>{var n,i,o;const r=e.sourceText.trim(),a=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(i=e.attachments)&&void 0!==i?i:[],l=null!==(o=e.attachmentRefs)&&void 0!==o?o:[];if(a.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(l.length>0&&s.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or inline `attachments`, not both.",path:["attachmentRefs"]});if(l.length>0&&a.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or deprecated `images`, not both.",path:["attachmentRefs"]});if(0===r.length&&0===a.length&&0===s.length&&0===l.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(l.length>0)return;if(a.length>0){a.reduce((e,t)=>e+$e(t.dataBase64).length,0)>ve&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let c=0,m=0,u=0,d=0,p=0,g=0,h=0;for(const e of s){const t=$e(e.dataBase64).length;switch(h+=t,e.kind){case"image":c+=1,d+=t;break;case"document":m+=1,p+=t;break;case"spreadsheet":u+=1,g+=t}}c>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),u>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=c<=8&&m<=2&&u<=2;s.length>0&&f&&(d>ve&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>xe&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>ke&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>Te&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function Fe(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:$e(e.dataBase64)}}function qe(e){return{kind:"document",mimeType:"application/pdf",dataBase64:$e(e.dataBase64)}}function De(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:$e(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const _e=r.object({response:r.object({message:r.string()}),config:S,extractMeta:ie.nullable(),lastAccuracyEvaluation:oe.optional(),run:F.optional()}).extend(T),Ne=r.object({config:S,response:r.object({message:r.string(),steps:r.array(r.string())}),run:F.optional()}).extend(T),Ke=z,Le=r.enum(["deal-breaker","pro","con","family","continuity"]),We=r.object({kind:Le,label:r.string(),weight:r.number(),reason:r.string()}),Ge=r.enum(["ok","disqualified"]),ze=r.object({rank:r.number().int().positive(),type:K,score:r.number(),verdict:Ge,factors:r.array(We)}),He=r.object({config:S,chartFamily:D.optional(),metadata:M.optional()}),Je=r.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),Xe=r.object({kind:Je,message:r.string()}),Qe=r.enum(["sum","avg","count","min","max"]),Ve=r.object({dimensionName:r.string(),dimensionLabel:r.string(),measureName:r.string().nullable(),measureLabel:r.string().nullable(),fn:Qe,chartType:K,score:r.number(),message:r.string()}),Ye=r.object({ranking:r.array(ze),observations:r.array(Xe).optional().default([]),suggestions:r.array(Ve).optional().default([]),run:F.optional()}),Ze=r.object({prompt:r.string(),datasetSummary:r.string().optional(),mustShow:r.array(r.string()).optional(),unacceptable:r.array(r.string()).optional(),acceptableChartFamilies:r.array(r.string()).optional()}),et=r.object({config:S.optional(),chartImage:r.string().optional(),data:r.unknown().optional(),rubric:Ze.optional(),userPrompt:r.string().optional(),metadata:M.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),tt=r.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),nt=r.enum(["info","low","medium","high"]),it=r.object({category:tt,severity:nt,observation:r.string(),rationale:r.string().optional(),suggestedChange:r.string().optional(),configPaths:r.array(r.string()).optional()}),ot=r.object({overallSummary:r.string(),overallSeverity:r.enum(["none","low","medium","high"]).optional(),issues:r.array(it)}),rt=r.object({dataFidelity:r.number().min(0).max(1),promptRelevance:r.number().min(0).max(1),chartTypeAppropriateness:r.number().min(0).max(1),readability:r.number().min(0).max(1),honesty:r.number().min(0).max(1),composite:r.number().min(0).max(1),rationale:r.string().optional()}),at=r.object({capturedAt:r.string(),chartId:r.string()}),st=r.object({response:r.object({message:r.string(),steps:r.array(r.string()),critiqueCommitted:r.boolean()}),critiqueReport:ot.nullable(),chartVisionAudit:at.nullable().optional().default(null),rubricScores:rt.nullable().optional().default(null),run:F.optional()}).extend(T),lt="/api/v0";class ct{constructor(e){this.client=new w(e)}generateGraph(t,n,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,r=o(t,["storytellingOptions"]),a=yield this.client.fetch(`${lt}/generate`,r,n,i),s=Ne.parse(a);return this.stripStorytelling(s,e)})}generateGraphStream(t,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,i=o(t,["storytellingOptions"]),r=yield this.client.stream(`${lt}/generate`,i,n);return this.wrapStreamWithStorytellingStripping(r,e)})}generateNarrative(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/narrate`,t,n,i);return G.parse(e)})}generateNarrativeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/narrate`,t,n)})}generateSuggestions(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/suggestions`,t,n,i);return z.parse(e)})}generateSuggestionsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/suggestions`,t,n)})}generateExploration(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/explore`,t,n,i);return X.parse(e)})}generateExplorationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/explore`,t,n)})}generateAnnotations(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/annotate`,t,n,i);return Q.parse(e)})}generateAnnotationsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/annotate`,t,n)})}generateMutation(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/mutate`,t,n,i);return V.parse(e)})}generateMutationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/mutate`,t,n)})}generatePipeline(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/pipeline`,t,n,i);return te.parse(e)})}generatePipelineStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/pipeline`,t,n)})}evaluate(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/evaluate`,t,void 0,n);return Ye.parse(e)})}judge(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/judge`,t,void 0,n);return st.parse(e)})}judgeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/judge`,t,n)})}extractFromProse(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/extract`,t,n,i);return _e.parse(e)})}extractFromProseStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/extract`,t,n)})}uploadAttachment(t,n,i){return e(this,void 0,void 0,function*(){const e=new FormData,o=null==n?void 0:n.filename;"undefined"!=typeof File&&t instanceof File?e.append("file",t):o?e.append("file",t,o):e.append("file",t,"upload"),o&&e.append("filename",o);const r=yield this.client.uploadMultipart(`${lt}/attachments`,e,i);return Me.parse(r)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,o){return n(this,arguments,function*(){var n,r,a,s;try{for(var l,m=!0,u=t(e);!(n=(l=yield i(u.next())).done);m=!0){s=l.value,m=!1;const e=s;if(c(e)){const t=this.stripStorytelling(e.data,o);yield yield i(Object.assign(Object.assign({},e),{data:t}))}else yield yield i(e)}}catch(e){r={error:e}}finally{try{m||n||!(a=u.return)||(yield i(a.call(u)))}finally{if(r)throw r.error}}})}}export{Qe as AggregationFunctionSchema,Ve as AggregationSuggestionSchema,K as AiChartTypeEnum,Me as AttachmentUploadResponseSchema,tt as ChartCritiqueIssueCategorySchema,it as ChartCritiqueIssueSchema,nt as ChartCritiqueIssueSeveritySchema,ot as ChartCritiqueReportSchema,D as ChartFamilySchema,ze as ChartFitEntrySchema,Le as ChartFitFactorKindSchema,We as ChartFitFactorSchema,Ge as ChartFitVerdictSchema,Ze as ChartJudgeRubricSchema,Je as DataObservationKindSchema,Xe as DataObservationSchema,He as EvaluateParamsSchema,Ye as EvaluateResponseSchema,E as ExecutionModeSchema,H as ExploreFindingSchema,J as ExploreStorySchema,oe as ExtractAccuracyEvaluationSchema,Ae as ExtractAttachmentInputSchema,Ee as ExtractAttachmentKindSchema,ne as ExtractConfidenceSchema,Be as ExtractFromProseParamsSchema,_e as ExtractFromProseResponseSchema,ie as ExtractMetaSchema,Q as GenerateAnnotationsResponseSchema,X as GenerateExplorationResponseSchema,Ne as GenerateGraphResponseSchema,Ke as GenerateGraphSuggestionsResponseSchema,V as GenerateMutationResponseSchema,W as GenerateNarrativeParamsSchema,G as GenerateNarrativeResponseSchema,ee as GeneratePipelineParamsSchema,te as GeneratePipelineResponseSchema,N as GenerateSuggestionsParamsSchema,z as GenerateSuggestionsResponseSchema,_ as GraphGenerationRequestSchema,ct as GraphyAiSdk,a as GraphyApiError,A as InvocationBudgetSchema,C as InvocationEffortSchema,et as JudgeParamsSchema,st as JudgeResponseSchema,O as MAX_BUDGET_COST_USD,I as MAX_BUDGET_TOTAL_TOKENS,U as MAX_BUDGET_WALL_CLOCK_MS,fe as MAX_EXTRACT_ATTACHMENTS,he as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,ce as MAX_EXTRACT_DOCUMENTS,ue as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,me as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,ae as MAX_EXTRACT_IMAGES,le as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,se as MAX_EXTRACT_IMAGE_DECODED_BYTES,de as MAX_EXTRACT_SPREADSHEETS,ge as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,pe as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,re as MAX_SOURCE_TEXT_LENGTH,q as MAX_USER_PROMPT_LENGTH,M as MetadataSchema,B as MutateNarrationReceiptSchema,Y as PipelineAgentNameSchema,Z as PipelineStageReasoningSchema,rt as RubricScoresSchema,F as RunContextSchema,R as StorytellingEffortSchema,L as SuggestionSchema,Fe as buildImageAttachment,qe as buildPdfAttachment,De as buildSpreadsheetAttachment,h as isAgentCompleteEvent,c as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,p as isLlmStepEvent,u as isPreviewEvent,l as isProgressEvent,d as isReasoningEvent,g as isSessionBudgetEvent,f as isToolCallEvent,b as isToolCompleteEvent,y as isToolErrorEvent};
|
|
1
|
+
import{__awaiter as e,__asyncValues as t,__asyncGenerator as n,__await as i,__rest as o}from"tslib";import{z as r}from"zod";class a extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const s=e=>e instanceof a,l=e=>"progress"===e.type,c=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type,p=e=>"llm_step"===e.type,g=e=>"session_budget"===e.type,h=e=>"agent_complete"===e.type,f=e=>"tool_call"===e.type,b=e=>"tool_complete"===e.type,y=e=>"tool_error"===e.type;function v(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class x{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return l(e)}static isCompleteEvent(e){return c(e)}static isErrorEvent(e){return m(e)}stream(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i);return this.parseSSE(e)})}fetch(n,i,o,r){return e(this,void 0,void 0,function*(){var e,s,d,u,p;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${n}`);try{const y=yield this.makeRequest(n,i,r),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,b=t(this.parseSSE(y));!(e=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(l(e)&&o&&o(e),c(e))return e.data;if(m(e)){const t=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${n} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(p=e.retryable)&&void 0!==p&&p})}}}catch(e){s={error:e}}finally{try{f||e||!(d=b.return)||(yield d.call(b))}finally{if(s)throw s.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${n} ${i}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${n} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${n} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,i);return yield e.json()})}get(t,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,void 0,n,1,"GET");return yield e.json()})}postJson(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i,1,"POST");return yield e.json()})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return n(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),n=new TextDecoder;let o="",r="",s="";try{for(;;){const{done:e,value:a}=yield i(t.read());if(e)break;o+=n.decode(a,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const e of l)if(e.startsWith("event: "))r=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=v(r,JSON.parse(s));if(null===e){r="",s="";continue}if(yield yield i(e),"complete"===r||"error"===r)return yield i(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}r="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1,o="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const r=new URL(e,this.baseUrl);if(r.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${r}`);const s=new AbortController,l=setTimeout(()=>s.abort(),this.timeout),c=()=>s.abort();n&&n.addEventListener("abort",c);try{const l=yield fetch(r,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!l.ok){let r,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(r=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===r)&&(l.status>=500||429===l.status),m=new a(s,{status:l.status,code:r,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(r){if(r instanceof a)throw r;if(r instanceof Error&&"AbortError"===r.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),r;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,r),new a("Network error",{retryable:!0})}finally{clearTimeout(l),n&&n.removeEventListener("abort",c)}})}makeMultipartRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeout),l=()=>r.abort();n&&n.addEventListener("abort",l);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:r.signal});if(!s.ok){let o,r=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?r=t.message:"string"==typeof t.error&&(r=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=s.status>=500||429===s.status,c=new a(r,{status:s.status,code:o,retryable:l});if(l&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw c}return s}catch(o){if(o instanceof a)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw new a("Network error",{retryable:!0})}finally{clearTimeout(s),n&&n.removeEventListener("abort",l)}})}}const w={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function j(e,t){var n;const i=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return i||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function k(e,t){var n;const i=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(i)return i;const o=e.type.trim();if(o.length>0)return o;const r=j(e,t);if(r){const e=function(e){const t=e.lastIndexOf(".");if(t<0)return;const n=e.slice(t).toLowerCase();return w[n]}(r);if(e)return e}throw new Error("uploadAttachment requires a MIME type: set `file.type`, pass `options.mimeType`, or use a filename with a supported extension (.png, .jpg, .pdf, .xlsx, …)")}const T=r.object({inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional(),wallClockMs:r.number()}),$=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()}),S=r.object({limits:r.object({maxWallClockMs:r.number().optional(),maxTotalTokens:r.number().optional(),maxCostUsd:r.number().optional(),trackUsage:r.boolean().optional()}),consumed:$,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});r.object({inputTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),modelName:r.string(),inputCachedTokens:r.number().optional(),inputUncachedTokens:r.number().optional(),cost:r.number().optional(),latencyMs:r.number().optional(),effort:r.string().optional(),providerReasoning:r.string().optional()});const C={usage:T.optional(),budget:S.optional()},R=r.enum(["EN_GB","EN_US"]),E=r.custom(e=>null!=e&&"object"==typeof e),U=r.enum(["low","medium","high"]),A=r.enum(["none","low","medium","high"]),O=r.enum(["agentic","fast"]),I=3e5,P=5e5,M=10,B=r.object({maxWallClockMs:r.number().positive().max(I).optional(),maxTotalTokens:r.number().int().positive().max(P).optional(),maxCostUsd:r.number().positive().max(10).optional(),trackUsage:r.boolean().optional()}),q=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()});r.object({limits:B,consumed:q,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});const F=r.object({callId:r.string().max(256).optional(),locale:R.optional(),effort:U.optional(),storytellingEffort:A.optional().default("low"),budget:B.optional(),executionMode:O.optional(),enforceTableRowCap:r.boolean().optional()}),_=r.object({steps:r.array(r.string()),postProcess:r.object({measureRelevance:r.enum(["prompt-named","derived","magnitude"]).optional(),grain:r.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:r.string().optional(),comparison:r.string().optional()}).optional(),droppedMeasures:r.array(r.string()).optional(),rowCount:r.number().int().nonnegative(),totalRowCountBeforeSlice:r.number().int().positive().optional(),displayedRowCount:r.number().int().nonnegative().optional(),columnKeys:r.array(r.string()),activeFilters:r.array(r.string()).optional(),grainSummary:r.string().optional()}),D=r.object({runId:r.string(),trackingId:r.string(),callId:r.string().optional()}),N=1e4,K=r.enum(["comparison","relationship","distribution","composition"]),L=r.object({config:E,userPrompt:r.string().max(N).optional().default(""),metadata:F.optional(),chartFamily:K.optional()}),z=L.extend({maxSuggestionCount:r.number().int().min(1).max(4).optional()}),G=r.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),W=r.object({dataPrepPrompt:r.string(),chartType:G,summary:r.string()}),H=L.extend({userPrompt:r.string().max(N),mutationReceipt:_.optional(),exploreFindingSummary:r.string().max(500).optional()}),J=r.object({response:r.object({message:r.string()}),config:E,run:D.optional()}).extend(C),X=r.object({suggestions:r.array(W),run:D.optional()}).extend(C),Q=r.object({finding:r.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:r.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:r.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:r.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:r.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:K.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:r.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),V=r.object({topic:r.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:r.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:r.number().int().min(1).describe("Number of findings in this story."),findings:r.array(Q).describe("Child findings, sorted by quadrant score desc.")}),Y=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),stories:r.array(V),run:D.optional()}).extend(C);L.extend({mutationReceipt:_.optional()});const Z=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:E,run:D.optional()}).extend(C),ee=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:E,mutationReceipt:_.optional(),warnings:r.array(r.string()).optional(),run:D.optional()}).extend(C),te=r.enum(["explore","mutate","narrate","annotate"]),ne=r.object({agent:te,summary:r.string(),steps:r.array(r.string()).optional()}),ie=L.extend({userPrompt:r.string().max(N),stages:r.array(te).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:r.string().max(500).optional()}),oe=ee.extend({reasoning:r.array(ne),stories:r.array(V).optional()}),re=r.enum(["high","medium","low"]),ae=r.object({confidence:re,needsUserInput:r.boolean(),warnings:r.array(r.string()),cellConfidence:r.array(r.object({rowIndex:r.number().int().nonnegative(),columnKey:r.string(),confidence:re,quote:r.string().optional()})).optional()}),se=r.object({score:r.number().min(0).max(1),issues:r.array(r.string()),sufficient:r.boolean(),summary:r.string()}),le=5e5,ce=8,me=2097152,de=7340032,ue=2,pe=6291456,ge=8388608,he=2,fe=pe,be=ge,ye=12582912,ve=12,xe=52428800;function we(e){return 4*Math.ceil(e/3)}const je=we(me),ke=we(de),Te=we(pe),$e=we(ge),Se=we(fe),Ce=we(be),Re=we(ye);function Ee(e){return e.replace(/\s+/g,"")}function Ue(e){const t=Ee(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const Ae=/^image\/(png|jpeg|jpg|webp|gif)$/i,Oe=r.object({mimeType:r.string().min(1).refine(e=>Ae.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:r.string().min(1).max(je).refine(Ue,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Ie=r.enum(["image","document","spreadsheet"]),Pe=Oe.extend({kind:r.literal("image")}),Me=r.object({kind:r.literal("document"),mimeType:r.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:r.string().min(1).max(Te).refine(Ue,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Be=r.object({kind:r.literal("spreadsheet"),mimeType:r.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:r.string().min(1).max(Se).refine(Ue,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:r.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),qe=r.discriminatedUnion("kind",[Pe,Me,Be]),Fe=r.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),_e=r.enum(["pending","ready","failed"]),De=r.object({id:r.string().uuid(),uri:r.string(),status:_e,kind:Ie.optional(),mimeType:r.string(),filename:r.string().optional(),sizeBytes:r.number().int().nonnegative(),uploadExpiresAt:r.string().datetime().optional(),completedAt:r.string().datetime().optional(),expiresAt:r.string().datetime()}),Ne=De.extend({status:r.literal("ready"),kind:Ie,sizeBytes:r.number().int().positive()}),Ke=r.object({mimeType:r.string().min(1),filename:r.string().max(512).optional(),sizeBytes:r.number().int().positive().max(xe).optional()}),Le=r.object({files:r.array(Ke).min(1).max(ve)}),ze=De.extend({status:r.literal("pending"),uploadUrl:r.string().url()}),Ge=r.object({uploads:r.array(ze)}),We=r.object({sourceText:r.string().max(le).default(""),images:r.array(Oe).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:r.array(qe).max(ve).optional(),attachmentRefs:r.array(Fe).max(ve).optional(),metadata:F.optional()}).superRefine((e,t)=>{var n,i,o;const r=e.sourceText.trim(),a=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(i=e.attachments)&&void 0!==i?i:[],l=null!==(o=e.attachmentRefs)&&void 0!==o?o:[];if(a.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===r.length&&0===a.length&&0===s.length&&0===l.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(a.length+s.length+l.length>ve)return void t.addIssue({code:"custom",message:"Too many attachments (max 12 across inline payloads and attachmentRefs)",path:["attachmentRefs"]});if(l.length>0&&0===s.length&&0===a.length)return;if(a.length>0){a.reduce((e,t)=>e+Ee(t.dataBase64).length,0)>ke&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let c=0,m=0,d=0,u=0,p=0,g=0,h=0;for(const e of s){const t=Ee(e.dataBase64).length;switch(h+=t,e.kind){case"image":c+=1,u+=t;break;case"document":m+=1,p+=t;break;case"spreadsheet":d+=1,g+=t}}c>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),d>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=c<=8&&m<=2&&d<=2;s.length>0&&f&&(u>ke&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>$e&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>Ce&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>Re&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function He(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:Ee(e.dataBase64)}}function Je(e){return{kind:"document",mimeType:"application/pdf",dataBase64:Ee(e.dataBase64)}}function Xe(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:Ee(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const Qe=r.object({response:r.object({message:r.string()}),config:E,extractMeta:ae.nullable(),lastAccuracyEvaluation:se.optional(),run:D.optional()}).extend(C),Ve=r.object({config:E,response:r.object({message:r.string(),steps:r.array(r.string())}),run:D.optional()}).extend(C),Ye=X,Ze=r.enum(["deal-breaker","pro","con","family","continuity"]),et=r.object({kind:Ze,label:r.string(),weight:r.number(),reason:r.string()}),tt=r.enum(["ok","disqualified"]),nt=r.object({rank:r.number().int().positive(),type:G,score:r.number(),verdict:tt,factors:r.array(et)}),it=r.object({config:E,chartFamily:K.optional(),metadata:F.optional()}),ot=r.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),rt=r.object({kind:ot,message:r.string()}),at=r.enum(["sum","avg","count","min","max"]),st=r.object({dimensionName:r.string(),dimensionLabel:r.string(),measureName:r.string().nullable(),measureLabel:r.string().nullable(),fn:at,chartType:G,score:r.number(),message:r.string()}),lt=r.object({ranking:r.array(nt),observations:r.array(rt).optional().default([]),suggestions:r.array(st).optional().default([]),run:D.optional()}),ct=r.object({prompt:r.string(),datasetSummary:r.string().optional(),mustShow:r.array(r.string()).optional(),unacceptable:r.array(r.string()).optional(),acceptableChartFamilies:r.array(r.string()).optional()}),mt=r.object({config:E.optional(),chartImage:r.string().optional(),data:r.unknown().optional(),rubric:ct.optional(),userPrompt:r.string().optional(),metadata:F.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),dt=r.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),ut=r.enum(["info","low","medium","high"]),pt=r.object({category:dt,severity:ut,observation:r.string(),rationale:r.string().optional(),suggestedChange:r.string().optional(),configPaths:r.array(r.string()).optional()}),gt=r.object({overallSummary:r.string(),overallSeverity:r.enum(["none","low","medium","high"]).optional(),issues:r.array(pt)}),ht=r.object({dataFidelity:r.number().min(0).max(1),promptRelevance:r.number().min(0).max(1),chartTypeAppropriateness:r.number().min(0).max(1),readability:r.number().min(0).max(1),honesty:r.number().min(0).max(1),composite:r.number().min(0).max(1),rationale:r.string().optional()}),ft=r.object({capturedAt:r.string(),chartId:r.string()}),bt=r.object({response:r.object({message:r.string(),steps:r.array(r.string()),critiqueCommitted:r.boolean()}),critiqueReport:gt.nullable(),chartVisionAudit:ft.nullable().optional().default(null),rubricScores:ht.nullable().optional().default(null),run:D.optional()}).extend(C),yt="/api/v0";class vt{constructor(e){this.client=new x(e)}generateGraph(t,n,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,r=o(t,["storytellingOptions"]),a=yield this.client.fetch(`${yt}/generate`,r,n,i),s=Ve.parse(a);return this.stripStorytelling(s,e)})}generateGraphStream(t,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,i=o(t,["storytellingOptions"]),r=yield this.client.stream(`${yt}/generate`,i,n);return this.wrapStreamWithStorytellingStripping(r,e)})}generateNarrative(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/narrate`,t,n,i);return J.parse(e)})}generateNarrativeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/narrate`,t,n)})}generateSuggestions(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/suggestions`,t,n,i);return X.parse(e)})}generateSuggestionsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/suggestions`,t,n)})}generateExploration(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/explore`,t,n,i);return Y.parse(e)})}generateExplorationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/explore`,t,n)})}generateAnnotations(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/annotate`,t,n,i);return Z.parse(e)})}generateAnnotationsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/annotate`,t,n)})}generateMutation(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/mutate`,t,n,i);return ee.parse(e)})}generateMutationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/mutate`,t,n)})}generatePipeline(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/pipeline`,t,n,i);return oe.parse(e)})}generatePipelineStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/pipeline`,t,n)})}evaluate(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/evaluate`,t,void 0,n);return lt.parse(e)})}judge(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/judge`,t,void 0,n);return bt.parse(e)})}judgeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/judge`,t,n)})}extractFromProse(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/extract`,t,n,i);return Qe.parse(e)})}extractFromProseStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/extract`,t,n)})}uploadAttachment(t,n,i){return e(this,void 0,void 0,function*(){const e=k(t,n),o=j(t,n),{uploads:r}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},o?{filename:o}:{}),t.size>0?{sizeBytes:t.size}:{})]},i),s=r[0];if(!s)throw new a("Attachment upload slot was not returned");const l=yield fetch(s.uploadUrl,{method:"PUT",headers:{"Content-Type":e},body:t,signal:i});if(!l.ok)throw new a(`Attachment upload failed (HTTP ${l.status})`,{status:l.status,retryable:l.status>=500});const c=yield this.completeAttachmentUpload(s.id,i);return Ne.parse(c)})}createAttachmentUploads(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${yt}/attachment-uploads`,t,n);return Ge.parse(e)})}completeAttachmentUpload(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${yt}/attachments/${t}/complete`,{},n);return De.parse(e)})}getAttachment(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.get(`${yt}/attachments/${t}`,n);return De.parse(e)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,o){return n(this,arguments,function*(){var n,r,a,s;try{for(var l,m=!0,d=t(e);!(n=(l=yield i(d.next())).done);m=!0){s=l.value,m=!1;const e=s;if(c(e)){const t=this.stripStorytelling(e.data,o);yield yield i(Object.assign(Object.assign({},e),{data:t}))}else yield yield i(e)}}catch(e){r={error:e}}finally{try{m||n||!(a=d.return)||(yield i(a.call(d)))}finally{if(r)throw r.error}}})}}export{at as AggregationFunctionSchema,st as AggregationSuggestionSchema,G as AiChartTypeEnum,De as AttachmentResponseSchema,Ne as AttachmentUploadResponseSchema,ze as AttachmentUploadSlotResponseSchema,dt as ChartCritiqueIssueCategorySchema,pt as ChartCritiqueIssueSchema,ut as ChartCritiqueIssueSeveritySchema,gt as ChartCritiqueReportSchema,K as ChartFamilySchema,nt as ChartFitEntrySchema,Ze as ChartFitFactorKindSchema,et as ChartFitFactorSchema,tt as ChartFitVerdictSchema,ct as ChartJudgeRubricSchema,Le as CreateAttachmentUploadsParamsSchema,Ge as CreateAttachmentUploadsResponseSchema,ot as DataObservationKindSchema,rt as DataObservationSchema,it as EvaluateParamsSchema,lt as EvaluateResponseSchema,O as ExecutionModeSchema,Q as ExploreFindingSchema,V as ExploreStorySchema,se as ExtractAccuracyEvaluationSchema,qe as ExtractAttachmentInputSchema,Ie as ExtractAttachmentKindSchema,re as ExtractConfidenceSchema,We as ExtractFromProseParamsSchema,Qe as ExtractFromProseResponseSchema,ae as ExtractMetaSchema,Z as GenerateAnnotationsResponseSchema,Y as GenerateExplorationResponseSchema,Ve as GenerateGraphResponseSchema,Ye as GenerateGraphSuggestionsResponseSchema,ee as GenerateMutationResponseSchema,H as GenerateNarrativeParamsSchema,J as GenerateNarrativeResponseSchema,ie as GeneratePipelineParamsSchema,oe as GeneratePipelineResponseSchema,z as GenerateSuggestionsParamsSchema,X as GenerateSuggestionsResponseSchema,L as GraphGenerationRequestSchema,vt as GraphyAiSdk,a as GraphyApiError,B as InvocationBudgetSchema,U as InvocationEffortSchema,mt as JudgeParamsSchema,bt as JudgeResponseSchema,M as MAX_BUDGET_COST_USD,P as MAX_BUDGET_TOTAL_TOKENS,I as MAX_BUDGET_WALL_CLOCK_MS,ve as MAX_EXTRACT_ATTACHMENTS,ye as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,ue as MAX_EXTRACT_DOCUMENTS,ge as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,pe as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,ce as MAX_EXTRACT_IMAGES,de as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,me as MAX_EXTRACT_IMAGE_DECODED_BYTES,he as MAX_EXTRACT_SPREADSHEETS,be as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,fe as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,le as MAX_SOURCE_TEXT_LENGTH,xe as MAX_STAGED_FILE_BYTES,N as MAX_USER_PROMPT_LENGTH,F as MetadataSchema,_ as MutateNarrationReceiptSchema,te as PipelineAgentNameSchema,ne as PipelineStageReasoningSchema,ht as RubricScoresSchema,D as RunContextSchema,A as StorytellingEffortSchema,W as SuggestionSchema,He as buildImageAttachment,Je as buildPdfAttachment,Xe as buildSpreadsheetAttachment,h as isAgentCompleteEvent,c as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,p as isLlmStepEvent,d as isPreviewEvent,l as isProgressEvent,u as isReasoningEvent,g as isSessionBudgetEvent,f as isToolCallEvent,b as isToolCompleteEvent,y as isToolErrorEvent};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@graphysdk/agents-sdk",
|
|
3
3
|
"author": "Graphy",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.7.0-beta.1782310277218",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"files": [
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
20
|
"zod": "^4.3.6",
|
|
21
|
-
"@graphysdk/core": "1.
|
|
21
|
+
"@graphysdk/core": "1.7.0-beta.1782310277218"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|