@graphysdk/agents-sdk 1.3.0 → 1.4.0-beta.1778840000414

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("tslib"),t=require("zod");class r extends Error{constructor(e,t){var r;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!==(r=null==t?void 0:t.retryable)&&void 0!==r&&r}}const s=e=>"progress"===e.type,i=e=>"complete"===e.type,a=e=>"error"===e.type;class n{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 s(e)}static isCompleteEvent(e){return i(e)}static isErrorEvent(e){return a(e)}stream(t,r,s){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,s);return this.parseSSE(e)})}fetch(t,n,o,c){return e.__awaiter(this,void 0,void 0,function*(){var m,l,d,p,g;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,n,c),x=b.headers.get("content-type");if(null==x?void 0:x.includes("text/event-stream")){try{for(var u,f=!0,y=e.__asyncValues(this.parseSSE(b));!(m=(u=yield y.next()).done);f=!0){p=u.value,f=!1;const e=p;if(s(e)&&o&&o(e),i(e))return e.data;if(a(e)){const s=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${t} ${s}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(g=e.retryable)&&void 0!==g&&g})}}}catch(e){l={error:e}}finally{try{f||m||!(d=y.return)||(yield d.call(y))}finally{if(l)throw l.error}}const n=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${n}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const s=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${s}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-h;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}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 r("Response body is null");const s=t.body.getReader(),i=new TextDecoder;let a="",n="",o="";try{for(;;){const{done:t,value:r}=yield e.__await(s.read());if(t)break;a+=i.decode(r,{stream:!0});const c=a.split(/\r?\n/);a=c.pop()||"";for(const t of c)if(t.startsWith("event: "))n=t.slice(7).trim();else if(t.startsWith("data: "))o+=(o?"\n":"")+t.slice(6);else if(""===t.trim()&&o){try{const t=JSON.parse(o);let r;if("progress"===n){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===n)r={type:"complete",data:t};else if("error"===n){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===n){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==n){n="",o="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===n||"error"===n)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}n="",o=""}}}finally{s.releaseLock()}})}makeRequest(t,s,i){return e.__awaiter(this,arguments,void 0,function*(e,t,s,i=1,a="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const n=new URL(e,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${n}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),m=()=>o.abort();s&&s.addEventListener("abort",m);try{const c=yield fetch(n,Object.assign({method:a,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:o.signal},"POST"===a&&{body:JSON.stringify(t)}));if(!c.ok){const n=c.status>=500||429===c.status;let o,m=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?m=t.message:"string"==typeof t.error&&(m=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=new r(m,{status:c.status,code:o,retryable:n});if(n&&i<this.retryConfig.attempts&&!(null==s?void 0:s.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,s,i+1,a)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${m}`),l}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),n;if(i<this.retryConfig.attempts&&!(null==s?void 0:s.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,s,i+1,a)}throw this.logger.error(`${this.tag} Network error: ${e}`,n),new r("Network error",{retryable:!0})}finally{clearTimeout(c),s&&s.removeEventListener("abort",m)}})}}const o=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),m=t.z.enum(["low","medium","high"]),l=t.z.enum(["none","low","medium","high"]),d=t.z.enum(["agentic","fast"]),p=t.z.object({maxWallClockMs:t.z.number().positive().optional(),maxTotalTokens:t.z.number().int().positive().optional(),maxCostUsd:t.z.number().positive().optional()}),g=t.z.object({callId:t.z.string().max(256),locale:o.optional(),effort:m.optional(),storytellingEffort:l.optional().default("low"),budget:p.optional(),executionMode:d.optional()}),h=t.z.object({config:c,userPrompt:t.z.string().max(1e4).optional().default(""),metadata:g.optional()}),u=h.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),f=t.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),y=t.z.object({dataPrepPrompt:t.z.string(),chartType:f,summary:t.z.string()}),b=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),x=t.z.object({suggestions:t.z.array(y)}),v=t.z.enum(["comparison","relationship","distribution","composition"]),_=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:v.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.")}),w=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(_).describe("Child findings, sorted by quadrant score desc.")}),E=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(w)}),z=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),S=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),T=t.z.enum(["high","medium","low"]),A=t.z.object({confidence:T,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:T,quote:t.z.string().optional()})).optional()}),C=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()}),j=5e5,$=2097152,R=7340032,O=6291456,D=8388608,k=O,M=D,I=12582912;function P(e){return 4*Math.ceil(e/3)}const G=P($),B=P(R),X=P(O),N=P(D),U=P(k),q=P(M),F=P(I);function K(e){return e.replace(/\s+/g,"")}function L(e){const t=K(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const H=/^image\/(png|jpeg|jpg|webp|gif)$/i,Y=t.z.object({mimeType:t.z.string().min(1).refine(e=>H.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(G).refine(L,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),W=t.z.enum(["image","document","spreadsheet"]),J=Y.extend({kind:t.z.literal("image")}),V=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(X).refine(L,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Z=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(U).refine(L,{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"]}),Q=t.z.discriminatedUnion("kind",[J,V,Z]),ee=t.z.object({sourceText:t.z.string().max(j).default(""),images:t.z.array(Y).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(Q).max(12).optional(),metadata:g.optional()}).superRefine((e,t)=>{var r,s;const i=e.sourceText.trim(),a=null!==(r=e.images)&&void 0!==r?r:[],n=null!==(s=e.attachments)&&void 0!==s?s:[];if(a.length>0&&n.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===i.length&&0===a.length&&0===n.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(a.length>0){a.reduce((e,t)=>e+K(t.dataBase64).length,0)>B&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,m=0,l=0,d=0,p=0,g=0;for(const e of n){const t=K(e.dataBase64).length;switch(g+=t,e.kind){case"image":o+=1,l+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":m+=1,p+=t}}o>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const h=o<=8&&c<=2&&m<=2;n.length>0&&h&&(l>B&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>N&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>q&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>F&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const te=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:A.nullable(),lastAccuracyEvaluation:C.optional()}),re=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),se=x,ie="/api/v0";exports.AiChartTypeEnum=f,exports.ChartFamilySchema=v,exports.ExecutionModeSchema=d,exports.ExploreFindingSchema=_,exports.ExploreStorySchema=w,exports.ExtractAccuracyEvaluationSchema=C,exports.ExtractAttachmentInputSchema=Q,exports.ExtractAttachmentKindSchema=W,exports.ExtractConfidenceSchema=T,exports.ExtractFromProseParamsSchema=ee,exports.ExtractFromProseResponseSchema=te,exports.ExtractMetaSchema=A,exports.GenerateAnnotationsResponseSchema=z,exports.GenerateExplorationResponseSchema=E,exports.GenerateGraphResponseSchema=re,exports.GenerateGraphSuggestionsResponseSchema=se,exports.GenerateMutationResponseSchema=S,exports.GenerateNarrativeResponseSchema=b,exports.GenerateSuggestionsParamsSchema=u,exports.GenerateSuggestionsResponseSchema=x,exports.GraphGenerationRequestSchema=h,exports.GraphyAiSdk=class{constructor(e){this.client=new n(e)}generateGraph(t,r,s){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,a=e.__rest(t,["storytellingOptions"]),n=yield this.client.fetch(`${ie}/generate`,a,r,s),o=re.parse(n);return this.stripStorytelling(o,i)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:s}=t,i=e.__rest(t,["storytellingOptions"]),a=yield this.client.stream(`${ie}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(a,s)})}generateNarrative(t,r,s){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ie}/narrate`,t,r,s);return b.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ie}/narrate`,t,r)})}generateSuggestions(t,r,s){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ie}/suggestions`,t,r,s);return x.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ie}/suggestions`,t,r)})}generateExploration(t,r,s){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ie}/explore`,t,r,s);return E.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ie}/explore`,t,r)})}generateAnnotations(t,r,s){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ie}/annotate`,t,r,s);return z.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ie}/annotate`,t,r)})}generateMutation(t,r,s){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ie}/mutate`,t,r,s);return S.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ie}/mutate`,t,r)})}extractFromProse(t,r,s){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ie}/extract`,t,r,s);return te.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${ie}/extract`,t,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(t,r){return e.__asyncGenerator(this,arguments,function*(){var s,a,n,o;try{for(var c,m=!0,l=e.__asyncValues(t);!(s=(c=yield e.__await(l.next())).done);m=!0){o=c.value,m=!1;const t=o;if(i(t)){const s=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:s}))}else yield yield e.__await(t)}}catch(e){a={error:e}}finally{try{m||s||!(n=l.return)||(yield e.__await(n.call(l)))}finally{if(a)throw a.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=p,exports.InvocationEffortSchema=m,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=I,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=D,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=O,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=R,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=$,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=M,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=k,exports.MAX_SOURCE_TEXT_LENGTH=j,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=g,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=y,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:K(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:K(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:K(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=i,exports.isErrorEvent=a,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=s,exports.isReasoningEvent=e=>"reasoning"===e.type;
1
+ "use strict";var e=require("tslib"),t=require("zod");class r extends Error{constructor(e,t){var r;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!==(r=null==t?void 0:t.retryable)&&void 0!==r&&r}}const a=e=>"progress"===e.type,i=e=>"complete"===e.type,s=e=>"error"===e.type;class n{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 i(e)}static isErrorEvent(e){return s(e)}stream(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,a);return this.parseSSE(e)})}fetch(t,n,o,c){return e.__awaiter(this,void 0,void 0,function*(){var m,l,d,p,h;const u=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,n,c),x=b.headers.get("content-type");if(null==x?void 0:x.includes("text/event-stream")){try{for(var g,f=!0,y=e.__asyncValues(this.parseSSE(b));!(m=(g=yield y.next()).done);f=!0){p=g.value,f=!1;const e=p;if(a(e)&&o&&o(e),i(e))return e.data;if(s(e)){const a=Date.now()-u;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(h=e.retryable)&&void 0!==h&&h})}}}catch(e){l={error:e}}finally{try{f||m||!(d=y.return)||(yield d.call(y))}finally{if(l)throw l.error}}const n=Date.now()-u;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${n}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const a=Date.now()-u;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-u;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}}})}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 r("Response body is null");const a=t.body.getReader(),i=new TextDecoder;let s="",n="",o="";try{for(;;){const{done:t,value:r}=yield e.__await(a.read());if(t)break;s+=i.decode(r,{stream:!0});const c=s.split(/\r?\n/);s=c.pop()||"";for(const t of c)if(t.startsWith("event: "))n=t.slice(7).trim();else if(t.startsWith("data: "))o+=(o?"\n":"")+t.slice(6);else if(""===t.trim()&&o){try{const t=JSON.parse(o);let r;if("progress"===n){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===n)r={type:"complete",data:t};else if("error"===n){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===n){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==n){n="",o="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===n||"error"===n)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}n="",o=""}}}finally{a.releaseLock()}})}makeRequest(t,a,i){return e.__awaiter(this,arguments,void 0,function*(e,t,a,i=1,s="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const n=new URL(e,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${n}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),m=()=>o.abort();a&&a.addEventListener("abort",m);try{const c=yield fetch(n,Object.assign({method:s,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:o.signal},"POST"===s&&{body:JSON.stringify(t)}));if(!c.ok){const n=c.status>=500||429===c.status;let o,m=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?m=t.message:"string"==typeof t.error&&(m=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=new r(m,{status:c.status,code:o,retryable:n});if(n&&i<this.retryConfig.attempts&&!(null==a?void 0:a.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,a,i+1,s)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${m}`),l}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),n;if(i<this.retryConfig.attempts&&!(null==a?void 0:a.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,a,i+1,s)}throw this.logger.error(`${this.tag} Network error: ${e}`,n),new r("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",m)}})}}const o=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),m=t.z.enum(["low","medium","high"]),l=t.z.enum(["none","low","medium","high"]),d=t.z.enum(["agentic","fast"]),p=t.z.object({maxWallClockMs:t.z.number().positive().optional(),maxTotalTokens:t.z.number().int().positive().optional(),maxCostUsd:t.z.number().positive().optional()}),h=t.z.object({callId:t.z.string().max(256),locale:o.optional(),effort:m.optional(),storytellingEffort:l.optional().default("low"),budget:p.optional(),executionMode:d.optional()}),u=t.z.object({config:c,userPrompt:t.z.string().max(1e4).optional().default(""),metadata:h.optional()}),g=u.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),f=t.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),y=t.z.object({dataPrepPrompt:t.z.string(),chartType:f,summary:t.z.string()}),b=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),x=t.z.object({suggestions:t.z.array(y)}),v=t.z.enum(["comparison","relationship","distribution","composition"]),z=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:v.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.")}),_=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(z).describe("Child findings, sorted by quadrant score desc.")}),E=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(_)}),w=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),S=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),T=t.z.enum(["high","medium","low"]),A=t.z.object({confidence:T,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:T,quote:t.z.string().optional()})).optional()}),C=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()}),j=5e5,$=2097152,R=7340032,k=6291456,O=8388608,D=k,M=O,P=12582912;function I(e){return 4*Math.ceil(e/3)}const G=I($),B=I(R),X=I(k),N=I(O),F=I(D),U=I(M),q=I(P);function K(e){return e.replace(/\s+/g,"")}function H(e){const t=K(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const L=/^image\/(png|jpeg|jpg|webp|gif)$/i,Y=t.z.object({mimeType:t.z.string().min(1).refine(e=>L.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(G).refine(H,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),W=t.z.enum(["image","document","spreadsheet"]),V=Y.extend({kind:t.z.literal("image")}),J=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(X).refine(H,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Z=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(F).refine(H,{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"]}),Q=t.z.discriminatedUnion("kind",[V,J,Z]),ee=t.z.object({sourceText:t.z.string().max(j).default(""),images:t.z.array(Y).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(Q).max(12).optional(),metadata:h.optional()}).superRefine((e,t)=>{var r,a;const i=e.sourceText.trim(),s=null!==(r=e.images)&&void 0!==r?r:[],n=null!==(a=e.attachments)&&void 0!==a?a:[];if(s.length>0&&n.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===i.length&&0===s.length&&0===n.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(s.length>0){s.reduce((e,t)=>e+K(t.dataBase64).length,0)>B&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,m=0,l=0,d=0,p=0,h=0;for(const e of n){const t=K(e.dataBase64).length;switch(h+=t,e.kind){case"image":o+=1,l+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":m+=1,p+=t}}o>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const u=o<=8&&c<=2&&m<=2;n.length>0&&u&&(l>B&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>N&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>U&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>q&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const te=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:A.nullable(),lastAccuracyEvaluation:C.optional()}),re=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),ae=x,ie=t.z.enum(["deal-breaker","pro","con","family","specificity","continuity"]),se=t.z.object({kind:ie,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),ne=t.z.enum(["ok","disqualified"]),oe=t.z.object({rank:t.z.number().int().positive(),type:f,score:t.z.number(),verdict:ne,factors:t.z.array(se)}),ce=u.extend({chartFamily:v.optional()}),me=t.z.enum(["needs-time-aggregation","needs-dimension-aggregation","drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction"]),le=t.z.object({kind:me,message:t.z.string()}),de=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),topPick:oe}),pe=t.z.object({ranking:t.z.array(oe),hints:t.z.array(le).optional().default([]),alternatives:t.z.array(de).optional().default([])}),he="/api/v0";exports.AiChartTypeEnum=f,exports.ChartFamilySchema=v,exports.ChartFitEntrySchema=oe,exports.ChartFitFactorKindSchema=ie,exports.ChartFitFactorSchema=se,exports.ChartFitVerdictSchema=ne,exports.DimensionAlternativeSchema=de,exports.EvaluateParamsSchema=ce,exports.EvaluateResponseSchema=pe,exports.EvaluationHintKindSchema=me,exports.EvaluationHintSchema=le,exports.ExecutionModeSchema=d,exports.ExploreFindingSchema=z,exports.ExploreStorySchema=_,exports.ExtractAccuracyEvaluationSchema=C,exports.ExtractAttachmentInputSchema=Q,exports.ExtractAttachmentKindSchema=W,exports.ExtractConfidenceSchema=T,exports.ExtractFromProseParamsSchema=ee,exports.ExtractFromProseResponseSchema=te,exports.ExtractMetaSchema=A,exports.GenerateAnnotationsResponseSchema=w,exports.GenerateExplorationResponseSchema=E,exports.GenerateGraphResponseSchema=re,exports.GenerateGraphSuggestionsResponseSchema=ae,exports.GenerateMutationResponseSchema=S,exports.GenerateNarrativeResponseSchema=b,exports.GenerateSuggestionsParamsSchema=g,exports.GenerateSuggestionsResponseSchema=x,exports.GraphGenerationRequestSchema=u,exports.GraphyAiSdk=class{constructor(e){this.client=new n(e)}generateGraph(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,s=e.__rest(t,["storytellingOptions"]),n=yield this.client.fetch(`${he}/generate`,s,r,a),o=re.parse(n);return this.stripStorytelling(o,i)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,i=e.__rest(t,["storytellingOptions"]),s=yield this.client.stream(`${he}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(s,a)})}generateNarrative(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${he}/narrate`,t,r,a);return b.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${he}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${he}/suggestions`,t,r,a);return x.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${he}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${he}/explore`,t,r,a);return E.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${he}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${he}/annotate`,t,r,a);return w.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${he}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${he}/mutate`,t,r,a);return S.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${he}/mutate`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${he}/evaluate`,t,void 0,r);return pe.parse(e)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${he}/extract`,t,r,a);return te.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${he}/extract`,t,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(t,r){return e.__asyncGenerator(this,arguments,function*(){var a,s,n,o;try{for(var c,m=!0,l=e.__asyncValues(t);!(a=(c=yield e.__await(l.next())).done);m=!0){o=c.value,m=!1;const t=o;if(i(t)){const a=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){s={error:e}}finally{try{m||a||!(n=l.return)||(yield e.__await(n.call(l)))}finally{if(s)throw s.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=p,exports.InvocationEffortSchema=m,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=P,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=O,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=k,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=R,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=$,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=M,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=D,exports.MAX_SOURCE_TEXT_LENGTH=j,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=h,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=y,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:K(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:K(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:K(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=i,exports.isErrorEvent=s,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,exports.isReasoningEvent=e=>"reasoning"===e.type;
package/dist/index.d.ts CHANGED
@@ -427,6 +427,7 @@ declare const AiChartTypeEnum: z.ZodEnum<{
427
427
  bubble: "bubble";
428
428
  waterfall: "waterfall";
429
429
  table: "table";
430
+ mekko: "mekko";
430
431
  }>;
431
432
  type AiChartType = z.infer<typeof AiChartTypeEnum>;
432
433
  declare const SuggestionSchema: z.ZodObject<{
@@ -450,6 +451,7 @@ declare const SuggestionSchema: z.ZodObject<{
450
451
  bubble: "bubble";
451
452
  waterfall: "waterfall";
452
453
  table: "table";
454
+ mekko: "mekko";
453
455
  }>;
454
456
  summary: z.ZodString;
455
457
  }, z.core.$strip>;
@@ -484,6 +486,7 @@ declare const GenerateSuggestionsResponseSchema: z.ZodObject<{
484
486
  bubble: "bubble";
485
487
  waterfall: "waterfall";
486
488
  table: "table";
489
+ mekko: "mekko";
487
490
  }>;
488
491
  summary: z.ZodString;
489
492
  }, z.core.$strip>>;
@@ -827,10 +830,315 @@ declare const GenerateGraphSuggestionsResponseSchema: z.ZodObject<{
827
830
  bubble: "bubble";
828
831
  waterfall: "waterfall";
829
832
  table: "table";
833
+ mekko: "mekko";
830
834
  }>;
831
835
  summary: z.ZodString;
832
836
  }, z.core.$strip>>;
833
837
  }, z.core.$strip>;
838
+ /** Kind of factor that contributed to a chart-type's score. Mirrors `Factor.kind` in agents-api. */
839
+ declare const ChartFitFactorKindSchema: z.ZodEnum<{
840
+ "deal-breaker": "deal-breaker";
841
+ pro: "pro";
842
+ con: "con";
843
+ family: "family";
844
+ specificity: "specificity";
845
+ continuity: "continuity";
846
+ }>;
847
+ type ChartFitFactorKind = z.infer<typeof ChartFitFactorKindSchema>;
848
+ /** A single factor entry on a ranked chart-fit result. */
849
+ declare const ChartFitFactorSchema: z.ZodObject<{
850
+ kind: z.ZodEnum<{
851
+ "deal-breaker": "deal-breaker";
852
+ pro: "pro";
853
+ con: "con";
854
+ family: "family";
855
+ specificity: "specificity";
856
+ continuity: "continuity";
857
+ }>;
858
+ label: z.ZodString;
859
+ weight: z.ZodNumber;
860
+ reason: z.ZodString;
861
+ }, z.core.$strip>;
862
+ type ChartFitFactor = z.infer<typeof ChartFitFactorSchema>;
863
+ declare const ChartFitVerdictSchema: z.ZodEnum<{
864
+ ok: "ok";
865
+ disqualified: "disqualified";
866
+ }>;
867
+ type ChartFitVerdict = z.infer<typeof ChartFitVerdictSchema>;
868
+ /** A single entry in the public chart-fit ranking returned by `POST /v0/evaluate`. */
869
+ declare const ChartFitEntrySchema: z.ZodObject<{
870
+ rank: z.ZodNumber;
871
+ type: z.ZodEnum<{
872
+ line: "line";
873
+ bar: "bar";
874
+ groupedBar: "groupedBar";
875
+ stackedBar: "stackedBar";
876
+ "100StackedBar": "100StackedBar";
877
+ column: "column";
878
+ groupedColumn: "groupedColumn";
879
+ stackedColumn: "stackedColumn";
880
+ "100StackedColumn": "100StackedColumn";
881
+ combo: "combo";
882
+ pie: "pie";
883
+ donut: "donut";
884
+ funnel: "funnel";
885
+ heatmap: "heatmap";
886
+ scatter: "scatter";
887
+ bubble: "bubble";
888
+ waterfall: "waterfall";
889
+ table: "table";
890
+ mekko: "mekko";
891
+ }>;
892
+ score: z.ZodNumber;
893
+ verdict: z.ZodEnum<{
894
+ ok: "ok";
895
+ disqualified: "disqualified";
896
+ }>;
897
+ factors: z.ZodArray<z.ZodObject<{
898
+ kind: z.ZodEnum<{
899
+ "deal-breaker": "deal-breaker";
900
+ pro: "pro";
901
+ con: "con";
902
+ family: "family";
903
+ specificity: "specificity";
904
+ continuity: "continuity";
905
+ }>;
906
+ label: z.ZodString;
907
+ weight: z.ZodNumber;
908
+ reason: z.ZodString;
909
+ }, z.core.$strip>>;
910
+ }, z.core.$strip>;
911
+ type ChartFitEntry = z.infer<typeof ChartFitEntrySchema>;
912
+ /**
913
+ * Request body for `POST /v0/evaluate`. Reuses `GraphGenerationRequestSchema` for shape symmetry
914
+ * with the other v0 routes; the server only reads `config.data` and the optional `chartFamily`.
915
+ * Other fields (including `userPrompt`, `config.type`, brand kit, annotations) are accepted-and-ignored.
916
+ */
917
+ declare const EvaluateParamsSchema: z.ZodObject<{
918
+ config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
919
+ userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
920
+ metadata: z.ZodOptional<z.ZodObject<{
921
+ callId: z.ZodString;
922
+ locale: z.ZodOptional<z.ZodEnum<{
923
+ EN_GB: "EN_GB";
924
+ EN_US: "EN_US";
925
+ }>>;
926
+ effort: z.ZodOptional<z.ZodEnum<{
927
+ low: "low";
928
+ medium: "medium";
929
+ high: "high";
930
+ }>>;
931
+ storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
932
+ low: "low";
933
+ medium: "medium";
934
+ high: "high";
935
+ none: "none";
936
+ }>>>;
937
+ budget: z.ZodOptional<z.ZodObject<{
938
+ maxWallClockMs: z.ZodOptional<z.ZodNumber>;
939
+ maxTotalTokens: z.ZodOptional<z.ZodNumber>;
940
+ maxCostUsd: z.ZodOptional<z.ZodNumber>;
941
+ }, z.core.$strip>>;
942
+ executionMode: z.ZodOptional<z.ZodEnum<{
943
+ agentic: "agentic";
944
+ fast: "fast";
945
+ }>>;
946
+ }, z.core.$strip>>;
947
+ chartFamily: z.ZodOptional<z.ZodEnum<{
948
+ comparison: "comparison";
949
+ relationship: "relationship";
950
+ distribution: "distribution";
951
+ composition: "composition";
952
+ }>>;
953
+ }, z.core.$strip>;
954
+ type EvaluateParams = z.input<typeof EvaluateParamsSchema>;
955
+ /**
956
+ * Actionable next-move suggestion returned alongside the ranking. Fires when the dataset has
957
+ * structural issues every chart type tripped over (e.g. duplicate primary dim → groupBy
958
+ * needed) — clients can react with a `groupBy` / `reshape` / `select` call before re-evaluating.
959
+ */
960
+ declare const EvaluationHintKindSchema: z.ZodEnum<{
961
+ "needs-time-aggregation": "needs-time-aggregation";
962
+ "needs-dimension-aggregation": "needs-dimension-aggregation";
963
+ "drop-noisy-dimensions": "drop-noisy-dimensions";
964
+ "reshape-for-heatmap": "reshape-for-heatmap";
965
+ "unpivot-wide-format": "unpivot-wide-format";
966
+ "needs-row-reduction": "needs-row-reduction";
967
+ }>;
968
+ type EvaluationHintKind = z.infer<typeof EvaluationHintKindSchema>;
969
+ declare const EvaluationHintSchema: z.ZodObject<{
970
+ kind: z.ZodEnum<{
971
+ "needs-time-aggregation": "needs-time-aggregation";
972
+ "needs-dimension-aggregation": "needs-dimension-aggregation";
973
+ "drop-noisy-dimensions": "drop-noisy-dimensions";
974
+ "reshape-for-heatmap": "reshape-for-heatmap";
975
+ "unpivot-wide-format": "unpivot-wide-format";
976
+ "needs-row-reduction": "needs-row-reduction";
977
+ }>;
978
+ message: z.ZodString;
979
+ }, z.core.$strip>;
980
+ type EvaluationHint = z.infer<typeof EvaluationHintSchema>;
981
+ /**
982
+ * Per-dimension alternative top pick — the chart that ranks #1 when a specific column is
983
+ * treated as the primary axis. One entry per plottable dim in `EvaluateResponse.alternatives`.
984
+ */
985
+ declare const DimensionAlternativeSchema: z.ZodObject<{
986
+ dimensionName: z.ZodString;
987
+ dimensionLabel: z.ZodString;
988
+ topPick: z.ZodObject<{
989
+ rank: z.ZodNumber;
990
+ type: z.ZodEnum<{
991
+ line: "line";
992
+ bar: "bar";
993
+ groupedBar: "groupedBar";
994
+ stackedBar: "stackedBar";
995
+ "100StackedBar": "100StackedBar";
996
+ column: "column";
997
+ groupedColumn: "groupedColumn";
998
+ stackedColumn: "stackedColumn";
999
+ "100StackedColumn": "100StackedColumn";
1000
+ combo: "combo";
1001
+ pie: "pie";
1002
+ donut: "donut";
1003
+ funnel: "funnel";
1004
+ heatmap: "heatmap";
1005
+ scatter: "scatter";
1006
+ bubble: "bubble";
1007
+ waterfall: "waterfall";
1008
+ table: "table";
1009
+ mekko: "mekko";
1010
+ }>;
1011
+ score: z.ZodNumber;
1012
+ verdict: z.ZodEnum<{
1013
+ ok: "ok";
1014
+ disqualified: "disqualified";
1015
+ }>;
1016
+ factors: z.ZodArray<z.ZodObject<{
1017
+ kind: z.ZodEnum<{
1018
+ "deal-breaker": "deal-breaker";
1019
+ pro: "pro";
1020
+ con: "con";
1021
+ family: "family";
1022
+ specificity: "specificity";
1023
+ continuity: "continuity";
1024
+ }>;
1025
+ label: z.ZodString;
1026
+ weight: z.ZodNumber;
1027
+ reason: z.ZodString;
1028
+ }, z.core.$strip>>;
1029
+ }, z.core.$strip>;
1030
+ }, z.core.$strip>;
1031
+ type DimensionAlternative = z.infer<typeof DimensionAlternativeSchema>;
1032
+ /**
1033
+ * Response body for `POST /v0/evaluate`.
1034
+ *
1035
+ * `hints` and `alternatives` are optional with a default of `[]` so the SDK stays compatible
1036
+ * with servers that haven't shipped them yet (older deployments, third-party agents-api forks,
1037
+ * cached responses). Newer servers populate them; consumers can treat both as always-present
1038
+ * arrays without null-checks.
1039
+ */
1040
+ declare const EvaluateResponseSchema: z.ZodObject<{
1041
+ ranking: z.ZodArray<z.ZodObject<{
1042
+ rank: z.ZodNumber;
1043
+ type: z.ZodEnum<{
1044
+ line: "line";
1045
+ bar: "bar";
1046
+ groupedBar: "groupedBar";
1047
+ stackedBar: "stackedBar";
1048
+ "100StackedBar": "100StackedBar";
1049
+ column: "column";
1050
+ groupedColumn: "groupedColumn";
1051
+ stackedColumn: "stackedColumn";
1052
+ "100StackedColumn": "100StackedColumn";
1053
+ combo: "combo";
1054
+ pie: "pie";
1055
+ donut: "donut";
1056
+ funnel: "funnel";
1057
+ heatmap: "heatmap";
1058
+ scatter: "scatter";
1059
+ bubble: "bubble";
1060
+ waterfall: "waterfall";
1061
+ table: "table";
1062
+ mekko: "mekko";
1063
+ }>;
1064
+ score: z.ZodNumber;
1065
+ verdict: z.ZodEnum<{
1066
+ ok: "ok";
1067
+ disqualified: "disqualified";
1068
+ }>;
1069
+ factors: z.ZodArray<z.ZodObject<{
1070
+ kind: z.ZodEnum<{
1071
+ "deal-breaker": "deal-breaker";
1072
+ pro: "pro";
1073
+ con: "con";
1074
+ family: "family";
1075
+ specificity: "specificity";
1076
+ continuity: "continuity";
1077
+ }>;
1078
+ label: z.ZodString;
1079
+ weight: z.ZodNumber;
1080
+ reason: z.ZodString;
1081
+ }, z.core.$strip>>;
1082
+ }, z.core.$strip>>;
1083
+ hints: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodObject<{
1084
+ kind: z.ZodEnum<{
1085
+ "needs-time-aggregation": "needs-time-aggregation";
1086
+ "needs-dimension-aggregation": "needs-dimension-aggregation";
1087
+ "drop-noisy-dimensions": "drop-noisy-dimensions";
1088
+ "reshape-for-heatmap": "reshape-for-heatmap";
1089
+ "unpivot-wide-format": "unpivot-wide-format";
1090
+ "needs-row-reduction": "needs-row-reduction";
1091
+ }>;
1092
+ message: z.ZodString;
1093
+ }, z.core.$strip>>>>;
1094
+ alternatives: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodObject<{
1095
+ dimensionName: z.ZodString;
1096
+ dimensionLabel: z.ZodString;
1097
+ topPick: z.ZodObject<{
1098
+ rank: z.ZodNumber;
1099
+ type: z.ZodEnum<{
1100
+ line: "line";
1101
+ bar: "bar";
1102
+ groupedBar: "groupedBar";
1103
+ stackedBar: "stackedBar";
1104
+ "100StackedBar": "100StackedBar";
1105
+ column: "column";
1106
+ groupedColumn: "groupedColumn";
1107
+ stackedColumn: "stackedColumn";
1108
+ "100StackedColumn": "100StackedColumn";
1109
+ combo: "combo";
1110
+ pie: "pie";
1111
+ donut: "donut";
1112
+ funnel: "funnel";
1113
+ heatmap: "heatmap";
1114
+ scatter: "scatter";
1115
+ bubble: "bubble";
1116
+ waterfall: "waterfall";
1117
+ table: "table";
1118
+ mekko: "mekko";
1119
+ }>;
1120
+ score: z.ZodNumber;
1121
+ verdict: z.ZodEnum<{
1122
+ ok: "ok";
1123
+ disqualified: "disqualified";
1124
+ }>;
1125
+ factors: z.ZodArray<z.ZodObject<{
1126
+ kind: z.ZodEnum<{
1127
+ "deal-breaker": "deal-breaker";
1128
+ pro: "pro";
1129
+ con: "con";
1130
+ family: "family";
1131
+ specificity: "specificity";
1132
+ continuity: "continuity";
1133
+ }>;
1134
+ label: z.ZodString;
1135
+ weight: z.ZodNumber;
1136
+ reason: z.ZodString;
1137
+ }, z.core.$strip>>;
1138
+ }, z.core.$strip>;
1139
+ }, z.core.$strip>>>>;
1140
+ }, z.core.$strip>;
1141
+ type EvaluateResponse = z.infer<typeof EvaluateResponseSchema>;
834
1142
 
835
1143
  /**
836
1144
  * Client SDK for the Graphy AI Agents API.
@@ -934,7 +1242,7 @@ declare class GraphyAiSdk {
934
1242
  generateSuggestions(data: GenerateSuggestionsParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
935
1243
  suggestions: {
936
1244
  dataPrepPrompt: string;
937
- chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table";
1245
+ chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table" | "mekko";
938
1246
  summary: string;
939
1247
  }[];
940
1248
  }>;
@@ -949,7 +1257,7 @@ declare class GraphyAiSdk {
949
1257
  generateSuggestionsStream(data: GenerateSuggestionsParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
950
1258
  suggestions: {
951
1259
  dataPrepPrompt: string;
952
- chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table";
1260
+ chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table" | "mekko";
953
1261
  summary: string;
954
1262
  }[];
955
1263
  }>>>;
@@ -1074,6 +1382,60 @@ declare class GraphyAiSdk {
1074
1382
  };
1075
1383
  config: _graphysdk_core_node.GraphConfig;
1076
1384
  }>>>;
1385
+ /**
1386
+ * Scores every supported chart type against the dataset in the provided `GraphConfig` and
1387
+ * returns the full ranking with per-type factor breakdowns. Deterministic, no LLM call.
1388
+ *
1389
+ * @remarks
1390
+ * - The server only reads `config.data` and the optional `chartFamily`. Other fields including
1391
+ * `userPrompt`, `config.type`, brand kit, and annotations are accepted-and-ignored.
1392
+ * - `config.type` is silently ignored: this endpoint reports intrinsic chart fit and does not
1393
+ * apply the mutate-agent's continuity bonus. To honor the current chart type, use {@link generateMutation}.
1394
+ * - Disqualified types are returned at the tail of the ranking with `verdict: 'disqualified'`,
1395
+ * `score: 0`, and their `factors` carry the deal-breaker reason.
1396
+ * - The raw `score` field drifts as scoring rules evolve; clients should assert against `rank`
1397
+ * and `verdict` for stable contracts.
1398
+ *
1399
+ * @param data - Request body (config + optional `chartFamily` + optional metadata).
1400
+ * @param signal - Optional `AbortSignal` to cancel the request.
1401
+ * @returns The ranked chart-fit entries.
1402
+ * @throws {GraphyApiError} When the API returns an error (e.g. 400 on unprofilable data) or
1403
+ * the network request fails.
1404
+ */
1405
+ evaluate(data: EvaluateParams, signal?: AbortSignal): Promise<{
1406
+ ranking: {
1407
+ rank: number;
1408
+ type: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table" | "mekko";
1409
+ score: number;
1410
+ verdict: "ok" | "disqualified";
1411
+ factors: {
1412
+ kind: "deal-breaker" | "pro" | "con" | "family" | "specificity" | "continuity";
1413
+ label: string;
1414
+ weight: number;
1415
+ reason: string;
1416
+ }[];
1417
+ }[];
1418
+ hints: {
1419
+ kind: "needs-time-aggregation" | "needs-dimension-aggregation" | "drop-noisy-dimensions" | "reshape-for-heatmap" | "unpivot-wide-format" | "needs-row-reduction";
1420
+ message: string;
1421
+ }[];
1422
+ alternatives: {
1423
+ dimensionName: string;
1424
+ dimensionLabel: string;
1425
+ topPick: {
1426
+ rank: number;
1427
+ type: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table" | "mekko";
1428
+ score: number;
1429
+ verdict: "ok" | "disqualified";
1430
+ factors: {
1431
+ kind: "deal-breaker" | "pro" | "con" | "family" | "specificity" | "continuity";
1432
+ label: string;
1433
+ weight: number;
1434
+ reason: string;
1435
+ }[];
1436
+ };
1437
+ }[];
1438
+ }>;
1077
1439
  /**
1078
1440
  * Runs the extract agent to build a chart-ready dataset from unstructured prose, images, and/or PDFs.
1079
1441
  *
@@ -1149,5 +1511,5 @@ declare class GraphyAiSdk {
1149
1511
  private wrapStreamWithStorytellingStripping;
1150
1512
  }
1151
1513
 
1152
- export { AiChartTypeEnum, ChartFamilySchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, 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, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
1153
- export type { AiChartType, ChartFamily, ClientConfig, CompleteEvent, ErrorEvent, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, Logger, Metadata, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
1514
+ export { AiChartTypeEnum, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, DimensionAlternativeSchema, EvaluateParamsSchema, EvaluateResponseSchema, EvaluationHintKindSchema, EvaluationHintSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, 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, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
1515
+ export type { AiChartType, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, ClientConfig, CompleteEvent, DimensionAlternative, ErrorEvent, EvaluateParams, EvaluateResponse, EvaluationHint, EvaluationHintKind, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, Logger, Metadata, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{__awaiter as e,__asyncValues as t,__asyncGenerator as i,__await as n,__rest as r}from"tslib";import{z as s}from"zod";class a extends Error{constructor(e,t){var i;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!==(i=null==t?void 0:t.retryable)&&void 0!==i&&i}}const o=e=>e instanceof a,c=e=>"progress"===e.type,l=e=>"complete"===e.type,d=e=>"error"===e.type,m=e=>"preview"===e.type,g=e=>"reasoning"===e.type;class u{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 c(e)}static isCompleteEvent(e){return l(e)}static isErrorEvent(e){return d(e)}stream(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,i,n);return this.parseSSE(e)})}fetch(i,n,r,s){return e(this,void 0,void 0,function*(){var e,o,m,g,u;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const b=yield this.makeRequest(i,n,s),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var p,f=!0,y=t(this.parseSSE(b));!(e=(p=yield y.next()).done);f=!0){g=p.value,f=!1;const e=g;if(c(e)&&r&&r(e),l(e))return e.data;if(d(e)){const t=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){o={error:e}}finally{try{f||e||!(m=y.return)||(yield m.call(y))}finally{if(o)throw o.error}}const n=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${n}ms`),new a("Stream ended without completion")}return yield b.json()}catch(e){const t=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-h;this.logger.debug(`${this.tag} Fetch completed: ${i} ${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}}})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return i(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let r="",s="",o="";try{for(;;){const{done:e,value:a}=yield n(t.read());if(e)break;r+=i.decode(a,{stream:!0});const c=r.split(/\r?\n/);r=c.pop()||"";for(const e of c)if(e.startsWith("event: "))s=e.slice(7).trim();else if(e.startsWith("data: "))o+=(o?"\n":"")+e.slice(6);else if(""===e.trim()&&o){try{const e=JSON.parse(o);let t;if("progress"===s){const i=e;t=Object.assign({type:"progress"},i)}else if("complete"===s)t={type:"complete",data:e};else if("error"===s){const i=e;t=Object.assign({type:"error"},i)}else if("preview"===s){const i=e;t=Object.assign(Object.assign({},i),{type:"preview"})}else{if("reasoning"!==s){s="",o="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield n(t),"complete"===s||"error"===s)return yield n(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}s="",o=""}}}finally{t.releaseLock()}})}makeRequest(t,i,n){return e(this,arguments,void 0,function*(e,t,i,n=1,r="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const s=new URL(e,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${s}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),l=()=>o.abort();i&&i.addEventListener("abort",l);try{const c=yield fetch(s,Object.assign({method:r,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:o.signal},"POST"===r&&{body:JSON.stringify(t)}));if(!c.ok){const s=c.status>=500||429===c.status;let o,l=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?l=t.message:"string"==typeof t.error&&(l=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const d=new a(l,{status:c.status,code:o,retryable:s});if(s&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${s}ms (attempt ${n+1})`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),d}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(s){if(s instanceof a)throw s;if(s instanceof Error&&"AbortError"===s.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),s;if(n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${s}ms`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new a("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const h=s.enum(["EN_GB","EN_US"]),p=s.custom(e=>null!=e&&"object"==typeof e),f=s.enum(["low","medium","high"]),y=s.enum(["none","low","medium","high"]),b=s.enum(["agentic","fast"]),v=s.object({maxWallClockMs:s.number().positive().optional(),maxTotalTokens:s.number().int().positive().optional(),maxCostUsd:s.number().positive().optional()}),w=s.object({callId:s.string().max(256),locale:h.optional(),effort:f.optional(),storytellingEffort:y.optional().default("low"),budget:v.optional(),executionMode:b.optional()}),x=1e4,j=s.object({config:p,userPrompt:s.string().max(1e4).optional().default(""),metadata:w.optional()}),$=j.extend({maxSuggestionCount:s.number().int().min(1).max(4).optional()}),S=s.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),k=s.object({dataPrepPrompt:s.string(),chartType:S,summary:s.string()}),C=s.object({response:s.object({message:s.string()}),config:p}),T=s.object({suggestions:s.array(k)}),O=s.enum(["comparison","relationship","distribution","composition"]),E=s.object({finding:s.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:s.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:s.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:s.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:s.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:O.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:s.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),I=s.object({topic:s.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:s.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:s.number().int().min(1).describe("Number of findings in this story."),findings:s.array(E).describe("Child findings, sorted by quadrant score desc.")}),R=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),stories:s.array(I)}),B=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),P=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),A=s.enum(["high","medium","low"]),U=s.object({confidence:A,needsUserInput:s.boolean(),warnings:s.array(s.string()),cellConfidence:s.array(s.object({rowIndex:s.number().int().nonnegative(),columnKey:s.string(),confidence:A,quote:s.string().optional()})).optional()}),q=s.object({score:s.number().min(0).max(1),issues:s.array(s.string()),sufficient:s.boolean(),summary:s.string()}),N=5e5,D=8,F=2097152,K=7340032,M=2,G=6291456,W=8388608,L=2,z=G,H=W,J=12582912,_=12;function Y(e){return 4*Math.ceil(e/3)}const Z=Y(F),Q=Y(K),V=Y(G),X=Y(W),ee=Y(z),te=Y(H),ie=Y(J);function ne(e){return e.replace(/\s+/g,"")}function re(e){const t=ne(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const se=/^image\/(png|jpeg|jpg|webp|gif)$/i,ae=s.object({mimeType:s.string().min(1).refine(e=>se.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:s.string().min(1).max(Z).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),oe=s.enum(["image","document","spreadsheet"]),ce=ae.extend({kind:s.literal("image")}),le=s.object({kind:s.literal("document"),mimeType:s.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:s.string().min(1).max(V).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),de=s.object({kind:s.literal("spreadsheet"),mimeType:s.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:s.string().min(1).max(ee).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:s.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"]}),me=s.discriminatedUnion("kind",[ce,le,de]),ge=s.object({sourceText:s.string().max(N).default(""),images:s.array(ae).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:s.array(me).max(12).optional(),metadata:w.optional()}).superRefine((e,t)=>{var i,n;const r=e.sourceText.trim(),s=null!==(i=e.images)&&void 0!==i?i:[],a=null!==(n=e.attachments)&&void 0!==n?n:[];if(s.length>0&&a.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===s.length&&0===a.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(s.length>0){s.reduce((e,t)=>e+ne(t.dataBase64).length,0)>Q&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,l=0,d=0,m=0,g=0,u=0;for(const e of a){const t=ne(e.dataBase64).length;switch(u+=t,e.kind){case"image":o+=1,d+=t;break;case"document":c+=1,m+=t;break;case"spreadsheet":l+=1,g+=t}}o>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),l>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const h=o<=8&&c<=2&&l<=2;a.length>0&&h&&(d>Q&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),m>X&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>te&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>ie&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function ue(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ne(e.dataBase64)}}function he(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ne(e.dataBase64)}}function pe(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ne(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const fe=s.object({response:s.object({message:s.string()}),config:p,extractMeta:U.nullable(),lastAccuracyEvaluation:q.optional()}),ye=s.object({config:p,response:s.object({message:s.string(),steps:s.array(s.string())})}),be=T,ve="/api/v0";class we{constructor(e){this.client=new u(e)}generateGraph(t,i,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,s=r(t,["storytellingOptions"]),a=yield this.client.fetch(`${ve}/generate`,s,i,n),o=ye.parse(a);return this.stripStorytelling(o,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,n=r(t,["storytellingOptions"]),s=yield this.client.stream(`${ve}/generate`,n,i);return this.wrapStreamWithStorytellingStripping(s,e)})}generateNarrative(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ve}/narrate`,t,i,n);return C.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${ve}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ve}/suggestions`,t,i,n);return T.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${ve}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ve}/explore`,t,i,n);return R.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${ve}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ve}/annotate`,t,i,n);return B.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${ve}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ve}/mutate`,t,i,n);return P.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${ve}/mutate`,t,i)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${ve}/extract`,t,i,n);return fe.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${ve}/extract`,t,i)})}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,r){return i(this,arguments,function*(){var i,s,a,o;try{for(var c,d=!0,m=t(e);!(i=(c=yield n(m.next())).done);d=!0){o=c.value,d=!1;const e=o;if(l(e)){const t=this.stripStorytelling(e.data,r);yield yield n(Object.assign(Object.assign({},e),{data:t}))}else yield yield n(e)}}catch(e){s={error:e}}finally{try{d||i||!(a=m.return)||(yield n(a.call(m)))}finally{if(s)throw s.error}}})}}export{S as AiChartTypeEnum,O as ChartFamilySchema,b as ExecutionModeSchema,E as ExploreFindingSchema,I as ExploreStorySchema,q as ExtractAccuracyEvaluationSchema,me as ExtractAttachmentInputSchema,oe as ExtractAttachmentKindSchema,A as ExtractConfidenceSchema,ge as ExtractFromProseParamsSchema,fe as ExtractFromProseResponseSchema,U as ExtractMetaSchema,B as GenerateAnnotationsResponseSchema,R as GenerateExplorationResponseSchema,ye as GenerateGraphResponseSchema,be as GenerateGraphSuggestionsResponseSchema,P as GenerateMutationResponseSchema,C as GenerateNarrativeResponseSchema,$ as GenerateSuggestionsParamsSchema,T as GenerateSuggestionsResponseSchema,j as GraphGenerationRequestSchema,we as GraphyAiSdk,a as GraphyApiError,v as InvocationBudgetSchema,f as InvocationEffortSchema,_ as MAX_EXTRACT_ATTACHMENTS,J as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,M as MAX_EXTRACT_DOCUMENTS,W as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,G as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,D as MAX_EXTRACT_IMAGES,K as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,F as MAX_EXTRACT_IMAGE_DECODED_BYTES,L as MAX_EXTRACT_SPREADSHEETS,H as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,z as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,N as MAX_SOURCE_TEXT_LENGTH,x as MAX_USER_PROMPT_LENGTH,w as MetadataSchema,y as StorytellingEffortSchema,k as SuggestionSchema,ue as buildImageAttachment,he as buildPdfAttachment,pe as buildSpreadsheetAttachment,l as isCompleteEvent,d as isErrorEvent,o as isGraphyApiError,m as isPreviewEvent,c as isProgressEvent,g as isReasoningEvent};
1
+ import{__awaiter as e,__asyncValues as t,__asyncGenerator as i,__await as n,__rest as r}from"tslib";import{z as s}from"zod";class a extends Error{constructor(e,t){var i;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!==(i=null==t?void 0:t.retryable)&&void 0!==i&&i}}const o=e=>e instanceof a,c=e=>"progress"===e.type,l=e=>"complete"===e.type,d=e=>"error"===e.type,m=e=>"preview"===e.type,g=e=>"reasoning"===e.type;class u{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 c(e)}static isCompleteEvent(e){return l(e)}static isErrorEvent(e){return d(e)}stream(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,i,n);return this.parseSSE(e)})}fetch(i,n,r,s){return e(this,void 0,void 0,function*(){var e,o,m,g,u;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const b=yield this.makeRequest(i,n,s),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var p,f=!0,y=t(this.parseSSE(b));!(e=(p=yield y.next()).done);f=!0){g=p.value,f=!1;const e=g;if(c(e)&&r&&r(e),l(e))return e.data;if(d(e)){const t=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){o={error:e}}finally{try{f||e||!(m=y.return)||(yield m.call(y))}finally{if(o)throw o.error}}const n=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${n}ms`),new a("Stream ended without completion")}return yield b.json()}catch(e){const t=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-h;this.logger.debug(`${this.tag} Fetch completed: ${i} ${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}}})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return i(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let r="",s="",o="";try{for(;;){const{done:e,value:a}=yield n(t.read());if(e)break;r+=i.decode(a,{stream:!0});const c=r.split(/\r?\n/);r=c.pop()||"";for(const e of c)if(e.startsWith("event: "))s=e.slice(7).trim();else if(e.startsWith("data: "))o+=(o?"\n":"")+e.slice(6);else if(""===e.trim()&&o){try{const e=JSON.parse(o);let t;if("progress"===s){const i=e;t=Object.assign({type:"progress"},i)}else if("complete"===s)t={type:"complete",data:e};else if("error"===s){const i=e;t=Object.assign({type:"error"},i)}else if("preview"===s){const i=e;t=Object.assign(Object.assign({},i),{type:"preview"})}else{if("reasoning"!==s){s="",o="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield n(t),"complete"===s||"error"===s)return yield n(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}s="",o=""}}}finally{t.releaseLock()}})}makeRequest(t,i,n){return e(this,arguments,void 0,function*(e,t,i,n=1,r="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const s=new URL(e,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${s}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),l=()=>o.abort();i&&i.addEventListener("abort",l);try{const c=yield fetch(s,Object.assign({method:r,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:o.signal},"POST"===r&&{body:JSON.stringify(t)}));if(!c.ok){const s=c.status>=500||429===c.status;let o,l=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?l=t.message:"string"==typeof t.error&&(l=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const d=new a(l,{status:c.status,code:o,retryable:s});if(s&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${s}ms (attempt ${n+1})`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),d}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(s){if(s instanceof a)throw s;if(s instanceof Error&&"AbortError"===s.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),s;if(n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${s}ms`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new a("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const h=s.enum(["EN_GB","EN_US"]),p=s.custom(e=>null!=e&&"object"==typeof e),f=s.enum(["low","medium","high"]),y=s.enum(["none","low","medium","high"]),b=s.enum(["agentic","fast"]),v=s.object({maxWallClockMs:s.number().positive().optional(),maxTotalTokens:s.number().int().positive().optional(),maxCostUsd:s.number().positive().optional()}),w=s.object({callId:s.string().max(256),locale:h.optional(),effort:f.optional(),storytellingEffort:y.optional().default("low"),budget:v.optional(),executionMode:b.optional()}),x=1e4,j=s.object({config:p,userPrompt:s.string().max(1e4).optional().default(""),metadata:w.optional()}),$=j.extend({maxSuggestionCount:s.number().int().min(1).max(4).optional()}),k=s.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),S=s.object({dataPrepPrompt:s.string(),chartType:k,summary:s.string()}),C=s.object({response:s.object({message:s.string()}),config:p}),T=s.object({suggestions:s.array(S)}),O=s.enum(["comparison","relationship","distribution","composition"]),E=s.object({finding:s.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:s.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:s.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:s.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:s.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:O.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:s.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),I=s.object({topic:s.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:s.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:s.number().int().min(1).describe("Number of findings in this story."),findings:s.array(E).describe("Child findings, sorted by quadrant score desc.")}),P=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),stories:s.array(I)}),R=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),B=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),A=s.enum(["high","medium","low"]),U=s.object({confidence:A,needsUserInput:s.boolean(),warnings:s.array(s.string()),cellConfidence:s.array(s.object({rowIndex:s.number().int().nonnegative(),columnKey:s.string(),confidence:A,quote:s.string().optional()})).optional()}),q=s.object({score:s.number().min(0).max(1),issues:s.array(s.string()),sufficient:s.boolean(),summary:s.string()}),N=5e5,D=8,F=2097152,K=7340032,M=2,G=6291456,L=8388608,W=2,z=G,H=L,J=12582912,_=12;function Y(e){return 4*Math.ceil(e/3)}const Z=Y(F),Q=Y(K),V=Y(G),X=Y(L),ee=Y(z),te=Y(H),ie=Y(J);function ne(e){return e.replace(/\s+/g,"")}function re(e){const t=ne(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const se=/^image\/(png|jpeg|jpg|webp|gif)$/i,ae=s.object({mimeType:s.string().min(1).refine(e=>se.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:s.string().min(1).max(Z).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),oe=s.enum(["image","document","spreadsheet"]),ce=ae.extend({kind:s.literal("image")}),le=s.object({kind:s.literal("document"),mimeType:s.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:s.string().min(1).max(V).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),de=s.object({kind:s.literal("spreadsheet"),mimeType:s.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:s.string().min(1).max(ee).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:s.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"]}),me=s.discriminatedUnion("kind",[ce,le,de]),ge=s.object({sourceText:s.string().max(N).default(""),images:s.array(ae).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:s.array(me).max(12).optional(),metadata:w.optional()}).superRefine((e,t)=>{var i,n;const r=e.sourceText.trim(),s=null!==(i=e.images)&&void 0!==i?i:[],a=null!==(n=e.attachments)&&void 0!==n?n:[];if(s.length>0&&a.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===s.length&&0===a.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(s.length>0){s.reduce((e,t)=>e+ne(t.dataBase64).length,0)>Q&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,l=0,d=0,m=0,g=0,u=0;for(const e of a){const t=ne(e.dataBase64).length;switch(u+=t,e.kind){case"image":o+=1,d+=t;break;case"document":c+=1,m+=t;break;case"spreadsheet":l+=1,g+=t}}o>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),l>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const h=o<=8&&c<=2&&l<=2;a.length>0&&h&&(d>Q&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),m>X&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>te&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>ie&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function ue(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ne(e.dataBase64)}}function he(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ne(e.dataBase64)}}function pe(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ne(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const fe=s.object({response:s.object({message:s.string()}),config:p,extractMeta:U.nullable(),lastAccuracyEvaluation:q.optional()}),ye=s.object({config:p,response:s.object({message:s.string(),steps:s.array(s.string())})}),be=T,ve=s.enum(["deal-breaker","pro","con","family","specificity","continuity"]),we=s.object({kind:ve,label:s.string(),weight:s.number(),reason:s.string()}),xe=s.enum(["ok","disqualified"]),je=s.object({rank:s.number().int().positive(),type:k,score:s.number(),verdict:xe,factors:s.array(we)}),$e=j.extend({chartFamily:O.optional()}),ke=s.enum(["needs-time-aggregation","needs-dimension-aggregation","drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction"]),Se=s.object({kind:ke,message:s.string()}),Ce=s.object({dimensionName:s.string(),dimensionLabel:s.string(),topPick:je}),Te=s.object({ranking:s.array(je),hints:s.array(Se).optional().default([]),alternatives:s.array(Ce).optional().default([])}),Oe="/api/v0";class Ee{constructor(e){this.client=new u(e)}generateGraph(t,i,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,s=r(t,["storytellingOptions"]),a=yield this.client.fetch(`${Oe}/generate`,s,i,n),o=ye.parse(a);return this.stripStorytelling(o,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,n=r(t,["storytellingOptions"]),s=yield this.client.stream(`${Oe}/generate`,n,i);return this.wrapStreamWithStorytellingStripping(s,e)})}generateNarrative(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/narrate`,t,i,n);return C.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/suggestions`,t,i,n);return T.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/explore`,t,i,n);return P.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/annotate`,t,i,n);return R.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/mutate`,t,i,n);return B.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/mutate`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/evaluate`,t,void 0,i);return Te.parse(e)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/extract`,t,i,n);return fe.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/extract`,t,i)})}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,r){return i(this,arguments,function*(){var i,s,a,o;try{for(var c,d=!0,m=t(e);!(i=(c=yield n(m.next())).done);d=!0){o=c.value,d=!1;const e=o;if(l(e)){const t=this.stripStorytelling(e.data,r);yield yield n(Object.assign(Object.assign({},e),{data:t}))}else yield yield n(e)}}catch(e){s={error:e}}finally{try{d||i||!(a=m.return)||(yield n(a.call(m)))}finally{if(s)throw s.error}}})}}export{k as AiChartTypeEnum,O as ChartFamilySchema,je as ChartFitEntrySchema,ve as ChartFitFactorKindSchema,we as ChartFitFactorSchema,xe as ChartFitVerdictSchema,Ce as DimensionAlternativeSchema,$e as EvaluateParamsSchema,Te as EvaluateResponseSchema,ke as EvaluationHintKindSchema,Se as EvaluationHintSchema,b as ExecutionModeSchema,E as ExploreFindingSchema,I as ExploreStorySchema,q as ExtractAccuracyEvaluationSchema,me as ExtractAttachmentInputSchema,oe as ExtractAttachmentKindSchema,A as ExtractConfidenceSchema,ge as ExtractFromProseParamsSchema,fe as ExtractFromProseResponseSchema,U as ExtractMetaSchema,R as GenerateAnnotationsResponseSchema,P as GenerateExplorationResponseSchema,ye as GenerateGraphResponseSchema,be as GenerateGraphSuggestionsResponseSchema,B as GenerateMutationResponseSchema,C as GenerateNarrativeResponseSchema,$ as GenerateSuggestionsParamsSchema,T as GenerateSuggestionsResponseSchema,j as GraphGenerationRequestSchema,Ee as GraphyAiSdk,a as GraphyApiError,v as InvocationBudgetSchema,f as InvocationEffortSchema,_ as MAX_EXTRACT_ATTACHMENTS,J as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,M as MAX_EXTRACT_DOCUMENTS,L as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,G as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,D as MAX_EXTRACT_IMAGES,K as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,F as MAX_EXTRACT_IMAGE_DECODED_BYTES,W as MAX_EXTRACT_SPREADSHEETS,H as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,z as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,N as MAX_SOURCE_TEXT_LENGTH,x as MAX_USER_PROMPT_LENGTH,w as MetadataSchema,y as StorytellingEffortSchema,S as SuggestionSchema,ue as buildImageAttachment,he as buildPdfAttachment,pe as buildSpreadsheetAttachment,l as isCompleteEvent,d as isErrorEvent,o as isGraphyApiError,m as isPreviewEvent,c as isProgressEvent,g as isReasoningEvent};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@graphysdk/agents-sdk",
3
3
  "author": "Graphy",
4
- "version": "1.3.0",
4
+ "version": "1.4.0-beta.1778840000414",
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.3.0"
21
+ "@graphysdk/core": "1.4.0-beta.1778840000414"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@rollup/plugin-commonjs": "^28.0.6",