@graphysdk/agents-sdk 1.6.2-beta.1782204737314 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  TypeScript client types and helpers for Graphy agent HTTP APIs.
4
4
 
5
+ ## Initial datasets (`datasetRef`)
6
+
7
+ Chart agent requests accept either inline **`config.data`** or a staged **`datasetRef`** (`graphy://attachments/{uuid}`).
8
+ Use **`uploadDataset(file)`** to stage CSV, TSV, or XLSX (presigned flow), then pass `datasetRef` on
9
+ `generateGraph`, `generateGraphStream`, and other `GraphGenerationRequestSchema` methods. Inline non-empty data and
10
+ `datasetRef` are mutually exclusive. See **`apps/agents-api/README.md`** (Initial datasets) for size limits and auth.
11
+
5
12
  ## Extract (`POST /api/v0/extract`)
6
13
 
7
14
  `ExtractFromProseParams` mirrors `ExtractFromProseRequestSchema` in **agents-api**. Prefer **`attachments[]`** over deprecated **`images[]`** (do not send both).
package/dist/README.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  TypeScript client types and helpers for Graphy agent HTTP APIs.
4
4
 
5
+ ## Initial datasets (`datasetRef`)
6
+
7
+ Chart agent requests accept either inline **`config.data`** or a staged **`datasetRef`** (`graphy://attachments/{uuid}`).
8
+ Use **`uploadDataset(file)`** to stage CSV, TSV, or XLSX (presigned flow), then pass `datasetRef` on
9
+ `generateGraph`, `generateGraphStream`, and other `GraphGenerationRequestSchema` methods. Inline non-empty data and
10
+ `datasetRef` are mutually exclusive. See **`apps/agents-api/README.md`** (Initial datasets) for size limits and auth.
11
+
5
12
  ## Extract (`POST /api/v0/extract`)
6
13
 
