@graphysdk/agents-sdk 1.7.1 → 1.7.2
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 +13 -2
- 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 a=e=>"progress"===e.type,r=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 a(e)}static isCompleteEvent(e){return r(e)}static isErrorEvent(e){return o(e)}stream(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,a);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(a(e)&&s&&s(e),r(e))return e.data;if(o(e)){const a=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${a}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 a=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}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,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,a);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,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,a,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 a=t.body.getReader(),r=new TextDecoder;let o="",s="",c="";try{for(;;){const{done:t,value:n}=yield e.__await(a.read());if(t)break;o+=r.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{a.releaseLock()}})}makeRequest(t,a,r){return e.__awaiter(this,arguments,void 0,function*(e,t,a,r=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 ${r}/${this.retryConfig.attempts}: ${i}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();a&&a.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&&r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${n}ms (attempt ${r+1})`),yield this.sleep(n),this.makeRequest(e,t,a,r+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(r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${n}ms`),yield this.sleep(n),this.makeRequest(e,t,a,r+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,i),new n("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",l)}})}makeMultipartRequest(t,a,r){return e.__awaiter(this,arguments,void 0,function*(e,t,a,r=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();a&&a.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&&r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,a,r+1)}throw l}return s}catch(o){if(o instanceof n)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,a,r+1)}throw new n("Network error",{retryable:!0})}finally{clearTimeout(s),a&&a.removeEventListener("abort",c)}})}}const c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".csv":"text/csv",".tsv":"text/tab-separated-values",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function l(e,t){var n;const a=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return a||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function m(e,t){var n;const a=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(a)return a;const r=e.type.trim();if(r.length>0)return r;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, .csv, .tsv, .xlsx, …)")}const p=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);function u(e,t){const n=m(e,t);if(a=n,!p.has(a.trim()))throw new Error("uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)");var a;return n}const d=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()}),g=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()}),h=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:g,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 f={usage:d.optional(),budget:h.optional()};function b(e,t){const n=void 0!==e.config.data,a=function(e){const{data:t}=e;return void 0!==t&&(t.columns.length>0||t.rows.length>0)}(e.config),r=void 0!==e.datasetRef&&e.datasetRef.trim().length>0;a&&r&&t.addIssue({code:"custom",message:"Provide either config.data or datasetRef, not both",path:["datasetRef"]}),n||r||t.addIssue({code:"custom",message:"Provide config.data or datasetRef",path:["datasetRef"]})}const y=t.z.enum(["EN_GB","EN_US"]),z=t.z.custom(e=>null!=e&&"object"==typeof e),x=t.z.enum(["low","medium","high"]),v=t.z.enum(["none","low","medium","high"]),_=t.z.enum(["agentic","fast"]),w=3e5,S=5e5,T=t.z.object({maxWallClockMs:t.z.number().positive().max(w).optional(),maxTotalTokens:t.z.number().int().positive().max(S).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),E=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:T,consumed:E,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});const C=t.z.object({callId:t.z.string().max(256).optional(),locale:y.optional(),effort:x.optional(),storytellingEffort:v.optional().default("low"),budget:T.optional(),executionMode:_.optional(),enforceTableRowCap:t.z.boolean().optional()}),j=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()}),A=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),R=1e4,k=t.z.enum(["comparison","relationship","distribution","composition"]),$=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,M=t.z.string().regex($,"datasetRef must be graphy://attachments/{uuid}"),O=t.z.object({config:z,userPrompt:t.z.string().max(R).optional().default(""),metadata:C.optional(),chartFamily:k.optional(),datasetRef:M.optional()}),P=O.superRefine(b),D=O.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}).superRefine(b),U=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),I=t.z.object({dataPrepPrompt:t.z.string(),chartType:U,summary:t.z.string()}),B=O.extend({userPrompt:t.z.string().max(R),mutationReceipt:j.optional(),exploreFindingSummary:t.z.string().max(500).optional()}).superRefine(b),G=t.z.object({response:t.z.object({message:t.z.string()}),config:z,run:A.optional()}).extend(f),X=t.z.object({suggestions:t.z.array(I),run:A.optional()}).extend(f),q=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:k.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.")}),F=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(q).describe("Child findings, sorted by quadrant score desc.")}),N=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(F),run:A.optional()}).extend(f);O.extend({mutationReceipt:j.optional()}).superRefine(b);const L=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:z,run:A.optional()}).extend(f),K=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:z,mutationReceipt:j.optional(),warnings:t.z.array(t.z.string()).optional(),run:A.optional()}).extend(f),H=t.z.enum(["explore","mutate","narrate","annotate"]),W=t.z.object({agent:H,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),Y=O.extend({userPrompt:t.z.string().max(R),stages:t.z.array(H).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}).superRefine(b),J=K.extend({reasoning:t.z.array(W),stories:t.z.array(F).optional()}),V=t.z.enum(["high","medium","low"]),Q=t.z.object({confidence:V,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:V,quote:t.z.string().optional()})).optional()}),Z=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()}),ee=5e5,te=2097152,ne=7340032,ae=6291456,re=8388608,oe=ae,ie=re,se=12582912,ce=12,le=52428800;function me(e){return 4*Math.ceil(e/3)}const pe=me(te),ue=me(ne),de=me(ae),ge=me(re),he=me(oe),fe=me(ie),be=me(se);function ye(e){return e.replace(/\s+/g,"")}function ze(e){const t=ye(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const xe=/^image\/(png|jpeg|jpg|webp|gif)$/i,ve=t.z.object({mimeType:t.z.string().min(1).refine(e=>xe.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(pe).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),_e=t.z.enum(["image","document","spreadsheet","tabular"]),we=ve.extend({kind:t.z.literal("image")}),Se=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(de).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Te=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(he).refine(ze,{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"]}),Ee=t.z.discriminatedUnion("kind",[we,Se,Te]),Ce=t.z.string().regex($,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),je=t.z.enum(["pending","ready","failed"]),Ae=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),status:je,kind:_e.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()}),Re=Ae.extend({status:t.z.literal("ready"),kind:_e,sizeBytes:t.z.number().int().positive()}),ke=t.z.object({mimeType:t.z.string().min(1),filename:t.z.string().max(512).optional(),sizeBytes:t.z.number().int().positive().max(le).optional()}),$e=t.z.object({files:t.z.array(ke).min(1).max(ce)}),Me=Ae.extend({status:t.z.literal("pending"),uploadUrl:t.z.string().url()}),Oe=t.z.object({uploads:t.z.array(Me)}),Pe=t.z.object({sourceText:t.z.string().max(ee).default(""),images:t.z.array(ve).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(Ee).max(ce).optional(),attachmentRefs:t.z.array(Ce).max(ce).optional(),metadata:C.optional()}).superRefine((e,t)=>{var n,a,r;const o=e.sourceText.trim(),i=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(a=e.attachments)&&void 0!==a?a:[],c=null!==(r=e.attachmentRefs)&&void 0!==r?r:[];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>ce)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+ye(t.dataBase64).length,0)>ue&&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=ye(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>ue&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ge&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>fe&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>be&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const De=t.z.object({response:t.z.object({message:t.z.string()}),config:z,extractMeta:Q.nullable(),lastAccuracyEvaluation:Z.optional(),run:A.optional()}).extend(f),Ue=t.z.object({config:z,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:A.optional()}).extend(f),Ie=X,Be=t.z.enum(["deal-breaker","pro","con","family","continuity"]),Ge=t.z.object({kind:Be,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),Xe=t.z.enum(["ok","disqualified"]),qe=t.z.object({rank:t.z.number().int().positive(),type:U,score:t.z.number(),verdict:Xe,factors:t.z.array(Ge)}),Fe=P,Ne=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"]),Le=t.z.object({kind:Ne,message:t.z.string()}),Ke=t.z.enum(["sum","avg","count","min","max"]),He=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:Ke,chartType:U,score:t.z.number(),message:t.z.string()}),We=t.z.object({ranking:t.z.array(qe),observations:t.z.array(Le).optional().default([]),suggestions:t.z.array(He).optional().default([]),run:A.optional()}),Ye=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()}),Je=t.z.object({config:z.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:Ye.optional(),userPrompt:t.z.string().optional(),metadata:C.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ve=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Qe=t.z.enum(["info","low","medium","high"]),Ze=t.z.object({category:Ve,severity:Qe,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),et=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Ze)}),tt=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()}),nt=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),at=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:et.nullable(),chartVisionAudit:nt.nullable().optional().default(null),rubricScores:tt.nullable().optional().default(null),run:A.optional()}).extend(f),rt="/api/v0";exports.AggregationFunctionSchema=Ke,exports.AggregationSuggestionSchema=He,exports.AiChartTypeEnum=U,exports.AttachmentResponseSchema=Ae,exports.AttachmentUploadResponseSchema=Re,exports.AttachmentUploadSlotResponseSchema=Me,exports.ChartCritiqueIssueCategorySchema=Ve,exports.ChartCritiqueIssueSchema=Ze,exports.ChartCritiqueIssueSeveritySchema=Qe,exports.ChartCritiqueReportSchema=et,exports.ChartFamilySchema=k,exports.ChartFitEntrySchema=qe,exports.ChartFitFactorKindSchema=Be,exports.ChartFitFactorSchema=Ge,exports.ChartFitVerdictSchema=Xe,exports.ChartJudgeRubricSchema=Ye,exports.CreateAttachmentUploadsParamsSchema=$e,exports.CreateAttachmentUploadsResponseSchema=Oe,exports.DataObservationKindSchema=Ne,exports.DataObservationSchema=Le,exports.EvaluateParamsSchema=Fe,exports.EvaluateResponseSchema=We,exports.ExecutionModeSchema=_,exports.ExploreFindingSchema=q,exports.ExploreStorySchema=F,exports.ExtractAccuracyEvaluationSchema=Z,exports.ExtractAttachmentInputSchema=Ee,exports.ExtractAttachmentKindSchema=_e,exports.ExtractConfidenceSchema=V,exports.ExtractFromProseParamsSchema=Pe,exports.ExtractFromProseResponseSchema=De,exports.ExtractMetaSchema=Q,exports.GenerateAnnotationsResponseSchema=L,exports.GenerateExplorationResponseSchema=N,exports.GenerateGraphResponseSchema=Ue,exports.GenerateGraphSuggestionsResponseSchema=Ie,exports.GenerateMutationResponseSchema=K,exports.GenerateNarrativeParamsSchema=B,exports.GenerateNarrativeResponseSchema=G,exports.GeneratePipelineParamsSchema=Y,exports.GeneratePipelineResponseSchema=J,exports.GenerateSuggestionsParamsSchema=D,exports.GenerateSuggestionsResponseSchema=X,exports.GraphGenerationRequestSchema=P,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:r}=t,o=e.__rest(t,["storytellingOptions"]),i=yield this.client.fetch(`${rt}/generate`,o,n,a),s=Ue.parse(i);return this.stripStorytelling(s,r)})}generateGraphStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,r=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${rt}/generate`,r,n);return this.wrapStreamWithStorytellingStripping(o,a)})}generateNarrative(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/narrate`,t,n,a);return G.parse(e)})}generateNarrativeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/narrate`,t,n)})}generateSuggestions(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/suggestions`,t,n,a);return X.parse(e)})}generateSuggestionsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/suggestions`,t,n)})}generateExploration(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/explore`,t,n,a);return N.parse(e)})}generateExplorationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/explore`,t,n)})}generateAnnotations(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/annotate`,t,n,a);return L.parse(e)})}generateAnnotationsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/annotate`,t,n)})}generateMutation(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/mutate`,t,n,a);return K.parse(e)})}generateMutationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/mutate`,t,n)})}generatePipeline(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/pipeline`,t,n,a);return J.parse(e)})}generatePipelineStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/pipeline`,t,n)})}evaluate(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/evaluate`,t,void 0,n);return We.parse(e)})}judge(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/judge`,t,void 0,n);return at.parse(e)})}judgeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/judge`,t,n)})}extractFromProse(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/extract`,t,n,a);return De.parse(e)})}extractFromProseStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/extract`,t,n)})}uploadAttachment(t,a,r){return e.__awaiter(this,void 0,void 0,function*(){const e=m(t,a),o=l(t,a),{uploads:i}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},o?{filename:o}:{}),t.size>0?{sizeBytes:t.size}:{})]},r),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:r});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,r);return Re.parse(p)})}uploadDataset(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=u(t,n);return this.uploadAttachment(t,Object.assign(Object.assign({},n),{mimeType:e}),a)})}createAttachmentUploads(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${rt}/attachment-uploads`,t,n);return Oe.parse(e)})}completeAttachmentUpload(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${rt}/attachments/${t}/complete`,{},n);return Ae.parse(e)})}getAttachment(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.get(`${rt}/attachments/${t}`,n);return Ae.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 a,o,i,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(a=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(r(t)){const a=this.stripStorytelling(t.data,n);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||a||!(i=m.return)||(yield e.__await(i.call(m)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=n,exports.InvocationBudgetSchema=T,exports.InvocationEffortSchema=x,exports.JudgeParamsSchema=Je,exports.JudgeResponseSchema=at,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=S,exports.MAX_BUDGET_WALL_CLOCK_MS=w,exports.MAX_EXTRACT_ATTACHMENTS=ce,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=se,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=re,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=ae,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=ne,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=te,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=ie,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=oe,exports.MAX_SOURCE_TEXT_LENGTH=ee,exports.MAX_STAGED_FILE_BYTES=le,exports.MAX_USER_PROMPT_LENGTH=R,exports.MetadataSchema=C,exports.MutateNarrationReceiptSchema=j,exports.PipelineAgentNameSchema=H,exports.PipelineStageReasoningSchema=W,exports.RubricScoresSchema=tt,exports.RunContextSchema=A,exports.StorytellingEffortSchema=v,exports.SuggestionSchema=I,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ye(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ye(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ye(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isAgentCompleteEvent=e=>"agent_complete"===e.type,exports.isCompleteEvent=r,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof n,exports.isLlmStepEvent=e=>"llm_step"===e.type,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,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 a=e=>"progress"===e.type,r=e=>"complete"===e.type,i=e=>"error"===e.type;function o(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){this.tag="[GRAPHY]";if(!("include"===e.credentials||e.apiKey&&0!==e.apiKey.trim().length))throw new Error('apiKey is required and must not be empty (unless credentials: "include" is set for cookie auth)');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.credentials=e.credentials,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 a(e)}static isCompleteEvent(e){return r(e)}static isErrorEvent(e){return i(e)}stream(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,a);return this.parseSSE(e)})}fetch(t,o,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,d,u;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const y=yield this.makeRequest(t,o,c),z=y.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var g,f=!0,b=e.__asyncValues(this.parseSSE(y));!(l=(g=yield b.next()).done);f=!0){d=g.value,f=!1;const e=d;if(a(e)&&s&&s(e),r(e))return e.data;if(i(e)){const a=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new n(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){m={error:e}}finally{try{f||l||!(p=b.return)||(yield p.call(b))}finally{if(m)throw m.error}}const o=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${o}ms`),new n("Stream ended without completion")}return yield y.json()}catch(e){const a=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof n)throw e;throw e}finally{const e=Date.now()-h;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,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,a);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,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,a,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 a=t.body.getReader(),r=new TextDecoder;let i="",s="",c="";try{for(;;){const{done:t,value:n}=yield e.__await(a.read());if(t)break;i+=r.decode(n,{stream:!0});const l=i.split(/\r?\n/);i=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=o(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{a.releaseLock()}})}makeRequest(t,a,r){return e.__awaiter(this,arguments,void 0,function*(e,t,a,r=1,i="POST"){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");this.logger.debug(`${this.tag} Request ${r}/${this.retryConfig.attempts}: ${o}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();a&&a.addEventListener("abort",l);try{const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache","User-Agent":"Graphy-SDK/1.0"};this.apiKey&&(c.Authorization=`Bearer ${this.apiKey}`);const l=yield fetch(o,Object.assign(Object.assign({method:i,headers:c,signal:s.signal},this.credentials?{credentials:this.credentials}:{}),"POST"===i&&{body:JSON.stringify(t)}));if(!l.ok){let o,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&&(o=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===o)&&(l.status>=500||429===l.status),m=new n(s,{status:l.status,code:o,retryable:c});if(c&&r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${n}ms (attempt ${r+1})`),yield this.sleep(n),this.makeRequest(e,t,a,r+1,i)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(o){if(o instanceof n)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),o;if(r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${n}ms`),yield this.sleep(n),this.makeRequest(e,t,a,r+1,i)}throw this.logger.error(`${this.tag} Network error: ${e}`,o),new n("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",l)}})}makeMultipartRequest(t,a,r){return e.__awaiter(this,arguments,void 0,function*(e,t,a,r=1){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");const o=new AbortController,s=setTimeout(()=>o.abort(),this.timeout),c=()=>o.abort();a&&a.addEventListener("abort",c);try{const s={Accept:"application/json","User-Agent":"Graphy-SDK/1.0"};this.apiKey&&(s.Authorization=`Bearer ${this.apiKey}`);const c=yield fetch(i,Object.assign({method:"POST",headers:s,body:t,signal:o.signal},this.credentials?{credentials:this.credentials}:{}));if(!c.ok){let i,o=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error),"string"==typeof t.code&&(i=t.code)}}catch(e){}const s=c.status>=500||429===c.status,l=new n(o,{status:c.status,code:i,retryable:s});if(s&&r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,a,r+1)}throw l}return c}catch(i){if(i instanceof n)throw i;if(i instanceof Error&&"AbortError"===i.name)throw i;if(r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,a,r+1)}throw new n("Network error",{retryable:!0})}finally{clearTimeout(s),a&&a.removeEventListener("abort",c)}})}}const c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".csv":"text/csv",".tsv":"text/tab-separated-values",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function l(e,t){var n;const a=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return a||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function m(e,t){var n;const a=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(a)return a;const r=e.type.trim();if(r.length>0)return r;const i=l(e,t);if(i){const e=function(e){const t=e.lastIndexOf(".");if(t<0)return;const n=e.slice(t).toLowerCase();return c[n]}(i);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, .csv, .tsv, .xlsx, …)")}const p=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);function d(e,t){const n=m(e,t);if(a=n,!p.has(a.trim()))throw new Error("uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)");var a;return n}const u=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()}),h=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()}),g=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:h,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 f={usage:u.optional(),budget:g.optional()};function b(e,t){const n=void 0!==e.config.data,a=function(e){const{data:t}=e;return void 0!==t&&(t.columns.length>0||t.rows.length>0)}(e.config),r=void 0!==e.datasetRef&&e.datasetRef.trim().length>0;a&&r&&t.addIssue({code:"custom",message:"Provide either config.data or datasetRef, not both",path:["datasetRef"]}),n||r||t.addIssue({code:"custom",message:"Provide config.data or datasetRef",path:["datasetRef"]})}const y=t.z.enum(["EN_GB","EN_US"]),z=t.z.custom(e=>null!=e&&"object"==typeof e),x=t.z.enum(["low","medium","high"]),v=t.z.enum(["none","low","medium","high"]),_=t.z.enum(["agentic","fast"]),w=3e5,S=5e5,T=t.z.object({maxWallClockMs:t.z.number().positive().max(w).optional(),maxTotalTokens:t.z.number().int().positive().max(S).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),E=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:T,consumed:E,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});const C=t.z.object({callId:t.z.string().max(256).optional(),locale:y.optional(),effort:x.optional(),storytellingEffort:v.optional().default("low"),budget:T.optional(),executionMode:_.optional(),enforceTableRowCap:t.z.boolean().optional()}),j=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()}),A=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),k=1e4,R=t.z.enum(["comparison","relationship","distribution","composition"]),$=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,M=t.z.string().regex($,"datasetRef must be graphy://attachments/{uuid}"),O=t.z.object({config:z,userPrompt:t.z.string().max(k).optional().default(""),metadata:C.optional(),chartFamily:R.optional(),datasetRef:M.optional()}),P=O.superRefine(b),D=O.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}).superRefine(b),U=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),I=t.z.object({dataPrepPrompt:t.z.string(),chartType:U,summary:t.z.string()}),B=O.extend({userPrompt:t.z.string().max(k),mutationReceipt:j.optional(),exploreFindingSummary:t.z.string().max(500).optional()}).superRefine(b),G=t.z.object({response:t.z.object({message:t.z.string()}),config:z,run:A.optional()}).extend(f),X=t.z.object({suggestions:t.z.array(I),run:A.optional()}).extend(f),q=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:R.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.")}),F=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(q).describe("Child findings, sorted by quadrant score desc.")}),N=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(F),run:A.optional()}).extend(f);O.extend({mutationReceipt:j.optional()}).superRefine(b);const L=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:z,run:A.optional()}).extend(f),K=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:z,mutationReceipt:j.optional(),warnings:t.z.array(t.z.string()).optional(),run:A.optional()}).extend(f),H=t.z.enum(["explore","mutate","narrate","annotate"]),W=t.z.object({agent:H,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),Y=O.extend({userPrompt:t.z.string().max(k),stages:t.z.array(H).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}).superRefine(b),J=K.extend({reasoning:t.z.array(W),stories:t.z.array(F).optional()}),V=t.z.enum(["high","medium","low"]),Q=t.z.object({confidence:V,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:V,quote:t.z.string().optional()})).optional()}),Z=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()}),ee=5e5,te=2097152,ne=7340032,ae=6291456,re=8388608,ie=ae,oe=re,se=12582912,ce=12,le=52428800;function me(e){return 4*Math.ceil(e/3)}const pe=me(te),de=me(ne),ue=me(ae),he=me(re),ge=me(ie),fe=me(oe),be=me(se);function ye(e){return e.replace(/\s+/g,"")}function ze(e){const t=ye(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const xe=/^image\/(png|jpeg|jpg|webp|gif)$/i,ve=t.z.object({mimeType:t.z.string().min(1).refine(e=>xe.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(pe).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),_e=t.z.enum(["image","document","spreadsheet","tabular"]),we=ve.extend({kind:t.z.literal("image")}),Se=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(ue).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Te=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(ge).refine(ze,{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"]}),Ee=t.z.discriminatedUnion("kind",[we,Se,Te]),Ce=t.z.string().regex($,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),je=t.z.enum(["pending","ready","failed"]),Ae=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),status:je,kind:_e.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()}),ke=Ae.extend({status:t.z.literal("ready"),kind:_e,sizeBytes:t.z.number().int().positive()}),Re=t.z.object({mimeType:t.z.string().min(1),filename:t.z.string().max(512).optional(),sizeBytes:t.z.number().int().positive().max(le).optional()}),$e=t.z.object({files:t.z.array(Re).min(1).max(ce)}),Me=Ae.extend({status:t.z.literal("pending"),uploadUrl:t.z.string().url()}),Oe=t.z.object({uploads:t.z.array(Me)}),Pe=t.z.object({sourceText:t.z.string().max(ee).default(""),images:t.z.array(ve).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(Ee).max(ce).optional(),attachmentRefs:t.z.array(Ce).max(ce).optional(),metadata:C.optional()}).superRefine((e,t)=>{var n,a,r;const i=e.sourceText.trim(),o=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(a=e.attachments)&&void 0!==a?a:[],c=null!==(r=e.attachmentRefs)&&void 0!==r?r:[];if(o.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===i.length&&0===o.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(o.length+s.length+c.length>ce)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===o.length)return;if(o.length>0){o.reduce((e,t)=>e+ye(t.dataBase64).length,0)>de&&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,d=0,u=0,h=0,g=0;for(const e of s){const t=ye(e.dataBase64).length;switch(g+=t,e.kind){case"image":l+=1,d+=t;break;case"document":m+=1,u+=t;break;case"spreadsheet":p+=1,h+=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&&(d>de&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>he&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>fe&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>be&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const De=t.z.object({response:t.z.object({message:t.z.string()}),config:z,extractMeta:Q.nullable(),lastAccuracyEvaluation:Z.optional(),run:A.optional()}).extend(f),Ue=t.z.object({config:z,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:A.optional()}).extend(f),Ie=X,Be=t.z.enum(["deal-breaker","pro","con","family","continuity"]),Ge=t.z.object({kind:Be,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),Xe=t.z.enum(["ok","disqualified"]),qe=t.z.object({rank:t.z.number().int().positive(),type:U,score:t.z.number(),verdict:Xe,factors:t.z.array(Ge)}),Fe=P,Ne=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"]),Le=t.z.object({kind:Ne,message:t.z.string()}),Ke=t.z.enum(["sum","avg","count","min","max"]),He=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:Ke,chartType:U,score:t.z.number(),message:t.z.string()}),We=t.z.object({ranking:t.z.array(qe),observations:t.z.array(Le).optional().default([]),suggestions:t.z.array(He).optional().default([]),run:A.optional()}),Ye=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()}),Je=t.z.object({config:z.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:Ye.optional(),userPrompt:t.z.string().optional(),metadata:C.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ve=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Qe=t.z.enum(["info","low","medium","high"]),Ze=t.z.object({category:Ve,severity:Qe,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),et=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Ze)}),tt=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()}),nt=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),at=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:et.nullable(),chartVisionAudit:nt.nullable().optional().default(null),rubricScores:tt.nullable().optional().default(null),run:A.optional()}).extend(f),rt="/api/v0";exports.AggregationFunctionSchema=Ke,exports.AggregationSuggestionSchema=He,exports.AiChartTypeEnum=U,exports.AttachmentResponseSchema=Ae,exports.AttachmentUploadResponseSchema=ke,exports.AttachmentUploadSlotResponseSchema=Me,exports.ChartCritiqueIssueCategorySchema=Ve,exports.ChartCritiqueIssueSchema=Ze,exports.ChartCritiqueIssueSeveritySchema=Qe,exports.ChartCritiqueReportSchema=et,exports.ChartFamilySchema=R,exports.ChartFitEntrySchema=qe,exports.ChartFitFactorKindSchema=Be,exports.ChartFitFactorSchema=Ge,exports.ChartFitVerdictSchema=Xe,exports.ChartJudgeRubricSchema=Ye,exports.CreateAttachmentUploadsParamsSchema=$e,exports.CreateAttachmentUploadsResponseSchema=Oe,exports.DataObservationKindSchema=Ne,exports.DataObservationSchema=Le,exports.EvaluateParamsSchema=Fe,exports.EvaluateResponseSchema=We,exports.ExecutionModeSchema=_,exports.ExploreFindingSchema=q,exports.ExploreStorySchema=F,exports.ExtractAccuracyEvaluationSchema=Z,exports.ExtractAttachmentInputSchema=Ee,exports.ExtractAttachmentKindSchema=_e,exports.ExtractConfidenceSchema=V,exports.ExtractFromProseParamsSchema=Pe,exports.ExtractFromProseResponseSchema=De,exports.ExtractMetaSchema=Q,exports.GenerateAnnotationsResponseSchema=L,exports.GenerateExplorationResponseSchema=N,exports.GenerateGraphResponseSchema=Ue,exports.GenerateGraphSuggestionsResponseSchema=Ie,exports.GenerateMutationResponseSchema=K,exports.GenerateNarrativeParamsSchema=B,exports.GenerateNarrativeResponseSchema=G,exports.GeneratePipelineParamsSchema=Y,exports.GeneratePipelineResponseSchema=J,exports.GenerateSuggestionsParamsSchema=D,exports.GenerateSuggestionsResponseSchema=X,exports.GraphGenerationRequestSchema=P,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:r}=t,i=e.__rest(t,["storytellingOptions"]),o=yield this.client.fetch(`${rt}/generate`,i,n,a),s=Ue.parse(o);return this.stripStorytelling(s,r)})}generateGraphStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,r=e.__rest(t,["storytellingOptions"]),i=yield this.client.stream(`${rt}/generate`,r,n);return this.wrapStreamWithStorytellingStripping(i,a)})}generateNarrative(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/narrate`,t,n,a);return G.parse(e)})}generateNarrativeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/narrate`,t,n)})}generateSuggestions(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/suggestions`,t,n,a);return X.parse(e)})}generateSuggestionsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/suggestions`,t,n)})}generateExploration(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/explore`,t,n,a);return N.parse(e)})}generateExplorationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/explore`,t,n)})}generateAnnotations(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/annotate`,t,n,a);return L.parse(e)})}generateAnnotationsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/annotate`,t,n)})}generateMutation(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/mutate`,t,n,a);return K.parse(e)})}generateMutationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/mutate`,t,n)})}generatePipeline(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/pipeline`,t,n,a);return J.parse(e)})}generatePipelineStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/pipeline`,t,n)})}evaluate(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/evaluate`,t,void 0,n);return We.parse(e)})}judge(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/judge`,t,void 0,n);return at.parse(e)})}judgeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/judge`,t,n)})}extractFromProse(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/extract`,t,n,a);return De.parse(e)})}extractFromProseStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/extract`,t,n)})}uploadAttachment(t,a,r){return e.__awaiter(this,void 0,void 0,function*(){const e=m(t,a),i=l(t,a),{uploads:o}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},i?{filename:i}:{}),t.size>0?{sizeBytes:t.size}:{})]},r),s=o[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:r});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,r);return ke.parse(p)})}uploadDataset(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=d(t,n);return this.uploadAttachment(t,Object.assign(Object.assign({},n),{mimeType:e}),a)})}createAttachmentUploads(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${rt}/attachment-uploads`,t,n);return Oe.parse(e)})}completeAttachmentUpload(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${rt}/attachments/${t}/complete`,{},n);return Ae.parse(e)})}getAttachment(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.get(`${rt}/attachments/${t}`,n);return Ae.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 a,i,o,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(a=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(r(t)){const a=this.stripStorytelling(t.data,n);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){i={error:e}}finally{try{l||a||!(o=m.return)||(yield e.__await(o.call(m)))}finally{if(i)throw i.error}}})}},exports.GraphyApiError=n,exports.InvocationBudgetSchema=T,exports.InvocationEffortSchema=x,exports.JudgeParamsSchema=Je,exports.JudgeResponseSchema=at,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=S,exports.MAX_BUDGET_WALL_CLOCK_MS=w,exports.MAX_EXTRACT_ATTACHMENTS=ce,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=se,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=re,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=ae,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=ne,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=te,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=oe,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=ie,exports.MAX_SOURCE_TEXT_LENGTH=ee,exports.MAX_STAGED_FILE_BYTES=le,exports.MAX_USER_PROMPT_LENGTH=k,exports.MetadataSchema=C,exports.MutateNarrationReceiptSchema=j,exports.PipelineAgentNameSchema=H,exports.PipelineStageReasoningSchema=W,exports.RubricScoresSchema=tt,exports.RunContextSchema=A,exports.StorytellingEffortSchema=v,exports.SuggestionSchema=I,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ye(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ye(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ye(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isAgentCompleteEvent=e=>"agent_complete"===e.type,exports.isCompleteEvent=r,exports.isErrorEvent=i,exports.isGraphyApiError=e=>e instanceof n,exports.isLlmStepEvent=e=>"llm_step"===e.type,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,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
|
@@ -228,10 +228,21 @@ interface RetryConfig {
|
|
|
228
228
|
* ```
|
|
229
229
|
*/
|
|
230
230
|
interface ClientConfig {
|
|
231
|
-
/**
|
|
232
|
-
|
|
231
|
+
/**
|
|
232
|
+
* API key for authenticating requests, sent as `Authorization: Bearer <key>`. Optional when
|
|
233
|
+
* {@link ClientConfig.credentials} is `'include'` for browser cookie auth: with no key the
|
|
234
|
+
* `Authorization` header is omitted so agents-api falls through to the session cookie (a
|
|
235
|
+
* present-but-invalid Bearer is rejected outright and never falls back to the cookie).
|
|
236
|
+
*/
|
|
237
|
+
apiKey?: string;
|
|
233
238
|
/** Base URL of the Graphy Agents API (e.g. `"https://agents.graphy.dev"`). */
|
|
234
239
|
baseUrl: string;
|
|
240
|
+
/**
|
|
241
|
+
* `fetch` credentials mode. Set to `'include'` for browser callers that authenticate with the
|
|
242
|
+
* agents-api session cookie (cross-origin requires credentialed CORS on the API). Left unset for
|
|
243
|
+
* the default same-origin behavior used by Bearer-key callers.
|
|
244
|
+
*/
|
|
245
|
+
credentials?: RequestCredentials;
|
|
235
246
|
/**
|
|
236
247
|
* Request timeout in milliseconds.
|
|
237
248
|
* @defaultValue 60000
|
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,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",".csv":"text/csv",".tsv":"text/tab-separated-values",".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, .csv, .tsv, .xlsx, …)")}const T=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);function $(e,t){const n=k(e,t);if(i=n,!T.has(i.trim()))throw new Error("uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)");var i;return n}const S=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()}),C=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=r.object({limits:r.object({maxWallClockMs:r.number().optional(),maxTotalTokens:r.number().optional(),maxCostUsd:r.number().optional(),trackUsage:r.boolean().optional()}),consumed:C,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 E={usage:S.optional(),budget:R.optional()};function U(e,t){const n=void 0!==e.config.data,i=function(e){const{data:t}=e;return void 0!==t&&(t.columns.length>0||t.rows.length>0)}(e.config),o=void 0!==e.datasetRef&&e.datasetRef.trim().length>0;i&&o&&t.addIssue({code:"custom",message:"Provide either config.data or datasetRef, not both",path:["datasetRef"]}),n||o||t.addIssue({code:"custom",message:"Provide config.data or datasetRef",path:["datasetRef"]})}const A=r.enum(["EN_GB","EN_US"]),I=r.custom(e=>null!=e&&"object"==typeof e),O=r.enum(["low","medium","high"]),P=r.enum(["none","low","medium","high"]),M=r.enum(["agentic","fast"]),B=3e5,q=5e5,D=10,F=r.object({maxWallClockMs:r.number().positive().max(B).optional(),maxTotalTokens:r.number().int().positive().max(q).optional(),maxCostUsd:r.number().positive().max(10).optional(),trackUsage:r.boolean().optional()}),_=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:F,consumed:_,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});const N=r.object({callId:r.string().max(256).optional(),locale:A.optional(),effort:O.optional(),storytellingEffort:P.optional().default("low"),budget:F.optional(),executionMode:M.optional(),enforceTableRowCap:r.boolean().optional()}),K=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()}),L=r.object({runId:r.string(),trackingId:r.string(),callId:r.string().optional()}),z=1e4,G=r.enum(["comparison","relationship","distribution","composition"]),W=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,H=r.string().regex(W,"datasetRef must be graphy://attachments/{uuid}"),J=r.object({config:I,userPrompt:r.string().max(z).optional().default(""),metadata:N.optional(),chartFamily:G.optional(),datasetRef:H.optional()}),X=J.superRefine(U),Q=J.extend({maxSuggestionCount:r.number().int().min(1).max(4).optional()}).superRefine(U),V=r.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),Y=r.object({dataPrepPrompt:r.string(),chartType:V,summary:r.string()}),Z=J.extend({userPrompt:r.string().max(z),mutationReceipt:K.optional(),exploreFindingSummary:r.string().max(500).optional()}).superRefine(U),ee=r.object({response:r.object({message:r.string()}),config:I,run:L.optional()}).extend(E),te=r.object({suggestions:r.array(Y),run:L.optional()}).extend(E),ne=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:G.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.")}),ie=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(ne).describe("Child findings, sorted by quadrant score desc.")}),oe=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),stories:r.array(ie),run:L.optional()}).extend(E);J.extend({mutationReceipt:K.optional()}).superRefine(U);const re=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:I,run:L.optional()}).extend(E),ae=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:I,mutationReceipt:K.optional(),warnings:r.array(r.string()).optional(),run:L.optional()}).extend(E),se=r.enum(["explore","mutate","narrate","annotate"]),le=r.object({agent:se,summary:r.string(),steps:r.array(r.string()).optional()}),ce=J.extend({userPrompt:r.string().max(z),stages:r.array(se).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:r.string().max(500).optional()}).superRefine(U),me=ae.extend({reasoning:r.array(le),stories:r.array(ie).optional()}),de=r.enum(["high","medium","low"]),ue=r.object({confidence:de,needsUserInput:r.boolean(),warnings:r.array(r.string()),cellConfidence:r.array(r.object({rowIndex:r.number().int().nonnegative(),columnKey:r.string(),confidence:de,quote:r.string().optional()})).optional()}),pe=r.object({score:r.number().min(0).max(1),issues:r.array(r.string()),sufficient:r.boolean(),summary:r.string()}),ge=5e5,he=8,fe=2097152,be=7340032,ye=2,ve=6291456,xe=8388608,we=2,je=ve,ke=xe,Te=12582912,$e=12,Se=52428800;function Ce(e){return 4*Math.ceil(e/3)}const Re=Ce(fe),Ee=Ce(be),Ue=Ce(ve),Ae=Ce(xe),Ie=Ce(je),Oe=Ce(ke),Pe=Ce(Te);function Me(e){return e.replace(/\s+/g,"")}function Be(e){const t=Me(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const qe=/^image\/(png|jpeg|jpg|webp|gif)$/i,De=r.object({mimeType:r.string().min(1).refine(e=>qe.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:r.string().min(1).max(Re).refine(Be,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Fe=r.enum(["image","document","spreadsheet","tabular"]),_e=De.extend({kind:r.literal("image")}),Ne=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(Ue).refine(Be,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Ke=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(Ie).refine(Be,{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"]}),Le=r.discriminatedUnion("kind",[_e,Ne,Ke]),ze=r.string().regex(W,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),Ge=r.enum(["pending","ready","failed"]),We=r.object({id:r.string().uuid(),uri:r.string(),status:Ge,kind:Fe.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()}),He=We.extend({status:r.literal("ready"),kind:Fe,sizeBytes:r.number().int().positive()}),Je=r.object({mimeType:r.string().min(1),filename:r.string().max(512).optional(),sizeBytes:r.number().int().positive().max(Se).optional()}),Xe=r.object({files:r.array(Je).min(1).max($e)}),Qe=We.extend({status:r.literal("pending"),uploadUrl:r.string().url()}),Ve=r.object({uploads:r.array(Qe)}),Ye=r.object({sourceText:r.string().max(ge).default(""),images:r.array(De).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:r.array(Le).max($e).optional(),attachmentRefs:r.array(ze).max($e).optional(),metadata:N.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>$e)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+Me(t.dataBase64).length,0)>Ee&&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=Me(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>Ee&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>Ae&&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>Pe&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function Ze(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:Me(e.dataBase64)}}function et(e){return{kind:"document",mimeType:"application/pdf",dataBase64:Me(e.dataBase64)}}function tt(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:Me(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const nt=r.object({response:r.object({message:r.string()}),config:I,extractMeta:ue.nullable(),lastAccuracyEvaluation:pe.optional(),run:L.optional()}).extend(E),it=r.object({config:I,response:r.object({message:r.string(),steps:r.array(r.string())}),run:L.optional()}).extend(E),ot=te,rt=r.enum(["deal-breaker","pro","con","family","continuity"]),at=r.object({kind:rt,label:r.string(),weight:r.number(),reason:r.string()}),st=r.enum(["ok","disqualified"]),lt=r.object({rank:r.number().int().positive(),type:V,score:r.number(),verdict:st,factors:r.array(at)}),ct=X,mt=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"]),dt=r.object({kind:mt,message:r.string()}),ut=r.enum(["sum","avg","count","min","max"]),pt=r.object({dimensionName:r.string(),dimensionLabel:r.string(),measureName:r.string().nullable(),measureLabel:r.string().nullable(),fn:ut,chartType:V,score:r.number(),message:r.string()}),gt=r.object({ranking:r.array(lt),observations:r.array(dt).optional().default([]),suggestions:r.array(pt).optional().default([]),run:L.optional()}),ht=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()}),ft=r.object({config:I.optional(),chartImage:r.string().optional(),data:r.unknown().optional(),rubric:ht.optional(),userPrompt:r.string().optional(),metadata:N.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),bt=r.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),yt=r.enum(["info","low","medium","high"]),vt=r.object({category:bt,severity:yt,observation:r.string(),rationale:r.string().optional(),suggestedChange:r.string().optional(),configPaths:r.array(r.string()).optional()}),xt=r.object({overallSummary:r.string(),overallSeverity:r.enum(["none","low","medium","high"]).optional(),issues:r.array(vt)}),wt=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()}),jt=r.object({capturedAt:r.string(),chartId:r.string()}),kt=r.object({response:r.object({message:r.string(),steps:r.array(r.string()),critiqueCommitted:r.boolean()}),critiqueReport:xt.nullable(),chartVisionAudit:jt.nullable().optional().default(null),rubricScores:wt.nullable().optional().default(null),run:L.optional()}).extend(E),Tt="/api/v0";class $t{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(`${Tt}/generate`,r,n,i),s=it.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(`${Tt}/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(`${Tt}/narrate`,t,n,i);return ee.parse(e)})}generateNarrativeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/narrate`,t,n)})}generateSuggestions(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/suggestions`,t,n,i);return te.parse(e)})}generateSuggestionsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/suggestions`,t,n)})}generateExploration(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/explore`,t,n,i);return oe.parse(e)})}generateExplorationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/explore`,t,n)})}generateAnnotations(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/annotate`,t,n,i);return re.parse(e)})}generateAnnotationsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/annotate`,t,n)})}generateMutation(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/mutate`,t,n,i);return ae.parse(e)})}generateMutationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/mutate`,t,n)})}generatePipeline(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/pipeline`,t,n,i);return me.parse(e)})}generatePipelineStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/pipeline`,t,n)})}evaluate(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/evaluate`,t,void 0,n);return gt.parse(e)})}judge(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/judge`,t,void 0,n);return kt.parse(e)})}judgeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/judge`,t,n)})}extractFromProse(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/extract`,t,n,i);return nt.parse(e)})}extractFromProseStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/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 He.parse(c)})}uploadDataset(t,n,i){return e(this,void 0,void 0,function*(){const e=$(t,n);return this.uploadAttachment(t,Object.assign(Object.assign({},n),{mimeType:e}),i)})}createAttachmentUploads(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Tt}/attachment-uploads`,t,n);return Ve.parse(e)})}completeAttachmentUpload(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Tt}/attachments/${t}/complete`,{},n);return We.parse(e)})}getAttachment(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.get(`${Tt}/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(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{ut as AggregationFunctionSchema,pt as AggregationSuggestionSchema,V as AiChartTypeEnum,We as AttachmentResponseSchema,He as AttachmentUploadResponseSchema,Qe as AttachmentUploadSlotResponseSchema,bt as ChartCritiqueIssueCategorySchema,vt as ChartCritiqueIssueSchema,yt as ChartCritiqueIssueSeveritySchema,xt as ChartCritiqueReportSchema,G as ChartFamilySchema,lt as ChartFitEntrySchema,rt as ChartFitFactorKindSchema,at as ChartFitFactorSchema,st as ChartFitVerdictSchema,ht as ChartJudgeRubricSchema,Xe as CreateAttachmentUploadsParamsSchema,Ve as CreateAttachmentUploadsResponseSchema,mt as DataObservationKindSchema,dt as DataObservationSchema,ct as EvaluateParamsSchema,gt as EvaluateResponseSchema,M as ExecutionModeSchema,ne as ExploreFindingSchema,ie as ExploreStorySchema,pe as ExtractAccuracyEvaluationSchema,Le as ExtractAttachmentInputSchema,Fe as ExtractAttachmentKindSchema,de as ExtractConfidenceSchema,Ye as ExtractFromProseParamsSchema,nt as ExtractFromProseResponseSchema,ue as ExtractMetaSchema,re as GenerateAnnotationsResponseSchema,oe as GenerateExplorationResponseSchema,it as GenerateGraphResponseSchema,ot as GenerateGraphSuggestionsResponseSchema,ae as GenerateMutationResponseSchema,Z as GenerateNarrativeParamsSchema,ee as GenerateNarrativeResponseSchema,ce as GeneratePipelineParamsSchema,me as GeneratePipelineResponseSchema,Q as GenerateSuggestionsParamsSchema,te as GenerateSuggestionsResponseSchema,X as GraphGenerationRequestSchema,$t as GraphyAiSdk,a as GraphyApiError,F as InvocationBudgetSchema,O as InvocationEffortSchema,ft as JudgeParamsSchema,kt as JudgeResponseSchema,D as MAX_BUDGET_COST_USD,q as MAX_BUDGET_TOTAL_TOKENS,B as MAX_BUDGET_WALL_CLOCK_MS,$e as MAX_EXTRACT_ATTACHMENTS,Te as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,ye as MAX_EXTRACT_DOCUMENTS,xe as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,ve as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,he as MAX_EXTRACT_IMAGES,be as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,fe as MAX_EXTRACT_IMAGE_DECODED_BYTES,we as MAX_EXTRACT_SPREADSHEETS,ke as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,je as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,ge as MAX_SOURCE_TEXT_LENGTH,Se as MAX_STAGED_FILE_BYTES,z as MAX_USER_PROMPT_LENGTH,N as MetadataSchema,K as MutateNarrationReceiptSchema,se as PipelineAgentNameSchema,le as PipelineStageReasoningSchema,wt as RubricScoresSchema,L as RunContextSchema,P as StorytellingEffortSchema,Y as SuggestionSchema,Ze as buildImageAttachment,et as buildPdfAttachment,tt 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};
|
|
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,d=e=>"error"===e.type,m=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){this.tag="[GRAPHY]";if(!("include"===e.credentials||e.apiKey&&0!==e.apiKey.trim().length))throw new Error('apiKey is required and must not be empty (unless credentials: "include" is set for cookie auth)');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.credentials=e.credentials,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 d(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,m,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(d(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||!(m=b.return)||(yield m.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={"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache","User-Agent":"Graphy-SDK/1.0"};this.apiKey&&(l.Authorization=`Bearer ${this.apiKey}`);const c=yield fetch(r,Object.assign(Object.assign({method:o,headers:l,signal:s.signal},this.credentials?{credentials:this.credentials}:{}),"POST"===o&&{body:JSON.stringify(t)}));if(!c.ok){let r,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&&(r=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===r)&&(c.status>=500||429===c.status),d=new a(s,{status:c.status,code:r,retryable:l});if(l&&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} (${c.status}) - ${s}`),d}return this.logger.debug(`${this.tag} Connected: ${e}`),c}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={Accept:"application/json","User-Agent":"Graphy-SDK/1.0"};this.apiKey&&(s.Authorization=`Bearer ${this.apiKey}`);const l=yield fetch(o,Object.assign({method:"POST",headers:s,body:t,signal:r.signal},this.credentials?{credentials:this.credentials}:{}));if(!l.ok){let o,r=`HTTP ${l.status}`;try{const e=yield l.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 s=l.status>=500||429===l.status,c=new a(r,{status:l.status,code:o,retryable:s});if(s&&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 l}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",".csv":"text/csv",".tsv":"text/tab-separated-values",".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, .csv, .tsv, .xlsx, …)")}const T=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);function $(e,t){const n=k(e,t);if(i=n,!T.has(i.trim()))throw new Error("uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)");var i;return n}const S=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()}),C=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=r.object({limits:r.object({maxWallClockMs:r.number().optional(),maxTotalTokens:r.number().optional(),maxCostUsd:r.number().optional(),trackUsage:r.boolean().optional()}),consumed:C,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 E={usage:S.optional(),budget:R.optional()};function U(e,t){const n=void 0!==e.config.data,i=function(e){const{data:t}=e;return void 0!==t&&(t.columns.length>0||t.rows.length>0)}(e.config),o=void 0!==e.datasetRef&&e.datasetRef.trim().length>0;i&&o&&t.addIssue({code:"custom",message:"Provide either config.data or datasetRef, not both",path:["datasetRef"]}),n||o||t.addIssue({code:"custom",message:"Provide config.data or datasetRef",path:["datasetRef"]})}const A=r.enum(["EN_GB","EN_US"]),O=r.custom(e=>null!=e&&"object"==typeof e),I=r.enum(["low","medium","high"]),P=r.enum(["none","low","medium","high"]),M=r.enum(["agentic","fast"]),B=3e5,q=5e5,D=10,F=r.object({maxWallClockMs:r.number().positive().max(B).optional(),maxTotalTokens:r.number().int().positive().max(q).optional(),maxCostUsd:r.number().positive().max(10).optional(),trackUsage:r.boolean().optional()}),_=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:F,consumed:_,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});const N=r.object({callId:r.string().max(256).optional(),locale:A.optional(),effort:I.optional(),storytellingEffort:P.optional().default("low"),budget:F.optional(),executionMode:M.optional(),enforceTableRowCap:r.boolean().optional()}),K=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()}),L=r.object({runId:r.string(),trackingId:r.string(),callId:r.string().optional()}),z=1e4,G=r.enum(["comparison","relationship","distribution","composition"]),W=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,H=r.string().regex(W,"datasetRef must be graphy://attachments/{uuid}"),J=r.object({config:O,userPrompt:r.string().max(z).optional().default(""),metadata:N.optional(),chartFamily:G.optional(),datasetRef:H.optional()}),X=J.superRefine(U),Q=J.extend({maxSuggestionCount:r.number().int().min(1).max(4).optional()}).superRefine(U),V=r.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),Y=r.object({dataPrepPrompt:r.string(),chartType:V,summary:r.string()}),Z=J.extend({userPrompt:r.string().max(z),mutationReceipt:K.optional(),exploreFindingSummary:r.string().max(500).optional()}).superRefine(U),ee=r.object({response:r.object({message:r.string()}),config:O,run:L.optional()}).extend(E),te=r.object({suggestions:r.array(Y),run:L.optional()}).extend(E),ne=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:G.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.")}),ie=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(ne).describe("Child findings, sorted by quadrant score desc.")}),oe=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),stories:r.array(ie),run:L.optional()}).extend(E);J.extend({mutationReceipt:K.optional()}).superRefine(U);const re=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:O,run:L.optional()}).extend(E),ae=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:O,mutationReceipt:K.optional(),warnings:r.array(r.string()).optional(),run:L.optional()}).extend(E),se=r.enum(["explore","mutate","narrate","annotate"]),le=r.object({agent:se,summary:r.string(),steps:r.array(r.string()).optional()}),ce=J.extend({userPrompt:r.string().max(z),stages:r.array(se).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:r.string().max(500).optional()}).superRefine(U),de=ae.extend({reasoning:r.array(le),stories:r.array(ie).optional()}),me=r.enum(["high","medium","low"]),ue=r.object({confidence:me,needsUserInput:r.boolean(),warnings:r.array(r.string()),cellConfidence:r.array(r.object({rowIndex:r.number().int().nonnegative(),columnKey:r.string(),confidence:me,quote:r.string().optional()})).optional()}),pe=r.object({score:r.number().min(0).max(1),issues:r.array(r.string()),sufficient:r.boolean(),summary:r.string()}),ge=5e5,he=8,fe=2097152,be=7340032,ye=2,ve=6291456,xe=8388608,we=2,je=ve,ke=xe,Te=12582912,$e=12,Se=52428800;function Ce(e){return 4*Math.ceil(e/3)}const Re=Ce(fe),Ee=Ce(be),Ue=Ce(ve),Ae=Ce(xe),Oe=Ce(je),Ie=Ce(ke),Pe=Ce(Te);function Me(e){return e.replace(/\s+/g,"")}function Be(e){const t=Me(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const qe=/^image\/(png|jpeg|jpg|webp|gif)$/i,De=r.object({mimeType:r.string().min(1).refine(e=>qe.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:r.string().min(1).max(Re).refine(Be,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Fe=r.enum(["image","document","spreadsheet","tabular"]),_e=De.extend({kind:r.literal("image")}),Ne=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(Ue).refine(Be,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Ke=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(Oe).refine(Be,{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"]}),Le=r.discriminatedUnion("kind",[_e,Ne,Ke]),ze=r.string().regex(W,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),Ge=r.enum(["pending","ready","failed"]),We=r.object({id:r.string().uuid(),uri:r.string(),status:Ge,kind:Fe.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()}),He=We.extend({status:r.literal("ready"),kind:Fe,sizeBytes:r.number().int().positive()}),Je=r.object({mimeType:r.string().min(1),filename:r.string().max(512).optional(),sizeBytes:r.number().int().positive().max(Se).optional()}),Xe=r.object({files:r.array(Je).min(1).max($e)}),Qe=We.extend({status:r.literal("pending"),uploadUrl:r.string().url()}),Ve=r.object({uploads:r.array(Qe)}),Ye=r.object({sourceText:r.string().max(ge).default(""),images:r.array(De).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:r.array(Le).max($e).optional(),attachmentRefs:r.array(ze).max($e).optional(),metadata:N.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>$e)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+Me(t.dataBase64).length,0)>Ee&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let c=0,d=0,m=0,u=0,p=0,g=0,h=0;for(const e of s){const t=Me(e.dataBase64).length;switch(h+=t,e.kind){case"image":c+=1,u+=t;break;case"document":d+=1,p+=t;break;case"spreadsheet":m+=1,g+=t}}c>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),d>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=c<=8&&d<=2&&m<=2;s.length>0&&f&&(u>Ee&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>Ae&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>Ie&&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"]}))});function Ze(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:Me(e.dataBase64)}}function et(e){return{kind:"document",mimeType:"application/pdf",dataBase64:Me(e.dataBase64)}}function tt(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:Me(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const nt=r.object({response:r.object({message:r.string()}),config:O,extractMeta:ue.nullable(),lastAccuracyEvaluation:pe.optional(),run:L.optional()}).extend(E),it=r.object({config:O,response:r.object({message:r.string(),steps:r.array(r.string())}),run:L.optional()}).extend(E),ot=te,rt=r.enum(["deal-breaker","pro","con","family","continuity"]),at=r.object({kind:rt,label:r.string(),weight:r.number(),reason:r.string()}),st=r.enum(["ok","disqualified"]),lt=r.object({rank:r.number().int().positive(),type:V,score:r.number(),verdict:st,factors:r.array(at)}),ct=X,dt=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"]),mt=r.object({kind:dt,message:r.string()}),ut=r.enum(["sum","avg","count","min","max"]),pt=r.object({dimensionName:r.string(),dimensionLabel:r.string(),measureName:r.string().nullable(),measureLabel:r.string().nullable(),fn:ut,chartType:V,score:r.number(),message:r.string()}),gt=r.object({ranking:r.array(lt),observations:r.array(mt).optional().default([]),suggestions:r.array(pt).optional().default([]),run:L.optional()}),ht=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()}),ft=r.object({config:O.optional(),chartImage:r.string().optional(),data:r.unknown().optional(),rubric:ht.optional(),userPrompt:r.string().optional(),metadata:N.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),bt=r.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),yt=r.enum(["info","low","medium","high"]),vt=r.object({category:bt,severity:yt,observation:r.string(),rationale:r.string().optional(),suggestedChange:r.string().optional(),configPaths:r.array(r.string()).optional()}),xt=r.object({overallSummary:r.string(),overallSeverity:r.enum(["none","low","medium","high"]).optional(),issues:r.array(vt)}),wt=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()}),jt=r.object({capturedAt:r.string(),chartId:r.string()}),kt=r.object({response:r.object({message:r.string(),steps:r.array(r.string()),critiqueCommitted:r.boolean()}),critiqueReport:xt.nullable(),chartVisionAudit:jt.nullable().optional().default(null),rubricScores:wt.nullable().optional().default(null),run:L.optional()}).extend(E),Tt="/api/v0";class $t{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(`${Tt}/generate`,r,n,i),s=it.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(`${Tt}/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(`${Tt}/narrate`,t,n,i);return ee.parse(e)})}generateNarrativeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/narrate`,t,n)})}generateSuggestions(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/suggestions`,t,n,i);return te.parse(e)})}generateSuggestionsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/suggestions`,t,n)})}generateExploration(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/explore`,t,n,i);return oe.parse(e)})}generateExplorationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/explore`,t,n)})}generateAnnotations(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/annotate`,t,n,i);return re.parse(e)})}generateAnnotationsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/annotate`,t,n)})}generateMutation(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/mutate`,t,n,i);return ae.parse(e)})}generateMutationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/mutate`,t,n)})}generatePipeline(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/pipeline`,t,n,i);return de.parse(e)})}generatePipelineStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/pipeline`,t,n)})}evaluate(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/evaluate`,t,void 0,n);return gt.parse(e)})}judge(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/judge`,t,void 0,n);return kt.parse(e)})}judgeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/judge`,t,n)})}extractFromProse(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/extract`,t,n,i);return nt.parse(e)})}extractFromProseStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/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 He.parse(c)})}uploadDataset(t,n,i){return e(this,void 0,void 0,function*(){const e=$(t,n);return this.uploadAttachment(t,Object.assign(Object.assign({},n),{mimeType:e}),i)})}createAttachmentUploads(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Tt}/attachment-uploads`,t,n);return Ve.parse(e)})}completeAttachmentUpload(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Tt}/attachments/${t}/complete`,{},n);return We.parse(e)})}getAttachment(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.get(`${Tt}/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(e,o){return n(this,arguments,function*(){var n,r,a,s;try{for(var l,d=!0,m=t(e);!(n=(l=yield i(m.next())).done);d=!0){s=l.value,d=!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{d||n||!(a=m.return)||(yield i(a.call(m)))}finally{if(r)throw r.error}}})}}export{ut as AggregationFunctionSchema,pt as AggregationSuggestionSchema,V as AiChartTypeEnum,We as AttachmentResponseSchema,He as AttachmentUploadResponseSchema,Qe as AttachmentUploadSlotResponseSchema,bt as ChartCritiqueIssueCategorySchema,vt as ChartCritiqueIssueSchema,yt as ChartCritiqueIssueSeveritySchema,xt as ChartCritiqueReportSchema,G as ChartFamilySchema,lt as ChartFitEntrySchema,rt as ChartFitFactorKindSchema,at as ChartFitFactorSchema,st as ChartFitVerdictSchema,ht as ChartJudgeRubricSchema,Xe as CreateAttachmentUploadsParamsSchema,Ve as CreateAttachmentUploadsResponseSchema,dt as DataObservationKindSchema,mt as DataObservationSchema,ct as EvaluateParamsSchema,gt as EvaluateResponseSchema,M as ExecutionModeSchema,ne as ExploreFindingSchema,ie as ExploreStorySchema,pe as ExtractAccuracyEvaluationSchema,Le as ExtractAttachmentInputSchema,Fe as ExtractAttachmentKindSchema,me as ExtractConfidenceSchema,Ye as ExtractFromProseParamsSchema,nt as ExtractFromProseResponseSchema,ue as ExtractMetaSchema,re as GenerateAnnotationsResponseSchema,oe as GenerateExplorationResponseSchema,it as GenerateGraphResponseSchema,ot as GenerateGraphSuggestionsResponseSchema,ae as GenerateMutationResponseSchema,Z as GenerateNarrativeParamsSchema,ee as GenerateNarrativeResponseSchema,ce as GeneratePipelineParamsSchema,de as GeneratePipelineResponseSchema,Q as GenerateSuggestionsParamsSchema,te as GenerateSuggestionsResponseSchema,X as GraphGenerationRequestSchema,$t as GraphyAiSdk,a as GraphyApiError,F as InvocationBudgetSchema,I as InvocationEffortSchema,ft as JudgeParamsSchema,kt as JudgeResponseSchema,D as MAX_BUDGET_COST_USD,q as MAX_BUDGET_TOTAL_TOKENS,B as MAX_BUDGET_WALL_CLOCK_MS,$e as MAX_EXTRACT_ATTACHMENTS,Te as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,ye as MAX_EXTRACT_DOCUMENTS,xe as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,ve as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,he as MAX_EXTRACT_IMAGES,be as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,fe as MAX_EXTRACT_IMAGE_DECODED_BYTES,we as MAX_EXTRACT_SPREADSHEETS,ke as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,je as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,ge as MAX_SOURCE_TEXT_LENGTH,Se as MAX_STAGED_FILE_BYTES,z as MAX_USER_PROMPT_LENGTH,N as MetadataSchema,K as MutateNarrationReceiptSchema,se as PipelineAgentNameSchema,le as PipelineStageReasoningSchema,wt as RubricScoresSchema,L as RunContextSchema,P as StorytellingEffortSchema,Y as SuggestionSchema,Ze as buildImageAttachment,et as buildPdfAttachment,tt as buildSpreadsheetAttachment,h as isAgentCompleteEvent,c as isCompleteEvent,d as isErrorEvent,s as isGraphyApiError,p as isLlmStepEvent,m 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.7.
|
|
4
|
+
"version": "1.7.2",
|
|
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.7.
|
|
21
|
+
"@graphysdk/core": "1.7.2"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|