7
14
  `ExtractFromProseParams` mirrors `ExtractFromProseRequestSchema` in **agents-api**. Prefer **`attachments[]`** over deprecated **`images[]`** (do not send both).
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("tslib"),t=require("zod");class n extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const r=e=>"progress"===e.type,a=e=>"complete"===e.type,o=e=>"error"===e.type;function i(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class s{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return r(e)}static isCompleteEvent(e){return a(e)}static isErrorEvent(e){return o(e)}stream(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,r);return this.parseSSE(e)})}fetch(t,i,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,u,d;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const z=yield this.makeRequest(t,i,c),y=z.headers.get("content-type");if(null==y?void 0:y.includes("text/event-stream")){try{for(var h,f=!0,b=e.__asyncValues(this.parseSSE(z));!(l=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(r(e)&&s&&s(e),a(e))return e.data;if(o(e)){const r=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${r}ms`,e.error),new n(e.error,{code:e.code,retryable:null!==(d=e.retryable)&&void 0!==d&&d})}}}catch(e){m={error:e}}finally{try{f||l||!(p=b.return)||(yield p.call(b))}finally{if(m)throw m.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${i}ms`),new n("Stream ended without completion")}return yield z.json()}catch(e){const r=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${r}ms`,e),e instanceof n)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,r);return yield e.json()})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new n("Response body is null");const r=t.body.getReader(),a=new TextDecoder;let o="",s="",c="";try{for(;;){const{done:t,value:n}=yield e.__await(r.read());if(t)break;o+=a.decode(n,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const t of l)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))c+=(c?"\n":"")+t.slice(6);else if(""===t.trim()&&c){try{const t=i(s,JSON.parse(c));if(null===t){s="",c="";continue}if(yield yield e.__await(t),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",c)}s="",c=""}}}finally{r.releaseLock()}})}makeRequest(t,r,a){return e.__awaiter(this,arguments,void 0,function*(e,t,r,a=1,o="POST"){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const i=new URL(e,this.baseUrl);if(i.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${a}/${this.retryConfig.attempts}: ${i}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();r&&r.addEventListener("abort",l);try{const c=yield fetch(i,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!c.ok){let i,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(i=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===i)&&(c.status>=500||429===c.status),m=new n(s,{status:c.status,code:i,retryable:l});if(l&&a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${n}ms (attempt ${a+1})`),yield this.sleep(n),this.makeRequest(e,t,r,a+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(i){if(i instanceof n)throw i;if(i instanceof Error&&"AbortError"===i.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),i;if(a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${n}ms`),yield this.sleep(n),this.makeRequest(e,t,r,a+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,i),new n("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",l)}})}makeMultipartRequest(t,r,a){return e.__awaiter(this,arguments,void 0,function*(e,t,r,a=1){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");const i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),c=()=>i.abort();r&&r.addEventListener("abort",c);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:i.signal});if(!s.ok){let o,i=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const c=s.status>=500||429===s.status,l=new n(i,{status:s.status,code:o,retryable:c});if(c&&a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,r,a+1)}throw l}return s}catch(o){if(o instanceof n)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,r,a+1)}throw new n("Network error",{retryable:!0})}finally{clearTimeout(s),r&&r.removeEventListener("abort",c)}})}}const c=t.z.object({inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional(),wallClockMs:t.z.number()}),l=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()}),m=t.z.object({limits:t.z.object({maxWallClockMs:t.z.number().optional(),maxTotalTokens:t.z.number().optional(),maxCostUsd:t.z.number().optional(),trackUsage:t.z.boolean().optional()}),consumed:l,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});t.z.object({inputTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),modelName:t.z.string(),inputCachedTokens:t.z.number().optional(),inputUncachedTokens:t.z.number().optional(),cost:t.z.number().optional(),latencyMs:t.z.number().optional(),effort:t.z.string().optional(),providerReasoning:t.z.string().optional()});const p={usage:c.optional(),budget:m.optional()},u=t.z.enum(["EN_GB","EN_US"]),d=t.z.custom(e=>null!=e&&"object"==typeof e),g=t.z.enum(["low","medium","high"]),h=t.z.enum(["none","low","medium","high"]),f=t.z.enum(["agentic","fast"]),b=3e5,z=5e5,y=t.z.object({maxWallClockMs:t.z.number().positive().max(b).optional(),maxTotalTokens:t.z.number().int().positive().max(z).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),x=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()});t.z.object({limits:y,consumed:x,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});const v=t.z.object({callId:t.z.string().max(256).optional(),locale:u.optional(),effort:g.optional(),storytellingEffort:h.optional().default("low"),budget:y.optional(),executionMode:f.optional(),enforceTableRowCap:t.z.boolean().optional()}),_=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),S=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),w=1e4,T=t.z.enum(["comparison","relationship","distribution","composition"]),E=t.z.object({config:d,userPrompt:t.z.string().max(w).optional().default(""),metadata:v.optional(),chartFamily:T.optional()}),C=E.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),j=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),k=t.z.object({dataPrepPrompt:t.z.string(),chartType:j,summary:t.z.string()}),A=E.extend({userPrompt:t.z.string().max(w),mutationReceipt:_.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),R=t.z.object({response:t.z.object({message:t.z.string()}),config:d,run:S.optional()}).extend(p),$=t.z.object({suggestions:t.z.array(k),run:S.optional()}).extend(p),M=t.z.object({finding:t.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:t.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:t.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:t.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:t.z.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:T.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),O=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(M).describe("Child findings, sorted by quadrant score desc.")}),D=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(O),run:S.optional()}).extend(p);E.extend({mutationReceipt:_.optional()});const P=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:d,run:S.optional()}).extend(p),U=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:d,mutationReceipt:_.optional(),warnings:t.z.array(t.z.string()).optional(),run:S.optional()}).extend(p),I=t.z.enum(["explore","mutate","narrate","annotate"]),B=t.z.object({agent:I,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),G=E.extend({userPrompt:t.z.string().max(w),stages:t.z.array(I).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),F=U.extend({reasoning:t.z.array(B),stories:t.z.array(O).optional()}),X=t.z.enum(["high","medium","low"]),N=t.z.object({confidence:X,needsUserInput:t.z.boolean(),warnings:t.z.array(t.z.string()),cellConfidence:t.z.array(t.z.object({rowIndex:t.z.number().int().nonnegative(),columnKey:t.z.string(),confidence:X,quote:t.z.string().optional()})).optional()}),q=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),L=5e5,K=2097152,H=7340032,W=6291456,Y=8388608,J=W,V=Y,Q=12582912;function Z(e){return 4*Math.ceil(e/3)}const ee=Z(K),te=Z(H),ne=Z(W),re=Z(Y),ae=Z(J),oe=Z(V),ie=Z(Q);function se(e){return e.replace(/\s+/g,"")}function ce(e){const t=se(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const le=/^image\/(png|jpeg|jpg|webp|gif)$/i,me=t.z.object({mimeType:t.z.string().min(1).refine(e=>le.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(ee).refine(ce,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),pe=t.z.enum(["image","document","spreadsheet"]),ue=me.extend({kind:t.z.literal("image")}),de=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(ne).refine(ce,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ge=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(ae).refine(ce,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),he=t.z.discriminatedUnion("kind",[ue,de,ge]),fe=t.z.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),be=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),kind:pe,mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().positive(),expiresAt:t.z.string().datetime()}),ze=t.z.object({sourceText:t.z.string().max(L).default(""),images:t.z.array(me).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(he).max(12).optional(),attachmentRefs:t.z.array(fe).max(12).optional(),metadata:v.optional()}).superRefine((e,t)=>{var n,r,a;const o=e.sourceText.trim(),i=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(r=e.attachments)&&void 0!==r?r:[],c=null!==(a=e.attachmentRefs)&&void 0!==a?a:[];if(i.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(c.length>0&&s.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or inline `attachments`, not both.",path:["attachmentRefs"]});if(c.length>0&&i.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or deprecated `images`, not both.",path:["attachmentRefs"]});if(0===o.length&&0===i.length&&0===s.length&&0===c.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(c.length>0)return;if(i.length>0){i.reduce((e,t)=>e+se(t.dataBase64).length,0)>te&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let l=0,m=0,p=0,u=0,d=0,g=0,h=0;for(const e of s){const t=se(e.dataBase64).length;switch(h+=t,e.kind){case"image":l+=1,u+=t;break;case"document":m+=1,d+=t;break;case"spreadsheet":p+=1,g+=t}}l>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),p>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&p<=2;s.length>0&&f&&(u>te&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>re&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>oe&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>ie&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const ye=t.z.object({response:t.z.object({message:t.z.string()}),config:d,extractMeta:N.nullable(),lastAccuracyEvaluation:q.optional(),run:S.optional()}).extend(p),xe=t.z.object({config:d,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:S.optional()}).extend(p),ve=$,_e=t.z.enum(["deal-breaker","pro","con","family","continuity"]),Se=t.z.object({kind:_e,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),we=t.z.enum(["ok","disqualified"]),Te=t.z.object({rank:t.z.number().int().positive(),type:j,score:t.z.number(),verdict:we,factors:t.z.array(Se)}),Ee=t.z.object({config:d,chartFamily:T.optional(),metadata:v.optional()}),Ce=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),je=t.z.object({kind:Ce,message:t.z.string()}),ke=t.z.enum(["sum","avg","count","min","max"]),Ae=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:ke,chartType:j,score:t.z.number(),message:t.z.string()}),Re=t.z.object({ranking:t.z.array(Te),observations:t.z.array(je).optional().default([]),suggestions:t.z.array(Ae).optional().default([]),run:S.optional()}),$e=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),Me=t.z.object({config:d.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:$e.optional(),userPrompt:t.z.string().optional(),metadata:v.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Oe=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),De=t.z.enum(["info","low","medium","high"]),Pe=t.z.object({category:Oe,severity:De,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),Ue=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Pe)}),Ie=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),Be=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),Ge=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:Ue.nullable(),chartVisionAudit:Be.nullable().optional().default(null),rubricScores:Ie.nullable().optional().default(null),run:S.optional()}).extend(p),Fe="/api/v0";exports.AggregationFunctionSchema=ke,exports.AggregationSuggestionSchema=Ae,exports.AiChartTypeEnum=j,exports.AttachmentUploadResponseSchema=be,exports.ChartCritiqueIssueCategorySchema=Oe,exports.ChartCritiqueIssueSchema=Pe,exports.ChartCritiqueIssueSeveritySchema=De,exports.ChartCritiqueReportSchema=Ue,exports.ChartFamilySchema=T,exports.ChartFitEntrySchema=Te,exports.ChartFitFactorKindSchema=_e,exports.ChartFitFactorSchema=Se,exports.ChartFitVerdictSchema=we,exports.ChartJudgeRubricSchema=$e,exports.DataObservationKindSchema=Ce,exports.DataObservationSchema=je,exports.EvaluateParamsSchema=Ee,exports.EvaluateResponseSchema=Re,exports.ExecutionModeSchema=f,exports.ExploreFindingSchema=M,exports.ExploreStorySchema=O,exports.ExtractAccuracyEvaluationSchema=q,exports.ExtractAttachmentInputSchema=he,exports.ExtractAttachmentKindSchema=pe,exports.ExtractConfidenceSchema=X,exports.ExtractFromProseParamsSchema=ze,exports.ExtractFromProseResponseSchema=ye,exports.ExtractMetaSchema=N,exports.GenerateAnnotationsResponseSchema=P,exports.GenerateExplorationResponseSchema=D,exports.GenerateGraphResponseSchema=xe,exports.GenerateGraphSuggestionsResponseSchema=ve,exports.GenerateMutationResponseSchema=U,exports.GenerateNarrativeParamsSchema=A,exports.GenerateNarrativeResponseSchema=R,exports.GeneratePipelineParamsSchema=G,exports.GeneratePipelineResponseSchema=F,exports.GenerateSuggestionsParamsSchema=C,exports.GenerateSuggestionsResponseSchema=$,exports.GraphGenerationRequestSchema=E,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,o=e.__rest(t,["storytellingOptions"]),i=yield this.client.fetch(`${Fe}/generate`,o,n,r),s=xe.parse(i);return this.stripStorytelling(s,a)})}generateGraphStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:r}=t,a=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${Fe}/generate`,a,n);return this.wrapStreamWithStorytellingStripping(o,r)})}generateNarrative(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/narrate`,t,n,r);return R.parse(e)})}generateNarrativeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/narrate`,t,n)})}generateSuggestions(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/suggestions`,t,n,r);return $.parse(e)})}generateSuggestionsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/suggestions`,t,n)})}generateExploration(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/explore`,t,n,r);return D.parse(e)})}generateExplorationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/explore`,t,n)})}generateAnnotations(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/annotate`,t,n,r);return P.parse(e)})}generateAnnotationsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/annotate`,t,n)})}generateMutation(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/mutate`,t,n,r);return U.parse(e)})}generateMutationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/mutate`,t,n)})}generatePipeline(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/pipeline`,t,n,r);return F.parse(e)})}generatePipelineStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/pipeline`,t,n)})}evaluate(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/evaluate`,t,void 0,n);return Re.parse(e)})}judge(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/judge`,t,void 0,n);return Ge.parse(e)})}judgeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/judge`,t,n)})}extractFromProse(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Fe}/extract`,t,n,r);return ye.parse(e)})}extractFromProseStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Fe}/extract`,t,n)})}uploadAttachment(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=new FormData,a=null==n?void 0:n.filename;"undefined"!=typeof File&&t instanceof File?e.append("file",t):a?e.append("file",t,a):e.append("file",t,"upload"),a&&e.append("filename",a);const o=yield this.client.uploadMultipart(`${Fe}/attachments`,e,r);return be.parse(o)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,n){return e.__asyncGenerator(this,arguments,function*(){var r,o,i,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(r=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(a(t)){const r=this.stripStorytelling(t.data,n);yield yield e.__await(Object.assign(Object.assign({},t),{data:r}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||r||!(i=m.return)||(yield e.__await(i.call(m)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=n,exports.InvocationBudgetSchema=y,exports.InvocationEffortSchema=g,exports.JudgeParamsSchema=Me,exports.JudgeResponseSchema=Ge,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=z,exports.MAX_BUDGET_WALL_CLOCK_MS=b,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=Q,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=Y,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=W,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=H,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=K,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=V,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=J,exports.MAX_SOURCE_TEXT_LENGTH=L,exports.MAX_USER_PROMPT_LENGTH=w,exports.MetadataSchema=v,exports.MutateNarrationReceiptSchema=_,exports.PipelineAgentNameSchema=I,exports.PipelineStageReasoningSchema=B,exports.RubricScoresSchema=Ie,exports.RunContextSchema=S,exports.StorytellingEffortSchema=h,exports.SuggestionSchema=k,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:se(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:se(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:se(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isAgentCompleteEvent=e=>"agent_complete"===e.type,exports.isCompleteEvent=a,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof n,exports.isLlmStepEvent=e=>"llm_step"===e.type,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=r,exports.isReasoningEvent=e=>"reasoning"===e.type,exports.isSessionBudgetEvent=e=>"session_budget"===e.type,exports.isToolCallEvent=e=>"tool_call"===e.type,exports.isToolCompleteEvent=e=>"tool_complete"===e.type,exports.isToolErrorEvent=e=>"tool_error"===e.type;
1
+ "use strict";var e=require("tslib"),t=require("zod");class n extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const 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;
package/dist/index.d.ts CHANGED
@@ -395,6 +395,18 @@ declare const isToolCallEvent: <T>(event: SSEEvent<T>) => event is ToolCallEvent
395
395
  declare const isToolCompleteEvent: <T>(event: SSEEvent<T>) => event is ToolCompleteEvent;
396
396
  declare const isToolErrorEvent: <T>(event: SSEEvent<T>) => event is ToolErrorEvent;
397
397
 
398
+ type UploadAttachmentOptions = {
399
+ /** Display name hint (especially for spreadsheets). */
400
+ filename?: string;
401
+ /**
402
+ * MIME type for the presigned upload slot. Required when `file.type` is empty and the
403
+ * filename has no recognized extension.
404
+ */
405
+ mimeType?: string;
406
+ };
407
+
408
+ type UploadDatasetOptions = UploadAttachmentOptions;
409
+
398
410
  declare const InvocationEffortSchema: z.ZodEnum<{
399
411
  low: "low";
400
412
  medium: "medium";
@@ -512,6 +524,47 @@ declare const ChartFamilySchema: z.ZodEnum<{
512
524
  composition: "composition";
513
525
  }>;
514
526
  type ChartFamily = z.infer<typeof ChartFamilySchema>;
527
+ /** Object shape shared by chart agent request bodies (before dataset-source refinement). */
528
+ declare const GraphGenerationRequestBodySchema: z.ZodObject<{
529
+ config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
530
+ userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
531
+ metadata: z.ZodOptional<z.ZodObject<{
532
+ callId: z.ZodOptional<z.ZodString>;
533
+ locale: z.ZodOptional<z.ZodEnum<{
534
+ EN_GB: "EN_GB";
535
+ EN_US: "EN_US";
536
+ }>>;
537
+ effort: z.ZodOptional<z.ZodEnum<{
538
+ low: "low";
539
+ medium: "medium";
540
+ high: "high";
541
+ }>>;
542
+ storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
543
+ low: "low";
544
+ medium: "medium";
545
+ high: "high";
546
+ none: "none";
547
+ }>>>;
548
+ budget: z.ZodOptional<z.ZodObject<{
549
+ maxWallClockMs: z.ZodOptional<z.ZodNumber>;
550
+ maxTotalTokens: z.ZodOptional<z.ZodNumber>;
551
+ maxCostUsd: z.ZodOptional<z.ZodNumber>;
552
+ trackUsage: z.ZodOptional<z.ZodBoolean>;
553
+ }, z.core.$strip>>;
554
+ executionMode: z.ZodOptional<z.ZodEnum<{
555
+ agentic: "agentic";
556
+ fast: "fast";
557
+ }>>;
558
+ enforceTableRowCap: z.ZodOptional<z.ZodBoolean>;
559
+ }, z.core.$strip>>;
560
+ chartFamily: z.ZodOptional<z.ZodEnum<{
561
+ comparison: "comparison";
562
+ relationship: "relationship";
563
+ distribution: "distribution";
564
+ composition: "composition";
565
+ }>>;
566
+ datasetRef: z.ZodOptional<z.ZodString>;
567
+ }, z.core.$strip>;
515
568
  /**
516
569
  * Shared request body for every agent endpoint (`/v0/generate`, `/v0/narrate`,
517
570
  * `/v0/explore`, `/v0/annotate`, etc.). Mirrors `GraphGenerationRequestSchema`
@@ -555,8 +608,9 @@ declare const GraphGenerationRequestSchema: z.ZodObject<{
555
608
  distribution: "distribution";
556
609
  composition: "composition";
557
610
  }>>;
611
+ datasetRef: z.ZodOptional<z.ZodString>;
558
612
  }, z.core.$strip>;
559
- type GraphGenerationRequest = z.input<typeof GraphGenerationRequestSchema>;
613
+ type GraphGenerationRequest = z.input<typeof GraphGenerationRequestBodySchema>;
560
614
  /** Request body for `POST /v0/suggestions` only. `maxSuggestionCount` max must match agents-api `PROMPT_SUGGESTIONS_UPPER_BOUND`. */
561
615
  declare const GenerateSuggestionsParamsSchema: z.ZodObject<{
562
616
  config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
@@ -596,6 +650,7 @@ declare const GenerateSuggestionsParamsSchema: z.ZodObject<{
596
650
  distribution: "distribution";
597
651
  composition: "composition";
598
652
  }>>;
653
+ datasetRef: z.ZodOptional<z.ZodString>;
599
654
  maxSuggestionCount: z.ZodOptional<z.ZodNumber>;
600
655
  }, z.core.$strip>;
601
656
  type GenerateSuggestionsParams = z.input<typeof GenerateSuggestionsParamsSchema>;
@@ -690,6 +745,7 @@ declare const GenerateNarrativeParamsSchema: z.ZodObject<{
690
745
  distribution: "distribution";
691
746
  composition: "composition";
692
747
  }>>;
748
+ datasetRef: z.ZodOptional<z.ZodString>;
693
749
  userPrompt: z.ZodString;
694
750
  mutationReceipt: z.ZodOptional<z.ZodObject<{
695
751
  steps: z.ZodArray<z.ZodString>;
@@ -982,6 +1038,7 @@ declare const GenerateAnnotationsParamsSchema: z.ZodObject<{
982
1038
  distribution: "distribution";
983
1039
  composition: "composition";
984
1040
  }>>;
1041
+ datasetRef: z.ZodOptional<z.ZodString>;
985
1042
  mutationReceipt: z.ZodOptional<z.ZodObject<{
986
1043
  steps: z.ZodArray<z.ZodString>;
987
1044
  postProcess: z.ZodOptional<z.ZodObject<{
@@ -1190,6 +1247,7 @@ declare const GeneratePipelineParamsSchema: z.ZodObject<{
1190
1247
  distribution: "distribution";
1191
1248
  composition: "composition";
1192
1249
  }>>;
1250
+ datasetRef: z.ZodOptional<z.ZodString>;
1193
1251
  userPrompt: z.ZodString;
1194
1252
  stages: z.ZodArray<z.ZodEnum<{
1195
1253
  explore: "explore";
@@ -1358,6 +1416,7 @@ declare const MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES: number;
1358
1416
  declare const MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES: number;
1359
1417
  /** Max entries in `attachments[]` (images + PDFs + spreadsheets). Mirrors agents-api. */
1360
1418
  declare const MAX_EXTRACT_ATTACHMENTS: number;
1419
+ declare const MAX_STAGED_FILE_BYTES: number;
1361
1420
  declare const extractImagePartSchema: z.ZodObject<{
1362
1421
  mimeType: z.ZodString;
1363
1422
  dataBase64: z.ZodString;
@@ -1367,6 +1426,7 @@ declare const ExtractAttachmentKindSchema: z.ZodEnum<{
1367
1426
  image: "image";
1368
1427
  document: "document";
1369
1428
  spreadsheet: "spreadsheet";
1429
+ tabular: "tabular";
1370
1430
  }>;
1371
1431
  type ExtractAttachmentKind = z.infer<typeof ExtractAttachmentKindSchema>;
1372
1432
  declare const ExtractAttachmentInputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
@@ -1384,20 +1444,95 @@ declare const ExtractAttachmentInputSchema: z.ZodDiscriminatedUnion<[z.ZodObject
1384
1444
  filename: z.ZodOptional<z.ZodString>;
1385
1445
  }, z.core.$strip>], "kind">;
1386
1446
  type ExtractAttachmentInput = z.infer<typeof ExtractAttachmentInputSchema>;
1447
+ declare const AttachmentResponseSchema: z.ZodObject<{
1448
+ id: z.ZodString;
1449
+ uri: z.ZodString;
1450
+ status: z.ZodEnum<{
1451
+ pending: "pending";
1452
+ ready: "ready";
1453
+ failed: "failed";
1454
+ }>;
1455
+ kind: z.ZodOptional<z.ZodEnum<{
1456
+ image: "image";
1457
+ document: "document";
1458
+ spreadsheet: "spreadsheet";
1459
+ tabular: "tabular";
1460
+ }>>;
1461
+ mimeType: z.ZodString;
1462
+ filename: z.ZodOptional<z.ZodString>;
1463
+ sizeBytes: z.ZodNumber;
1464
+ uploadExpiresAt: z.ZodOptional<z.ZodString>;
1465
+ completedAt: z.ZodOptional<z.ZodString>;
1466
+ expiresAt: z.ZodString;
1467
+ }, z.core.$strip>;
1468
+ type AttachmentResponse = z.infer<typeof AttachmentResponseSchema>;
1469
+ /** Multipart upload response (`POST /v0/attachments`). */
1387
1470
  declare const AttachmentUploadResponseSchema: z.ZodObject<{
1388
1471
  id: z.ZodString;
1389
1472
  uri: z.ZodString;
1473
+ mimeType: z.ZodString;
1474
+ filename: z.ZodOptional<z.ZodString>;
1475
+ uploadExpiresAt: z.ZodOptional<z.ZodString>;
1476
+ completedAt: z.ZodOptional<z.ZodString>;
1477
+ expiresAt: z.ZodString;
1478
+ status: z.ZodLiteral<"ready">;
1390
1479
  kind: z.ZodEnum<{
1391
1480
  image: "image";
1392
1481
  document: "document";
1393
1482
  spreadsheet: "spreadsheet";
1483
+ tabular: "tabular";
1394
1484
  }>;
1485
+ sizeBytes: z.ZodNumber;
1486
+ }, z.core.$strip>;
1487
+ type AttachmentUploadResponse = z.infer<typeof AttachmentUploadResponseSchema>;
1488
+ declare const CreateAttachmentUploadsParamsSchema: z.ZodObject<{
1489
+ files: z.ZodArray<z.ZodObject<{
1490
+ mimeType: z.ZodString;
1491
+ filename: z.ZodOptional<z.ZodString>;
1492
+ sizeBytes: z.ZodOptional<z.ZodNumber>;
1493
+ }, z.core.$strip>>;
1494
+ }, z.core.$strip>;
1495
+ type CreateAttachmentUploadsParams = z.infer<typeof CreateAttachmentUploadsParamsSchema>;
1496
+ declare const AttachmentUploadSlotResponseSchema: z.ZodObject<{
1497
+ id: z.ZodString;
1498
+ uri: z.ZodString;
1499
+ kind: z.ZodOptional<z.ZodEnum<{
1500
+ image: "image";
1501
+ document: "document";
1502
+ spreadsheet: "spreadsheet";
1503
+ tabular: "tabular";
1504
+ }>>;
1395
1505
  mimeType: z.ZodString;
1396
1506
  filename: z.ZodOptional<z.ZodString>;
1397
1507
  sizeBytes: z.ZodNumber;
1508
+ uploadExpiresAt: z.ZodOptional<z.ZodString>;
1509
+ completedAt: z.ZodOptional<z.ZodString>;
1398
1510
  expiresAt: z.ZodString;
1511
+ status: z.ZodLiteral<"pending">;
1512
+ uploadUrl: z.ZodString;
1399
1513
  }, z.core.$strip>;
1400
- type AttachmentUploadResponse = z.infer<typeof AttachmentUploadResponseSchema>;
1514
+ type AttachmentUploadSlotResponse = z.infer<typeof AttachmentUploadSlotResponseSchema>;
1515
+ declare const CreateAttachmentUploadsResponseSchema: z.ZodObject<{
1516
+ uploads: z.ZodArray<z.ZodObject<{
1517
+ id: z.ZodString;
1518
+ uri: z.ZodString;
1519
+ kind: z.ZodOptional<z.ZodEnum<{
1520
+ image: "image";
1521
+ document: "document";
1522
+ spreadsheet: "spreadsheet";
1523
+ tabular: "tabular";
1524
+ }>>;
1525
+ mimeType: z.ZodString;
1526
+ filename: z.ZodOptional<z.ZodString>;
1527
+ sizeBytes: z.ZodNumber;
1528
+ uploadExpiresAt: z.ZodOptional<z.ZodString>;
1529
+ completedAt: z.ZodOptional<z.ZodString>;
1530
+ expiresAt: z.ZodString;
1531
+ status: z.ZodLiteral<"pending">;
1532
+ uploadUrl: z.ZodString;
1533
+ }, z.core.$strip>>;
1534
+ }, z.core.$strip>;
1535
+ type CreateAttachmentUploadsResponse = z.infer<typeof CreateAttachmentUploadsResponseSchema>;
1401
1536
  /**
1402
1537
  * Request body for `POST /v0/extract`. Mirrors `ExtractFromProseRequestSchema` in agents-api.
1403
1538
  *
@@ -1759,19 +1894,14 @@ declare const ChartFitEntrySchema: z.ZodObject<{
1759
1894
  }, z.core.$strip>;
1760
1895
  type ChartFitEntry = z.infer<typeof ChartFitEntrySchema>;
1761
1896
  /**
1762
- * Request body for `POST /v0/evaluate`. Evaluation is deterministic — it reads only
1763
- * `config.data` and the optional `chartFamily`, so this is its own type rather than a
1764
- * reuse of `GraphGenerationRequestSchema`: there is no `userPrompt`. Server-side,
1765
- * `config.type`, brand kit, and annotations are also ignored.
1897
+ * Request body for `POST /v0/evaluate`. Reuses `GraphGenerationRequestSchema` for shape
1898
+ * symmetry with other chart routes (including `datasetRef`). The handler only reads
1899
+ * `config.data` (and `chartFamily` if present); other fields including `userPrompt` and
1900
+ * `config.type` are accepted-and-ignored.
1766
1901
  */
1767
1902
  declare const EvaluateParamsSchema: z.ZodObject<{
1768
1903
  config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
1769
- chartFamily: z.ZodOptional<z.ZodEnum<{
1770
- comparison: "comparison";
1771
- relationship: "relationship";
1772
- distribution: "distribution";
1773
- composition: "composition";
1774
- }>>;
1904
+ userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
1775
1905
  metadata: z.ZodOptional<z.ZodObject<{
1776
1906
  callId: z.ZodOptional<z.ZodString>;
1777
1907
  locale: z.ZodOptional<z.ZodEnum<{
@@ -1801,8 +1931,15 @@ declare const EvaluateParamsSchema: z.ZodObject<{
1801
1931
  }>>;
1802
1932
  enforceTableRowCap: z.ZodOptional<z.ZodBoolean>;
1803
1933
  }, z.core.$strip>>;
1934
+ chartFamily: z.ZodOptional<z.ZodEnum<{
1935
+ comparison: "comparison";
1936
+ relationship: "relationship";
1937
+ distribution: "distribution";
1938
+ composition: "composition";
1939
+ }>>;
1940
+ datasetRef: z.ZodOptional<z.ZodString>;
1804
1941
  }, z.core.$strip>;
1805
- type EvaluateParams = z.input<typeof EvaluateParamsSchema>;
1942
+ type EvaluateParams = GraphGenerationRequest;
1806
1943
  /**
1807
1944
  * Actionable observation returned alongside the ranking. Each `kind` describes a data-shape
1808
1945
  * or data-quality concern (not a chart-specific suggestion — those live in `suggestions`).
@@ -3477,19 +3614,43 @@ declare class GraphyAiSdk {
3477
3614
  } | undefined;
3478
3615
  }>>>;
3479
3616
  /**
3480
- * Uploads a file to the staged attachment store (`POST /v0/attachments`).
3617
+ * Uploads a file to the staged attachment store via the presigned flow
3618
+ * (`POST /v0/attachment-uploads` → PUT `uploadUrl` → `POST /v0/attachments/{id}/complete`).
3481
3619
  *
3482
3620
  * @param file - File or Blob to upload (browser `File` or Node `Blob`).
3483
- * @param options - Optional filename override when `file` has no name.
3621
+ * @param options - Optional filename and mimeType overrides when `file` lacks metadata.
3484
3622
  * @param signal - Optional `AbortSignal` to cancel the request.
3485
3623
  * @returns Staged attachment metadata including `graphy://attachments/{id}` URI.
3486
3624
  */
3487
- uploadAttachment(file: Blob, options?: {
3488
- filename?: string;
3489
- }, signal?: AbortSignal): Promise<AttachmentUploadResponse>;
3625
+ uploadAttachment(file: Blob, options?: UploadAttachmentOptions, signal?: AbortSignal): Promise<AttachmentUploadResponse>;
3626
+ /**
3627
+ * Uploads a dataset file (CSV, TSV, or XLSX) via the presigned attachment flow.
3628
+ * Returns a `graphy://attachments/{id}` URI for `datasetRef` on chart agent routes.
3629
+ *
3630
+ * @param file - File or Blob to upload (browser `File` or Node `Blob`).
3631
+ * @param options - Optional filename and mimeType overrides when `file` lacks metadata.
3632
+ * @param signal - Optional `AbortSignal` to cancel the request.
3633
+ * @returns Staged attachment metadata including `graphy://attachments/{id}` URI.
3634
+ * @throws {Error} When the MIME type is not dataset-eligible (e.g. PDF or image).
3635
+ */
3636
+ uploadDataset(file: Blob, options?: UploadDatasetOptions, signal?: AbortSignal): Promise<AttachmentUploadResponse>;
3637
+ /**
3638
+ * Mints presigned upload slots (`POST /v0/attachment-uploads`).
3639
+ *
3640
+ * @returns Pending upload slots with `uploadUrl`, `uri`, and lifetime fields.
3641
+ */
3642
+ createAttachmentUploads(params: CreateAttachmentUploadsParams, signal?: AbortSignal): Promise<CreateAttachmentUploadsResponse>;
3643
+ /**
3644
+ * Finalizes a presigned upload after PUTting bytes to `uploadUrl`.
3645
+ */
3646
+ completeAttachmentUpload(attachmentId: string, signal?: AbortSignal): Promise<AttachmentResponse>;
3647
+ /**
3648
+ * Polls staged attachment status (`GET /v0/attachments/{id}`).
3649
+ */
3650
+ getAttachment(attachmentId: string, signal?: AbortSignal): Promise<AttachmentResponse>;
3490
3651
  private stripStorytelling;
3491
3652
  private wrapStreamWithStorytellingStripping;
3492
3653
  }
3493
3654
 
3494
- export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, AttachmentUploadResponseSchema, ChartCritiqueIssueCategorySchema, ChartCritiqueIssueSchema, ChartCritiqueIssueSeveritySchema, ChartCritiqueReportSchema, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, ChartJudgeRubricSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeParamsSchema, GenerateNarrativeResponseSchema, GeneratePipelineParamsSchema, GeneratePipelineResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, JudgeParamsSchema, JudgeResponseSchema, MAX_BUDGET_COST_USD, MAX_BUDGET_TOTAL_TOKENS, MAX_BUDGET_WALL_CLOCK_MS, MAX_EXTRACT_ATTACHMENTS, MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES, MAX_EXTRACT_DOCUMENTS, MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES, MAX_EXTRACT_DOCUMENT_DECODED_BYTES, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, MutateNarrationReceiptSchema, PipelineAgentNameSchema, PipelineStageReasoningSchema, RubricScoresSchema, RunContextSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isAgentCompleteEvent, isCompleteEvent, isErrorEvent, isGraphyApiError, isLlmStepEvent, isPreviewEvent, isProgressEvent, isReasoningEvent, isSessionBudgetEvent, isToolCallEvent, isToolCompleteEvent, isToolErrorEvent };
3495
- export type { AgentCompleteEvent, AggregationFunction, AggregationSuggestion, AiChartType, AttachmentUploadResponse, BudgetReport, ChartCritiqueIssue, ChartCritiqueIssueCategory, ChartCritiqueIssueSeverity, ChartCritiqueReport, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, ChartJudgeRubric, ClientConfig, CompleteEvent, DataObservation, DataObservationKind, ErrorEvent, EvaluateParams, EvaluateResponse, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GeneratePipelineParams, GeneratePipelineResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, InvocationUsageSummary, JudgeParams, JudgeResponse, LlmStepEvent, Logger, Metadata, MutateNarrationReceipt, PipelineAgentName, PipelineStageReasoning, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, RubricScores, RunContext, SSEEvent, SessionBudgetEvent, StorytellingEffort, StorytellingOptions, Suggestion, ToolCallEvent, ToolCompleteEvent, ToolErrorEvent, UsageMetadata };
3655
+ export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, AttachmentResponseSchema, AttachmentUploadResponseSchema, AttachmentUploadSlotResponseSchema, ChartCritiqueIssueCategorySchema, ChartCritiqueIssueSchema, ChartCritiqueIssueSeveritySchema, ChartCritiqueReportSchema, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, ChartJudgeRubricSchema, CreateAttachmentUploadsParamsSchema, CreateAttachmentUploadsResponseSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeParamsSchema, GenerateNarrativeResponseSchema, GeneratePipelineParamsSchema, GeneratePipelineResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, JudgeParamsSchema, JudgeResponseSchema, MAX_BUDGET_COST_USD, MAX_BUDGET_TOTAL_TOKENS, MAX_BUDGET_WALL_CLOCK_MS, MAX_EXTRACT_ATTACHMENTS, MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES, MAX_EXTRACT_DOCUMENTS, MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES, MAX_EXTRACT_DOCUMENT_DECODED_BYTES, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_STAGED_FILE_BYTES, MAX_USER_PROMPT_LENGTH, MetadataSchema, MutateNarrationReceiptSchema, PipelineAgentNameSchema, PipelineStageReasoningSchema, RubricScoresSchema, RunContextSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isAgentCompleteEvent, isCompleteEvent, isErrorEvent, isGraphyApiError, isLlmStepEvent, isPreviewEvent, isProgressEvent, isReasoningEvent, isSessionBudgetEvent, isToolCallEvent, isToolCompleteEvent, isToolErrorEvent };
3656
+ export type { AgentCompleteEvent, AggregationFunction, AggregationSuggestion, AiChartType, AttachmentResponse, AttachmentUploadResponse, AttachmentUploadSlotResponse, BudgetReport, ChartCritiqueIssue, ChartCritiqueIssueCategory, ChartCritiqueIssueSeverity, ChartCritiqueReport, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, ChartJudgeRubric, ClientConfig, CompleteEvent, CreateAttachmentUploadsParams, CreateAttachmentUploadsResponse, DataObservation, DataObservationKind, ErrorEvent, EvaluateParams, EvaluateResponse, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GeneratePipelineParams, GeneratePipelineResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, InvocationUsageSummary, JudgeParams, JudgeResponse, LlmStepEvent, Logger, Metadata, MutateNarrationReceipt, PipelineAgentName, PipelineStageReasoning, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, RubricScores, RunContext, SSEEvent, SessionBudgetEvent, StorytellingEffort, StorytellingOptions, Suggestion, ToolCallEvent, ToolCompleteEvent, ToolErrorEvent, UploadAttachmentOptions, UsageMetadata };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{__awaiter as e,__asyncValues as t,__asyncGenerator as n,__await as i,__rest as o}from"tslib";import{z as r}from"zod";class a extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const s=e=>e instanceof a,l=e=>"progress"===e.type,c=e=>"complete"===e.type,m=e=>"error"===e.type,u=e=>"preview"===e.type,d=e=>"reasoning"===e.type,p=e=>"llm_step"===e.type,g=e=>"session_budget"===e.type,h=e=>"agent_complete"===e.type,f=e=>"tool_call"===e.type,b=e=>"tool_complete"===e.type,y=e=>"tool_error"===e.type;function v(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class w{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return l(e)}static isCompleteEvent(e){return c(e)}static isErrorEvent(e){return m(e)}stream(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i);return this.parseSSE(e)})}fetch(n,i,o,r){return e(this,void 0,void 0,function*(){var e,s,u,d,p;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${n}`);try{const y=yield this.makeRequest(n,i,r),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,b=t(this.parseSSE(y));!(e=(h=yield b.next()).done);f=!0){d=h.value,f=!1;const e=d;if(l(e)&&o&&o(e),c(e))return e.data;if(m(e)){const t=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${n} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(p=e.retryable)&&void 0!==p&&p})}}}catch(e){s={error:e}}finally{try{f||e||!(u=b.return)||(yield u.call(b))}finally{if(s)throw s.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${n} ${i}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${n} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${n} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,i);return yield e.json()})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return n(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),n=new TextDecoder;let o="",r="",s="";try{for(;;){const{done:e,value:a}=yield i(t.read());if(e)break;o+=n.decode(a,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const e of l)if(e.startsWith("event: "))r=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=v(r,JSON.parse(s));if(null===e){r="",s="";continue}if(yield yield i(e),"complete"===r||"error"===r)return yield i(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}r="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1,o="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const r=new URL(e,this.baseUrl);if(r.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${r}`);const s=new AbortController,l=setTimeout(()=>s.abort(),this.timeout),c=()=>s.abort();n&&n.addEventListener("abort",c);try{const l=yield fetch(r,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!l.ok){let r,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(r=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===r)&&(l.status>=500||429===l.status),m=new a(s,{status:l.status,code:r,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(r){if(r instanceof a)throw r;if(r instanceof Error&&"AbortError"===r.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),r;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,r),new a("Network error",{retryable:!0})}finally{clearTimeout(l),n&&n.removeEventListener("abort",c)}})}makeMultipartRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeout),l=()=>r.abort();n&&n.addEventListener("abort",l);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:r.signal});if(!s.ok){let o,r=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?r=t.message:"string"==typeof t.error&&(r=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=s.status>=500||429===s.status,c=new a(r,{status:s.status,code:o,retryable:l});if(l&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw c}return s}catch(o){if(o instanceof a)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw new a("Network error",{retryable:!0})}finally{clearTimeout(s),n&&n.removeEventListener("abort",l)}})}}const x=r.object({inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional(),wallClockMs:r.number()}),j=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()}),k=r.object({limits:r.object({maxWallClockMs:r.number().optional(),maxTotalTokens:r.number().optional(),maxCostUsd:r.number().optional(),trackUsage:r.boolean().optional()}),consumed:j,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});r.object({inputTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),modelName:r.string(),inputCachedTokens:r.number().optional(),inputUncachedTokens:r.number().optional(),cost:r.number().optional(),latencyMs:r.number().optional(),effort:r.string().optional(),providerReasoning:r.string().optional()});const T={usage:x.optional(),budget:k.optional()},$=r.enum(["EN_GB","EN_US"]),S=r.custom(e=>null!=e&&"object"==typeof e),C=r.enum(["low","medium","high"]),R=r.enum(["none","low","medium","high"]),E=r.enum(["agentic","fast"]),U=3e5,I=5e5,O=10,A=r.object({maxWallClockMs:r.number().positive().max(U).optional(),maxTotalTokens:r.number().int().positive().max(I).optional(),maxCostUsd:r.number().positive().max(10).optional(),trackUsage:r.boolean().optional()}),P=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()});r.object({limits:A,consumed:P,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});const M=r.object({callId:r.string().max(256).optional(),locale:$.optional(),effort:C.optional(),storytellingEffort:R.optional().default("low"),budget:A.optional(),executionMode:E.optional(),enforceTableRowCap:r.boolean().optional()}),B=r.object({steps:r.array(r.string()),postProcess:r.object({measureRelevance:r.enum(["prompt-named","derived","magnitude"]).optional(),grain:r.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:r.string().optional(),comparison:r.string().optional()}).optional(),droppedMeasures:r.array(r.string()).optional(),rowCount:r.number().int().nonnegative(),totalRowCountBeforeSlice:r.number().int().positive().optional(),displayedRowCount:r.number().int().nonnegative().optional(),columnKeys:r.array(r.string()),activeFilters:r.array(r.string()).optional(),grainSummary:r.string().optional()}),F=r.object({runId:r.string(),trackingId:r.string(),callId:r.string().optional()}),q=1e4,D=r.enum(["comparison","relationship","distribution","composition"]),_=r.object({config:S,userPrompt:r.string().max(q).optional().default(""),metadata:M.optional(),chartFamily:D.optional()}),N=_.extend({maxSuggestionCount:r.number().int().min(1).max(4).optional()}),K=r.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),L=r.object({dataPrepPrompt:r.string(),chartType:K,summary:r.string()}),W=_.extend({userPrompt:r.string().max(q),mutationReceipt:B.optional(),exploreFindingSummary:r.string().max(500).optional()}),G=r.object({response:r.object({message:r.string()}),config:S,run:F.optional()}).extend(T),z=r.object({suggestions:r.array(L),run:F.optional()}).extend(T),H=r.object({finding:r.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:r.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:r.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:r.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:r.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:D.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:r.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),J=r.object({topic:r.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:r.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:r.number().int().min(1).describe("Number of findings in this story."),findings:r.array(H).describe("Child findings, sorted by quadrant score desc.")}),X=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),stories:r.array(J),run:F.optional()}).extend(T);_.extend({mutationReceipt:B.optional()});const Q=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:S,run:F.optional()}).extend(T),V=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:S,mutationReceipt:B.optional(),warnings:r.array(r.string()).optional(),run:F.optional()}).extend(T),Y=r.enum(["explore","mutate","narrate","annotate"]),Z=r.object({agent:Y,summary:r.string(),steps:r.array(r.string()).optional()}),ee=_.extend({userPrompt:r.string().max(q),stages:r.array(Y).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:r.string().max(500).optional()}),te=V.extend({reasoning:r.array(Z),stories:r.array(J).optional()}),ne=r.enum(["high","medium","low"]),ie=r.object({confidence:ne,needsUserInput:r.boolean(),warnings:r.array(r.string()),cellConfidence:r.array(r.object({rowIndex:r.number().int().nonnegative(),columnKey:r.string(),confidence:ne,quote:r.string().optional()})).optional()}),oe=r.object({score:r.number().min(0).max(1),issues:r.array(r.string()),sufficient:r.boolean(),summary:r.string()}),re=5e5,ae=8,se=2097152,le=7340032,ce=2,me=6291456,ue=8388608,de=2,pe=me,ge=ue,he=12582912,fe=12;function be(e){return 4*Math.ceil(e/3)}const ye=be(se),ve=be(le),we=be(me),xe=be(ue),je=be(pe),ke=be(ge),Te=be(he);function $e(e){return e.replace(/\s+/g,"")}function Se(e){const t=$e(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const Ce=/^image\/(png|jpeg|jpg|webp|gif)$/i,Re=r.object({mimeType:r.string().min(1).refine(e=>Ce.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:r.string().min(1).max(ye).refine(Se,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Ee=r.enum(["image","document","spreadsheet"]),Ue=Re.extend({kind:r.literal("image")}),Ie=r.object({kind:r.literal("document"),mimeType:r.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:r.string().min(1).max(we).refine(Se,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Oe=r.object({kind:r.literal("spreadsheet"),mimeType:r.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:r.string().min(1).max(je).refine(Se,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:r.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),Ae=r.discriminatedUnion("kind",[Ue,Ie,Oe]),Pe=r.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),Me=r.object({id:r.string().uuid(),uri:r.string(),kind:Ee,mimeType:r.string(),filename:r.string().optional(),sizeBytes:r.number().int().positive(),expiresAt:r.string().datetime()}),Be=r.object({sourceText:r.string().max(re).default(""),images:r.array(Re).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:r.array(Ae).max(12).optional(),attachmentRefs:r.array(Pe).max(12).optional(),metadata:M.optional()}).superRefine((e,t)=>{var n,i,o;const r=e.sourceText.trim(),a=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(i=e.attachments)&&void 0!==i?i:[],l=null!==(o=e.attachmentRefs)&&void 0!==o?o:[];if(a.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(l.length>0&&s.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or inline `attachments`, not both.",path:["attachmentRefs"]});if(l.length>0&&a.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or deprecated `images`, not both.",path:["attachmentRefs"]});if(0===r.length&&0===a.length&&0===s.length&&0===l.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(l.length>0)return;if(a.length>0){a.reduce((e,t)=>e+$e(t.dataBase64).length,0)>ve&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let c=0,m=0,u=0,d=0,p=0,g=0,h=0;for(const e of s){const t=$e(e.dataBase64).length;switch(h+=t,e.kind){case"image":c+=1,d+=t;break;case"document":m+=1,p+=t;break;case"spreadsheet":u+=1,g+=t}}c>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),u>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=c<=8&&m<=2&&u<=2;s.length>0&&f&&(d>ve&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>xe&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>ke&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>Te&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function Fe(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:$e(e.dataBase64)}}function qe(e){return{kind:"document",mimeType:"application/pdf",dataBase64:$e(e.dataBase64)}}function De(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:$e(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const _e=r.object({response:r.object({message:r.string()}),config:S,extractMeta:ie.nullable(),lastAccuracyEvaluation:oe.optional(),run:F.optional()}).extend(T),Ne=r.object({config:S,response:r.object({message:r.string(),steps:r.array(r.string())}),run:F.optional()}).extend(T),Ke=z,Le=r.enum(["deal-breaker","pro","con","family","continuity"]),We=r.object({kind:Le,label:r.string(),weight:r.number(),reason:r.string()}),Ge=r.enum(["ok","disqualified"]),ze=r.object({rank:r.number().int().positive(),type:K,score:r.number(),verdict:Ge,factors:r.array(We)}),He=r.object({config:S,chartFamily:D.optional(),metadata:M.optional()}),Je=r.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),Xe=r.object({kind:Je,message:r.string()}),Qe=r.enum(["sum","avg","count","min","max"]),Ve=r.object({dimensionName:r.string(),dimensionLabel:r.string(),measureName:r.string().nullable(),measureLabel:r.string().nullable(),fn:Qe,chartType:K,score:r.number(),message:r.string()}),Ye=r.object({ranking:r.array(ze),observations:r.array(Xe).optional().default([]),suggestions:r.array(Ve).optional().default([]),run:F.optional()}),Ze=r.object({prompt:r.string(),datasetSummary:r.string().optional(),mustShow:r.array(r.string()).optional(),unacceptable:r.array(r.string()).optional(),acceptableChartFamilies:r.array(r.string()).optional()}),et=r.object({config:S.optional(),chartImage:r.string().optional(),data:r.unknown().optional(),rubric:Ze.optional(),userPrompt:r.string().optional(),metadata:M.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),tt=r.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),nt=r.enum(["info","low","medium","high"]),it=r.object({category:tt,severity:nt,observation:r.string(),rationale:r.string().optional(),suggestedChange:r.string().optional(),configPaths:r.array(r.string()).optional()}),ot=r.object({overallSummary:r.string(),overallSeverity:r.enum(["none","low","medium","high"]).optional(),issues:r.array(it)}),rt=r.object({dataFidelity:r.number().min(0).max(1),promptRelevance:r.number().min(0).max(1),chartTypeAppropriateness:r.number().min(0).max(1),readability:r.number().min(0).max(1),honesty:r.number().min(0).max(1),composite:r.number().min(0).max(1),rationale:r.string().optional()}),at=r.object({capturedAt:r.string(),chartId:r.string()}),st=r.object({response:r.object({message:r.string(),steps:r.array(r.string()),critiqueCommitted:r.boolean()}),critiqueReport:ot.nullable(),chartVisionAudit:at.nullable().optional().default(null),rubricScores:rt.nullable().optional().default(null),run:F.optional()}).extend(T),lt="/api/v0";class ct{constructor(e){this.client=new w(e)}generateGraph(t,n,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,r=o(t,["storytellingOptions"]),a=yield this.client.fetch(`${lt}/generate`,r,n,i),s=Ne.parse(a);return this.stripStorytelling(s,e)})}generateGraphStream(t,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,i=o(t,["storytellingOptions"]),r=yield this.client.stream(`${lt}/generate`,i,n);return this.wrapStreamWithStorytellingStripping(r,e)})}generateNarrative(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/narrate`,t,n,i);return G.parse(e)})}generateNarrativeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/narrate`,t,n)})}generateSuggestions(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/suggestions`,t,n,i);return z.parse(e)})}generateSuggestionsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/suggestions`,t,n)})}generateExploration(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/explore`,t,n,i);return X.parse(e)})}generateExplorationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/explore`,t,n)})}generateAnnotations(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/annotate`,t,n,i);return Q.parse(e)})}generateAnnotationsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/annotate`,t,n)})}generateMutation(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/mutate`,t,n,i);return V.parse(e)})}generateMutationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/mutate`,t,n)})}generatePipeline(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/pipeline`,t,n,i);return te.parse(e)})}generatePipelineStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/pipeline`,t,n)})}evaluate(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/evaluate`,t,void 0,n);return Ye.parse(e)})}judge(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/judge`,t,void 0,n);return st.parse(e)})}judgeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/judge`,t,n)})}extractFromProse(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${lt}/extract`,t,n,i);return _e.parse(e)})}extractFromProseStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${lt}/extract`,t,n)})}uploadAttachment(t,n,i){return e(this,void 0,void 0,function*(){const e=new FormData,o=null==n?void 0:n.filename;"undefined"!=typeof File&&t instanceof File?e.append("file",t):o?e.append("file",t,o):e.append("file",t,"upload"),o&&e.append("filename",o);const r=yield this.client.uploadMultipart(`${lt}/attachments`,e,i);return Me.parse(r)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,o){return n(this,arguments,function*(){var n,r,a,s;try{for(var l,m=!0,u=t(e);!(n=(l=yield i(u.next())).done);m=!0){s=l.value,m=!1;const e=s;if(c(e)){const t=this.stripStorytelling(e.data,o);yield yield i(Object.assign(Object.assign({},e),{data:t}))}else yield yield i(e)}}catch(e){r={error:e}}finally{try{m||n||!(a=u.return)||(yield i(a.call(u)))}finally{if(r)throw r.error}}})}}export{Qe as AggregationFunctionSchema,Ve as AggregationSuggestionSchema,K as AiChartTypeEnum,Me as AttachmentUploadResponseSchema,tt as ChartCritiqueIssueCategorySchema,it as ChartCritiqueIssueSchema,nt as ChartCritiqueIssueSeveritySchema,ot as ChartCritiqueReportSchema,D as ChartFamilySchema,ze as ChartFitEntrySchema,Le as ChartFitFactorKindSchema,We as ChartFitFactorSchema,Ge as ChartFitVerdictSchema,Ze as ChartJudgeRubricSchema,Je as DataObservationKindSchema,Xe as DataObservationSchema,He as EvaluateParamsSchema,Ye as EvaluateResponseSchema,E as ExecutionModeSchema,H as ExploreFindingSchema,J as ExploreStorySchema,oe as ExtractAccuracyEvaluationSchema,Ae as ExtractAttachmentInputSchema,Ee as ExtractAttachmentKindSchema,ne as ExtractConfidenceSchema,Be as ExtractFromProseParamsSchema,_e as ExtractFromProseResponseSchema,ie as ExtractMetaSchema,Q as GenerateAnnotationsResponseSchema,X as GenerateExplorationResponseSchema,Ne as GenerateGraphResponseSchema,Ke as GenerateGraphSuggestionsResponseSchema,V as GenerateMutationResponseSchema,W as GenerateNarrativeParamsSchema,G as GenerateNarrativeResponseSchema,ee as GeneratePipelineParamsSchema,te as GeneratePipelineResponseSchema,N as GenerateSuggestionsParamsSchema,z as GenerateSuggestionsResponseSchema,_ as GraphGenerationRequestSchema,ct as GraphyAiSdk,a as GraphyApiError,A as InvocationBudgetSchema,C as InvocationEffortSchema,et as JudgeParamsSchema,st as JudgeResponseSchema,O as MAX_BUDGET_COST_USD,I as MAX_BUDGET_TOTAL_TOKENS,U as MAX_BUDGET_WALL_CLOCK_MS,fe as MAX_EXTRACT_ATTACHMENTS,he as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,ce as MAX_EXTRACT_DOCUMENTS,ue as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,me as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,ae as MAX_EXTRACT_IMAGES,le as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,se as MAX_EXTRACT_IMAGE_DECODED_BYTES,de as MAX_EXTRACT_SPREADSHEETS,ge as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,pe as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,re as MAX_SOURCE_TEXT_LENGTH,q as MAX_USER_PROMPT_LENGTH,M as MetadataSchema,B as MutateNarrationReceiptSchema,Y as PipelineAgentNameSchema,Z as PipelineStageReasoningSchema,rt as RubricScoresSchema,F as RunContextSchema,R as StorytellingEffortSchema,L as SuggestionSchema,Fe as buildImageAttachment,qe as buildPdfAttachment,De as buildSpreadsheetAttachment,h as isAgentCompleteEvent,c as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,p as isLlmStepEvent,u as isPreviewEvent,l as isProgressEvent,d as isReasoningEvent,g as isSessionBudgetEvent,f as isToolCallEvent,b as isToolCompleteEvent,y as isToolErrorEvent};
1
+ import{__awaiter as e,__asyncValues as t,__asyncGenerator as n,__await as i,__rest as o}from"tslib";import{z as r}from"zod";class a extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const s=e=>e instanceof a,l=e=>"progress"===e.type,c=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type,p=e=>"llm_step"===e.type,g=e=>"session_budget"===e.type,h=e=>"agent_complete"===e.type,f=e=>"tool_call"===e.type,b=e=>"tool_complete"===e.type,y=e=>"tool_error"===e.type;function v(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class x{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return l(e)}static isCompleteEvent(e){return c(e)}static isErrorEvent(e){return m(e)}stream(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i);return this.parseSSE(e)})}fetch(n,i,o,r){return e(this,void 0,void 0,function*(){var e,s,d,u,p;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${n}`);try{const y=yield this.makeRequest(n,i,r),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,b=t(this.parseSSE(y));!(e=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(l(e)&&o&&o(e),c(e))return e.data;if(m(e)){const t=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${n} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(p=e.retryable)&&void 0!==p&&p})}}}catch(e){s={error:e}}finally{try{f||e||!(d=b.return)||(yield d.call(b))}finally{if(s)throw s.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${n} ${i}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${n} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${n} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,i);return yield e.json()})}get(t,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,void 0,n,1,"GET");return yield e.json()})}postJson(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i,1,"POST");return yield e.json()})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return n(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),n=new TextDecoder;let o="",r="",s="";try{for(;;){const{done:e,value:a}=yield i(t.read());if(e)break;o+=n.decode(a,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const e of l)if(e.startsWith("event: "))r=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=v(r,JSON.parse(s));if(null===e){r="",s="";continue}if(yield yield i(e),"complete"===r||"error"===r)return yield i(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}r="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1,o="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const r=new URL(e,this.baseUrl);if(r.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${r}`);const s=new AbortController,l=setTimeout(()=>s.abort(),this.timeout),c=()=>s.abort();n&&n.addEventListener("abort",c);try{const l=yield fetch(r,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!l.ok){let r,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(r=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===r)&&(l.status>=500||429===l.status),m=new a(s,{status:l.status,code:r,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(r){if(r instanceof a)throw r;if(r instanceof Error&&"AbortError"===r.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),r;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,r),new a("Network error",{retryable:!0})}finally{clearTimeout(l),n&&n.removeEventListener("abort",c)}})}makeMultipartRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeout),l=()=>r.abort();n&&n.addEventListener("abort",l);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:r.signal});if(!s.ok){let o,r=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?r=t.message:"string"==typeof t.error&&(r=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=s.status>=500||429===s.status,c=new a(r,{status:s.status,code:o,retryable:l});if(l&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw c}return s}catch(o){if(o instanceof a)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw new a("Network error",{retryable:!0})}finally{clearTimeout(s),n&&n.removeEventListener("abort",l)}})}}const w={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".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};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@graphysdk/agents-sdk",
3
3
  "author": "Graphy",
4
- "version": "1.6.2-beta.1782204737314",
4
+ "version": "1.7.0",
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.6.2-beta.1782204737314"
21
+ "@graphysdk/core": "1.7.0"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@rollup/plugin-commonjs": "^28.0.6",