@graphysdk/agents-sdk 1.6.2-beta.1782128674332 → 1.6.2-beta.1782148741262
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +144 -0
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("zod");class 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,n=e=>"error"===e.type;class o{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 n(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,o,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,d,u;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,o,c),z=b.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var h,f=!0,y=e.__asyncValues(this.parseSSE(b));!(l=(h=yield y.next()).done);f=!0){d=h.value,f=!1;const e=d;if(a(e)&&s&&s(e),i(e))return e.data;if(n(e)){const a=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){m={error:e}}finally{try{f||l||!(p=y.return)||(yield p.call(y))}finally{if(m)throw m.error}}const o=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${o}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const a=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,r,a);return yield e.json()})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new r("Response body is null");const a=t.body.getReader(),i=new TextDecoder;let n="",o="",s="";try{for(;;){const{done:t,value:r}=yield e.__await(a.read());if(t)break;n+=i.decode(r,{stream:!0});const c=n.split(/\r?\n/);n=c.pop()||"";for(const t of c)if(t.startsWith("event: "))o=t.slice(7).trim();else if(t.startsWith("data: "))s+=(s?"\n":"")+t.slice(6);else if(""===t.trim()&&s){try{const t=JSON.parse(s);let r;if("progress"===o){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===o)r={type:"complete",data:t};else if("error"===o){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===o){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==o){o="",s="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===o||"error"===o)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}o="",s=""}}}finally{a.releaseLock()}})}makeRequest(t,a,i){return e.__awaiter(this,arguments,void 0,function*(e,t,a,i=1,n="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${o}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();a&&a.addEventListener("abort",l);try{const c=yield fetch(o,Object.assign({method:n,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===n&&{body:JSON.stringify(t)}));if(!c.ok){let o,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===o)&&(c.status>=500||429===c.status),m=new r(s,{status:c.status,code:o,retryable:l});if(l&&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,n)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(o){if(o instanceof r)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),o;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,n)}throw this.logger.error(`${this.tag} Network error: ${e}`,o),new r("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",l)}})}makeMultipartRequest(t,a,i){return e.__awaiter(this,arguments,void 0,function*(e,t,a,i=1){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");const o=new AbortController,s=setTimeout(()=>o.abort(),this.timeout),c=()=>o.abort();a&&a.addEventListener("abort",c);try{const s=yield fetch(n,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:o.signal});if(!s.ok){let n,o=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error),"string"==typeof t.code&&(n=t.code)}}catch(e){}const c=s.status>=500||429===s.status,l=new r(o,{status:s.status,code:n,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(r),this.makeMultipartRequest(e,t,a,i+1)}throw l}return s}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw 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 yield this.sleep(r),this.makeMultipartRequest(e,t,a,i+1)}throw new r("Network error",{retryable:!0})}finally{clearTimeout(s),a&&a.removeEventListener("abort",c)}})}}const s=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),l=t.z.enum(["low","medium","high"]),m=t.z.enum(["none","low","medium","high"]),p=t.z.enum(["agentic","fast"]),d=3e5,u=5e5,g=t.z.object({maxWallClockMs:t.z.number().positive().max(d).optional(),maxTotalTokens:t.z.number().int().positive().max(u).optional(),maxCostUsd:t.z.number().positive().max(10).optional()}),h=t.z.object({callId:t.z.string().max(256).optional(),locale:s.optional(),effort:l.optional(),storytellingEffort:m.optional().default("low"),budget:g.optional(),executionMode:p.optional(),enforceTableRowCap:t.z.boolean().optional()}),f=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),y=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),b=1e4,z=t.z.enum(["comparison","relationship","distribution","composition"]),x=t.z.object({config:c,userPrompt:t.z.string().max(b).optional().default(""),metadata:h.optional(),chartFamily:z.optional()}),v=x.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),S=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),w=t.z.object({dataPrepPrompt:t.z.string(),chartType:S,summary:t.z.string()}),_=x.extend({userPrompt:t.z.string().max(b),mutationReceipt:f.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),E=t.z.object({response:t.z.object({message:t.z.string()}),config:c,run:y.optional()}),T=t.z.object({suggestions:t.z.array(w),run:y.optional()}),C=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:z.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.")}),A=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(C).describe("Child findings, sorted by quadrant score desc.")}),j=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(A),run:y.optional()});x.extend({mutationReceipt:f.optional()});const R=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c,run:y.optional()}),$=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c,mutationReceipt:f.optional(),warnings:t.z.array(t.z.string()).optional(),run:y.optional()}),k=t.z.enum(["explore","mutate","narrate","annotate"]),O=t.z.object({agent:k,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),M=x.extend({userPrompt:t.z.string().max(b),stages:t.z.array(k).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),D=$.extend({reasoning:t.z.array(O),stories:t.z.array(A).optional()}),P=t.z.enum(["high","medium","low"]),I=t.z.object({confidence:P,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:P,quote:t.z.string().optional()})).optional()}),G=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()}),B=5e5,U=2097152,F=7340032,X=6291456,N=8388608,q=X,L=N,K=12582912;function H(e){return 4*Math.ceil(e/3)}const W=H(U),Y=H(F),J=H(X),V=H(N),Q=H(q),Z=H(L),ee=H(K);function te(e){return e.replace(/\s+/g,"")}function re(e){const t=te(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const ae=/^image\/(png|jpeg|jpg|webp|gif)$/i,ie=t.z.object({mimeType:t.z.string().min(1).refine(e=>ae.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(W).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ne=t.z.enum(["image","document","spreadsheet"]),oe=ie.extend({kind:t.z.literal("image")}),se=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(J).refine(re,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ce=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(Q).refine(re,{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"]}),le=t.z.discriminatedUnion("kind",[oe,se,ce]),me=t.z.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),pe=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),kind:ne,mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().positive(),expiresAt:t.z.string().datetime()}),de=t.z.object({sourceText:t.z.string().max(B).default(""),images:t.z.array(ie).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(le).max(12).optional(),attachmentRefs:t.z.array(me).max(12).optional(),metadata:h.optional()}).superRefine((e,t)=>{var r,a,i;const n=e.sourceText.trim(),o=null!==(r=e.images)&&void 0!==r?r:[],s=null!==(a=e.attachments)&&void 0!==a?a:[],c=null!==(i=e.attachmentRefs)&&void 0!==i?i:[];if(o.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(c.length>0&&s.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or inline `attachments`, not both.",path:["attachmentRefs"]});if(c.length>0&&o.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or deprecated `images`, not both.",path:["attachmentRefs"]});if(0===n.length&&0===o.length&&0===s.length&&0===c.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(c.length>0)return;if(o.length>0){o.reduce((e,t)=>e+te(t.dataBase64).length,0)>Y&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let l=0,m=0,p=0,d=0,u=0,g=0,h=0;for(const e of s){const t=te(e.dataBase64).length;switch(h+=t,e.kind){case"image":l+=1,d+=t;break;case"document":m+=1,u+=t;break;case"spreadsheet":p+=1,g+=t}}l>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),p>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&p<=2;s.length>0&&f&&(d>Y&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>V&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>Z&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>ee&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const ue=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:I.nullable(),lastAccuracyEvaluation:G.optional(),run:y.optional()}),ge=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:y.optional()}),he=T,fe=t.z.enum(["deal-breaker","pro","con","family","continuity"]),ye=t.z.object({kind:fe,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),be=t.z.enum(["ok","disqualified"]),ze=t.z.object({rank:t.z.number().int().positive(),type:S,score:t.z.number(),verdict:be,factors:t.z.array(ye)}),xe=t.z.object({config:c,chartFamily:z.optional(),metadata:h.optional()}),ve=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),Se=t.z.object({kind:ve,message:t.z.string()}),we=t.z.enum(["sum","avg","count","min","max"]),_e=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:we,chartType:S,score:t.z.number(),message:t.z.string()}),Ee=t.z.object({ranking:t.z.array(ze),observations:t.z.array(Se).optional().default([]),suggestions:t.z.array(_e).optional().default([]),run:y.optional()}),Te=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),Ce=t.z.object({config:c.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:Te.optional(),userPrompt:t.z.string().optional(),metadata:h.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ae=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),je=t.z.enum(["info","low","medium","high"]),Re=t.z.object({category:Ae,severity:je,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),$e=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Re)}),ke=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),Oe=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),Me=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:$e.nullable(),chartVisionAudit:Oe.nullable().optional().default(null),rubricScores:ke.nullable().optional().default(null),run:y.optional()}),De="/api/v0";exports.AggregationFunctionSchema=we,exports.AggregationSuggestionSchema=_e,exports.AiChartTypeEnum=S,exports.AttachmentUploadResponseSchema=pe,exports.ChartCritiqueIssueCategorySchema=Ae,exports.ChartCritiqueIssueSchema=Re,exports.ChartCritiqueIssueSeveritySchema=je,exports.ChartCritiqueReportSchema=$e,exports.ChartFamilySchema=z,exports.ChartFitEntrySchema=ze,exports.ChartFitFactorKindSchema=fe,exports.ChartFitFactorSchema=ye,exports.ChartFitVerdictSchema=be,exports.ChartJudgeRubricSchema=Te,exports.DataObservationKindSchema=ve,exports.DataObservationSchema=Se,exports.EvaluateParamsSchema=xe,exports.EvaluateResponseSchema=Ee,exports.ExecutionModeSchema=p,exports.ExploreFindingSchema=C,exports.ExploreStorySchema=A,exports.ExtractAccuracyEvaluationSchema=G,exports.ExtractAttachmentInputSchema=le,exports.ExtractAttachmentKindSchema=ne,exports.ExtractConfidenceSchema=P,exports.ExtractFromProseParamsSchema=de,exports.ExtractFromProseResponseSchema=ue,exports.ExtractMetaSchema=I,exports.GenerateAnnotationsResponseSchema=R,exports.GenerateExplorationResponseSchema=j,exports.GenerateGraphResponseSchema=ge,exports.GenerateGraphSuggestionsResponseSchema=he,exports.GenerateMutationResponseSchema=$,exports.GenerateNarrativeParamsSchema=_,exports.GenerateNarrativeResponseSchema=E,exports.GeneratePipelineParamsSchema=M,exports.GeneratePipelineResponseSchema=D,exports.GenerateSuggestionsParamsSchema=v,exports.GenerateSuggestionsResponseSchema=T,exports.GraphGenerationRequestSchema=x,exports.GraphyAiSdk=class{constructor(e){this.client=new o(e)}generateGraph(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,n=e.__rest(t,["storytellingOptions"]),o=yield this.client.fetch(`${De}/generate`,n,r,a),s=ge.parse(o);return this.stripStorytelling(s,i)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,i=e.__rest(t,["storytellingOptions"]),n=yield this.client.stream(`${De}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(n,a)})}generateNarrative(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/narrate`,t,r,a);return E.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${De}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/suggestions`,t,r,a);return T.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${De}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/explore`,t,r,a);return j.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${De}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/annotate`,t,r,a);return R.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${De}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/mutate`,t,r,a);return $.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${De}/mutate`,t,r)})}generatePipeline(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/pipeline`,t,r,a);return D.parse(e)})}generatePipelineStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${De}/pipeline`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/evaluate`,t,void 0,r);return Ee.parse(e)})}judge(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/judge`,t,void 0,r);return Me.parse(e)})}judgeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${De}/judge`,t,r)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${De}/extract`,t,r,a);return ue.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${De}/extract`,t,r)})}uploadAttachment(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=new FormData,i=null==r?void 0:r.filename;"undefined"!=typeof File&&t instanceof File?e.append("file",t):i?e.append("file",t,i):e.append("file",t,"upload"),i&&e.append("filename",i);const n=yield this.client.uploadMultipart(`${De}/attachments`,e,a);return pe.parse(n)})}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,n,o,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(a=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(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){n={error:e}}finally{try{l||a||!(o=m.return)||(yield e.__await(o.call(m)))}finally{if(n)throw n.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.InvocationEffortSchema=l,exports.JudgeParamsSchema=Ce,exports.JudgeResponseSchema=Me,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=u,exports.MAX_BUDGET_WALL_CLOCK_MS=d,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=K,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=N,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=X,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=F,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=U,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=L,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=q,exports.MAX_SOURCE_TEXT_LENGTH=B,exports.MAX_USER_PROMPT_LENGTH=b,exports.MetadataSchema=h,exports.MutateNarrationReceiptSchema=f,exports.PipelineAgentNameSchema=k,exports.PipelineStageReasoningSchema=O,exports.RubricScoresSchema=ke,exports.RunContextSchema=y,exports.StorytellingEffortSchema=m,exports.SuggestionSchema=w,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:te(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:te(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:te(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=i,exports.isErrorEvent=n,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,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,n=e=>"error"===e.type;class o{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 n(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,o,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,d,u;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,o,c),z=b.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var h,f=!0,y=e.__asyncValues(this.parseSSE(b));!(l=(h=yield y.next()).done);f=!0){d=h.value,f=!1;const e=d;if(a(e)&&s&&s(e),i(e))return e.data;if(n(e)){const a=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){m={error:e}}finally{try{f||l||!(p=y.return)||(yield p.call(y))}finally{if(m)throw m.error}}const o=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${o}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const a=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,r,a);return yield e.json()})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new r("Response body is null");const a=t.body.getReader(),i=new TextDecoder;let n="",o="",s="";try{for(;;){const{done:t,value:r}=yield e.__await(a.read());if(t)break;n+=i.decode(r,{stream:!0});const c=n.split(/\r?\n/);n=c.pop()||"";for(const t of c)if(t.startsWith("event: "))o=t.slice(7).trim();else if(t.startsWith("data: "))s+=(s?"\n":"")+t.slice(6);else if(""===t.trim()&&s){try{const t=JSON.parse(s);let r;if("progress"===o){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===o)r={type:"complete",data:t};else if("error"===o){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===o){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==o){o="",s="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===o||"error"===o)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}o="",s=""}}}finally{a.releaseLock()}})}makeRequest(t,a,i){return e.__awaiter(this,arguments,void 0,function*(e,t,a,i=1,n="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${o}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();a&&a.addEventListener("abort",l);try{const c=yield fetch(o,Object.assign({method:n,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===n&&{body:JSON.stringify(t)}));if(!c.ok){let o,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===o)&&(c.status>=500||429===c.status),m=new r(s,{status:c.status,code:o,retryable:l});if(l&&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,n)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(o){if(o instanceof r)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),o;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,n)}throw this.logger.error(`${this.tag} Network error: ${e}`,o),new r("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",l)}})}makeMultipartRequest(t,a,i){return e.__awaiter(this,arguments,void 0,function*(e,t,a,i=1){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");const o=new AbortController,s=setTimeout(()=>o.abort(),this.timeout),c=()=>o.abort();a&&a.addEventListener("abort",c);try{const s=yield fetch(n,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:o.signal});if(!s.ok){let n,o=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error),"string"==typeof t.code&&(n=t.code)}}catch(e){}const c=s.status>=500||429===s.status,l=new r(o,{status:s.status,code:n,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(r),this.makeMultipartRequest(e,t,a,i+1)}throw l}return s}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw 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 yield this.sleep(r),this.makeMultipartRequest(e,t,a,i+1)}throw new r("Network error",{retryable:!0})}finally{clearTimeout(s),a&&a.removeEventListener("abort",c)}})}}const s=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),l=t.z.enum(["low","medium","high"]),m=t.z.enum(["none","low","medium","high"]),p=t.z.enum(["agentic","fast"]),d=3e5,u=5e5,g=t.z.object({maxWallClockMs:t.z.number().positive().max(d).optional(),maxTotalTokens:t.z.number().int().positive().max(u).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),h=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()}),f=t.z.object({limits:g,consumed:h,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()}),y=t.z.object({callId:t.z.string().max(256).optional(),locale:s.optional(),effort:l.optional(),storytellingEffort:m.optional().default("low"),budget:g.optional(),executionMode:p.optional(),enforceTableRowCap:t.z.boolean().optional()}),b=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),z=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),x=1e4,v=t.z.enum(["comparison","relationship","distribution","composition"]),S=t.z.object({config:c,userPrompt:t.z.string().max(x).optional().default(""),metadata:y.optional(),chartFamily:v.optional()}),w=S.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),_=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),E=t.z.object({dataPrepPrompt:t.z.string(),chartType:_,summary:t.z.string()}),T=S.extend({userPrompt:t.z.string().max(x),mutationReceipt:b.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),C=t.z.object({response:t.z.object({message:t.z.string()}),config:c,run:z.optional()}),j=t.z.object({suggestions:t.z.array(E),run:z.optional()}),A=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.")}),R=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(A).describe("Child findings, sorted by quadrant score desc.")}),k=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(R),run:z.optional()});S.extend({mutationReceipt:b.optional()});const $=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c,run:z.optional()}),M=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c,mutationReceipt:b.optional(),warnings:t.z.array(t.z.string()).optional(),budget:f.optional(),run:z.optional()}),O=t.z.enum(["explore","mutate","narrate","annotate"]),D=t.z.object({agent:O,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),P=S.extend({userPrompt:t.z.string().max(x),stages:t.z.array(O).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),I=M.extend({reasoning:t.z.array(D),stories:t.z.array(R).optional()}),U=t.z.enum(["high","medium","low"]),G=t.z.object({confidence:U,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:U,quote:t.z.string().optional()})).optional()}),B=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()}),F=5e5,X=2097152,N=7340032,q=6291456,L=8388608,K=q,H=L,W=12582912;function Y(e){return 4*Math.ceil(e/3)}const J=Y(X),V=Y(N),Q=Y(q),Z=Y(L),ee=Y(K),te=Y(H),re=Y(W);function ae(e){return e.replace(/\s+/g,"")}function ie(e){const t=ae(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const ne=/^image\/(png|jpeg|jpg|webp|gif)$/i,oe=t.z.object({mimeType:t.z.string().min(1).refine(e=>ne.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(J).refine(ie,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),se=t.z.enum(["image","document","spreadsheet"]),ce=oe.extend({kind:t.z.literal("image")}),le=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(Q).refine(ie,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),me=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(ee).refine(ie,{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"]}),pe=t.z.discriminatedUnion("kind",[ce,le,me]),de=t.z.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),ue=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),kind:se,mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().positive(),expiresAt:t.z.string().datetime()}),ge=t.z.object({sourceText:t.z.string().max(F).default(""),images:t.z.array(oe).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(pe).max(12).optional(),attachmentRefs:t.z.array(de).max(12).optional(),metadata:y.optional()}).superRefine((e,t)=>{var r,a,i;const n=e.sourceText.trim(),o=null!==(r=e.images)&&void 0!==r?r:[],s=null!==(a=e.attachments)&&void 0!==a?a:[],c=null!==(i=e.attachmentRefs)&&void 0!==i?i:[];if(o.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(c.length>0&&s.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or inline `attachments`, not both.",path:["attachmentRefs"]});if(c.length>0&&o.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or deprecated `images`, not both.",path:["attachmentRefs"]});if(0===n.length&&0===o.length&&0===s.length&&0===c.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(c.length>0)return;if(o.length>0){o.reduce((e,t)=>e+ae(t.dataBase64).length,0)>V&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let l=0,m=0,p=0,d=0,u=0,g=0,h=0;for(const e of s){const t=ae(e.dataBase64).length;switch(h+=t,e.kind){case"image":l+=1,d+=t;break;case"document":m+=1,u+=t;break;case"spreadsheet":p+=1,g+=t}}l>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),p>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&p<=2;s.length>0&&f&&(d>V&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>Z&&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"]}),h>re&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const he=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:G.nullable(),lastAccuracyEvaluation:B.optional(),run:z.optional()}),fe=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:z.optional()}),ye=j,be=t.z.enum(["deal-breaker","pro","con","family","continuity"]),ze=t.z.object({kind:be,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),xe=t.z.enum(["ok","disqualified"]),ve=t.z.object({rank:t.z.number().int().positive(),type:_,score:t.z.number(),verdict:xe,factors:t.z.array(ze)}),Se=t.z.object({config:c,chartFamily:v.optional(),metadata:y.optional()}),we=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),_e=t.z.object({kind:we,message:t.z.string()}),Ee=t.z.enum(["sum","avg","count","min","max"]),Te=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:Ee,chartType:_,score:t.z.number(),message:t.z.string()}),Ce=t.z.object({ranking:t.z.array(ve),observations:t.z.array(_e).optional().default([]),suggestions:t.z.array(Te).optional().default([]),run:z.optional()}),je=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),Ae=t.z.object({config:c.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:je.optional(),userPrompt:t.z.string().optional(),metadata:y.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Re=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),ke=t.z.enum(["info","low","medium","high"]),$e=t.z.object({category:Re,severity:ke,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),Me=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array($e)}),Oe=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),De=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),Pe=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:Me.nullable(),chartVisionAudit:De.nullable().optional().default(null),rubricScores:Oe.nullable().optional().default(null),run:z.optional()}),Ie="/api/v0";exports.AggregationFunctionSchema=Ee,exports.AggregationSuggestionSchema=Te,exports.AiChartTypeEnum=_,exports.AttachmentUploadResponseSchema=ue,exports.ChartCritiqueIssueCategorySchema=Re,exports.ChartCritiqueIssueSchema=$e,exports.ChartCritiqueIssueSeveritySchema=ke,exports.ChartCritiqueReportSchema=Me,exports.ChartFamilySchema=v,exports.ChartFitEntrySchema=ve,exports.ChartFitFactorKindSchema=be,exports.ChartFitFactorSchema=ze,exports.ChartFitVerdictSchema=xe,exports.ChartJudgeRubricSchema=je,exports.DataObservationKindSchema=we,exports.DataObservationSchema=_e,exports.EvaluateParamsSchema=Se,exports.EvaluateResponseSchema=Ce,exports.ExecutionModeSchema=p,exports.ExploreFindingSchema=A,exports.ExploreStorySchema=R,exports.ExtractAccuracyEvaluationSchema=B,exports.ExtractAttachmentInputSchema=pe,exports.ExtractAttachmentKindSchema=se,exports.ExtractConfidenceSchema=U,exports.ExtractFromProseParamsSchema=ge,exports.ExtractFromProseResponseSchema=he,exports.ExtractMetaSchema=G,exports.GenerateAnnotationsResponseSchema=$,exports.GenerateExplorationResponseSchema=k,exports.GenerateGraphResponseSchema=fe,exports.GenerateGraphSuggestionsResponseSchema=ye,exports.GenerateMutationResponseSchema=M,exports.GenerateNarrativeParamsSchema=T,exports.GenerateNarrativeResponseSchema=C,exports.GeneratePipelineParamsSchema=P,exports.GeneratePipelineResponseSchema=I,exports.GenerateSuggestionsParamsSchema=w,exports.GenerateSuggestionsResponseSchema=j,exports.GraphGenerationRequestSchema=S,exports.GraphyAiSdk=class{constructor(e){this.client=new o(e)}generateGraph(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,n=e.__rest(t,["storytellingOptions"]),o=yield this.client.fetch(`${Ie}/generate`,n,r,a),s=fe.parse(o);return this.stripStorytelling(s,i)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,i=e.__rest(t,["storytellingOptions"]),n=yield this.client.stream(`${Ie}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(n,a)})}generateNarrative(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/narrate`,t,r,a);return C.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,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/suggestions`,t,r,a);return j.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,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/explore`,t,r,a);return k.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,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/annotate`,t,r,a);return $.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,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/mutate`,t,r,a);return M.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/mutate`,t,r)})}generatePipeline(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/pipeline`,t,r,a);return I.parse(e)})}generatePipelineStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/pipeline`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/evaluate`,t,void 0,r);return Ce.parse(e)})}judge(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/judge`,t,void 0,r);return Pe.parse(e)})}judgeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/judge`,t,r)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/extract`,t,r,a);return he.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/extract`,t,r)})}uploadAttachment(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=new FormData,i=null==r?void 0:r.filename;"undefined"!=typeof File&&t instanceof File?e.append("file",t):i?e.append("file",t,i):e.append("file",t,"upload"),i&&e.append("filename",i);const n=yield this.client.uploadMultipart(`${Ie}/attachments`,e,a);return ue.parse(n)})}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,n,o,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(a=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(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){n={error:e}}finally{try{l||a||!(o=m.return)||(yield e.__await(o.call(m)))}finally{if(n)throw n.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.InvocationEffortSchema=l,exports.JudgeParamsSchema=Ae,exports.JudgeResponseSchema=Pe,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=u,exports.MAX_BUDGET_WALL_CLOCK_MS=d,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=W,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=L,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=q,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=N,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=X,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=H,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=K,exports.MAX_SOURCE_TEXT_LENGTH=F,exports.MAX_USER_PROMPT_LENGTH=x,exports.MetadataSchema=y,exports.MutateNarrationReceiptSchema=b,exports.PipelineAgentNameSchema=O,exports.PipelineStageReasoningSchema=D,exports.RubricScoresSchema=Oe,exports.RunContextSchema=z,exports.StorytellingEffortSchema=m,exports.SuggestionSchema=E,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ae(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ae(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ae(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=i,exports.isErrorEvent=n,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
|
@@ -306,6 +306,7 @@ declare const InvocationBudgetSchema: z.ZodObject<{
|
|
|
306
306
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
307
307
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
308
308
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
309
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
309
310
|
}, z.core.$strip>;
|
|
310
311
|
type InvocationBudget = z.infer<typeof InvocationBudgetSchema>;
|
|
311
312
|
/**
|
|
@@ -333,6 +334,7 @@ declare const MetadataSchema: z.ZodObject<{
|
|
|
333
334
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
334
335
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
335
336
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
337
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
336
338
|
}, z.core.$strip>>;
|
|
337
339
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
338
340
|
agentic: "agentic";
|
|
@@ -417,6 +419,7 @@ declare const GraphGenerationRequestSchema: z.ZodObject<{
|
|
|
417
419
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
418
420
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
419
421
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
422
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
420
423
|
}, z.core.$strip>>;
|
|
421
424
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
422
425
|
agentic: "agentic";
|
|
@@ -457,6 +460,7 @@ declare const GenerateSuggestionsParamsSchema: z.ZodObject<{
|
|
|
457
460
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
458
461
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
459
462
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
463
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
460
464
|
}, z.core.$strip>>;
|
|
461
465
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
462
466
|
agentic: "agentic";
|
|
@@ -550,6 +554,7 @@ declare const GenerateNarrativeParamsSchema: z.ZodObject<{
|
|
|
550
554
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
551
555
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
552
556
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
557
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
553
558
|
}, z.core.$strip>>;
|
|
554
559
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
555
560
|
agentic: "agentic";
|
|
@@ -736,6 +741,7 @@ declare const GenerateAnnotationsParamsSchema: z.ZodObject<{
|
|
|
736
741
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
737
742
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
738
743
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
744
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
739
745
|
}, z.core.$strip>>;
|
|
740
746
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
741
747
|
agentic: "agentic";
|
|
@@ -822,6 +828,31 @@ declare const GenerateMutationResponseSchema: z.ZodObject<{
|
|
|
822
828
|
grainSummary: z.ZodOptional<z.ZodString>;
|
|
823
829
|
}, z.core.$strip>>;
|
|
824
830
|
warnings: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
831
|
+
budget: z.ZodOptional<z.ZodObject<{
|
|
832
|
+
limits: z.ZodObject<{
|
|
833
|
+
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
834
|
+
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
835
|
+
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
836
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
837
|
+
}, z.core.$strip>;
|
|
838
|
+
consumed: z.ZodObject<{
|
|
839
|
+
wallClockMs: z.ZodNumber;
|
|
840
|
+
inputTokens: z.ZodNumber;
|
|
841
|
+
inputCachedTokens: z.ZodNumber;
|
|
842
|
+
inputUncachedTokens: z.ZodNumber;
|
|
843
|
+
outputTokens: z.ZodNumber;
|
|
844
|
+
totalTokens: z.ZodNumber;
|
|
845
|
+
costUsd: z.ZodNullable<z.ZodNumber>;
|
|
846
|
+
costEnforcementSkipped: z.ZodOptional<z.ZodBoolean>;
|
|
847
|
+
}, z.core.$strip>;
|
|
848
|
+
exceeded: z.ZodBoolean;
|
|
849
|
+
exceededDimensions: z.ZodArray<z.ZodEnum<{
|
|
850
|
+
wallClockMs: "wallClockMs";
|
|
851
|
+
totalTokens: "totalTokens";
|
|
852
|
+
costUsd: "costUsd";
|
|
853
|
+
}>>;
|
|
854
|
+
exceededSummary: z.ZodOptional<z.ZodString>;
|
|
855
|
+
}, z.core.$strip>>;
|
|
825
856
|
run: z.ZodOptional<z.ZodObject<{
|
|
826
857
|
runId: z.ZodString;
|
|
827
858
|
trackingId: z.ZodString;
|
|
@@ -873,6 +904,7 @@ declare const GeneratePipelineParamsSchema: z.ZodObject<{
|
|
|
873
904
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
874
905
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
875
906
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
907
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
876
908
|
}, z.core.$strip>>;
|
|
877
909
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
878
910
|
agentic: "agentic";
|
|
@@ -928,6 +960,31 @@ declare const GeneratePipelineResponseSchema: z.ZodObject<{
|
|
|
928
960
|
grainSummary: z.ZodOptional<z.ZodString>;
|
|
929
961
|
}, z.core.$strip>>;
|
|
930
962
|
warnings: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
963
|
+
budget: z.ZodOptional<z.ZodObject<{
|
|
964
|
+
limits: z.ZodObject<{
|
|
965
|
+
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
966
|
+
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
967
|
+
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
968
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
969
|
+
}, z.core.$strip>;
|
|
970
|
+
consumed: z.ZodObject<{
|
|
971
|
+
wallClockMs: z.ZodNumber;
|
|
972
|
+
inputTokens: z.ZodNumber;
|
|
973
|
+
inputCachedTokens: z.ZodNumber;
|
|
974
|
+
inputUncachedTokens: z.ZodNumber;
|
|
975
|
+
outputTokens: z.ZodNumber;
|
|
976
|
+
totalTokens: z.ZodNumber;
|
|
977
|
+
costUsd: z.ZodNullable<z.ZodNumber>;
|
|
978
|
+
costEnforcementSkipped: z.ZodOptional<z.ZodBoolean>;
|
|
979
|
+
}, z.core.$strip>;
|
|
980
|
+
exceeded: z.ZodBoolean;
|
|
981
|
+
exceededDimensions: z.ZodArray<z.ZodEnum<{
|
|
982
|
+
wallClockMs: "wallClockMs";
|
|
983
|
+
totalTokens: "totalTokens";
|
|
984
|
+
costUsd: "costUsd";
|
|
985
|
+
}>>;
|
|
986
|
+
exceededSummary: z.ZodOptional<z.ZodString>;
|
|
987
|
+
}, z.core.$strip>>;
|
|
931
988
|
run: z.ZodOptional<z.ZodObject<{
|
|
932
989
|
runId: z.ZodString;
|
|
933
990
|
trackingId: z.ZodString;
|
|
@@ -1107,6 +1164,7 @@ declare const ExtractFromProseParamsSchema: z.ZodObject<{
|
|
|
1107
1164
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
1108
1165
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
1109
1166
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
1167
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
1110
1168
|
}, z.core.$strip>>;
|
|
1111
1169
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
1112
1170
|
agentic: "agentic";
|
|
@@ -1348,6 +1406,7 @@ declare const EvaluateParamsSchema: z.ZodObject<{
|
|
|
1348
1406
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
1349
1407
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
1350
1408
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
1409
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
1351
1410
|
}, z.core.$strip>>;
|
|
1352
1411
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
1353
1412
|
agentic: "agentic";
|
|
@@ -1610,6 +1669,7 @@ declare const JudgeParamsSchema: z.ZodObject<{
|
|
|
1610
1669
|
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
1611
1670
|
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
1612
1671
|
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
1672
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
1613
1673
|
}, z.core.$strip>>;
|
|
1614
1674
|
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
1615
1675
|
agentic: "agentic";
|
|
@@ -2060,6 +2120,27 @@ declare class GraphyAiSdk {
|
|
|
2060
2120
|
grainSummary?: string | undefined;
|
|
2061
2121
|
} | undefined;
|
|
2062
2122
|
warnings?: string[] | undefined;
|
|
2123
|
+
budget?: {
|
|
2124
|
+
limits: {
|
|
2125
|
+
maxWallClockMs?: number | undefined;
|
|
2126
|
+
maxTotalTokens?: number | undefined;
|
|
2127
|
+
maxCostUsd?: number | undefined;
|
|
2128
|
+
trackUsage?: boolean | undefined;
|
|
2129
|
+
};
|
|
2130
|
+
consumed: {
|
|
2131
|
+
wallClockMs: number;
|
|
2132
|
+
inputTokens: number;
|
|
2133
|
+
inputCachedTokens: number;
|
|
2134
|
+
inputUncachedTokens: number;
|
|
2135
|
+
outputTokens: number;
|
|
2136
|
+
totalTokens: number;
|
|
2137
|
+
costUsd: number | null;
|
|
2138
|
+
costEnforcementSkipped?: boolean | undefined;
|
|
2139
|
+
};
|
|
2140
|
+
exceeded: boolean;
|
|
2141
|
+
exceededDimensions: ("wallClockMs" | "totalTokens" | "costUsd")[];
|
|
2142
|
+
exceededSummary?: string | undefined;
|
|
2143
|
+
} | undefined;
|
|
2063
2144
|
run?: {
|
|
2064
2145
|
runId: string;
|
|
2065
2146
|
trackingId: string;
|
|
@@ -2097,6 +2178,27 @@ declare class GraphyAiSdk {
|
|
|
2097
2178
|
grainSummary?: string | undefined;
|
|
2098
2179
|
} | undefined;
|
|
2099
2180
|
warnings?: string[] | undefined;
|
|
2181
|
+
budget?: {
|
|
2182
|
+
limits: {
|
|
2183
|
+
maxWallClockMs?: number | undefined;
|
|
2184
|
+
maxTotalTokens?: number | undefined;
|
|
2185
|
+
maxCostUsd?: number | undefined;
|
|
2186
|
+
trackUsage?: boolean | undefined;
|
|
2187
|
+
};
|
|
2188
|
+
consumed: {
|
|
2189
|
+
wallClockMs: number;
|
|
2190
|
+
inputTokens: number;
|
|
2191
|
+
inputCachedTokens: number;
|
|
2192
|
+
inputUncachedTokens: number;
|
|
2193
|
+
outputTokens: number;
|
|
2194
|
+
totalTokens: number;
|
|
2195
|
+
costUsd: number | null;
|
|
2196
|
+
costEnforcementSkipped?: boolean | undefined;
|
|
2197
|
+
};
|
|
2198
|
+
exceeded: boolean;
|
|
2199
|
+
exceededDimensions: ("wallClockMs" | "totalTokens" | "costUsd")[];
|
|
2200
|
+
exceededSummary?: string | undefined;
|
|
2201
|
+
} | undefined;
|
|
2100
2202
|
run?: {
|
|
2101
2203
|
runId: string;
|
|
2102
2204
|
trackingId: string;
|
|
@@ -2135,6 +2237,27 @@ declare class GraphyAiSdk {
|
|
|
2135
2237
|
grainSummary?: string | undefined;
|
|
2136
2238
|
} | undefined;
|
|
2137
2239
|
warnings?: string[] | undefined;
|
|
2240
|
+
budget?: {
|
|
2241
|
+
limits: {
|
|
2242
|
+
maxWallClockMs?: number | undefined;
|
|
2243
|
+
maxTotalTokens?: number | undefined;
|
|
2244
|
+
maxCostUsd?: number | undefined;
|
|
2245
|
+
trackUsage?: boolean | undefined;
|
|
2246
|
+
};
|
|
2247
|
+
consumed: {
|
|
2248
|
+
wallClockMs: number;
|
|
2249
|
+
inputTokens: number;
|
|
2250
|
+
inputCachedTokens: number;
|
|
2251
|
+
inputUncachedTokens: number;
|
|
2252
|
+
outputTokens: number;
|
|
2253
|
+
totalTokens: number;
|
|
2254
|
+
costUsd: number | null;
|
|
2255
|
+
costEnforcementSkipped?: boolean | undefined;
|
|
2256
|
+
};
|
|
2257
|
+
exceeded: boolean;
|
|
2258
|
+
exceededDimensions: ("wallClockMs" | "totalTokens" | "costUsd")[];
|
|
2259
|
+
exceededSummary?: string | undefined;
|
|
2260
|
+
} | undefined;
|
|
2138
2261
|
run?: {
|
|
2139
2262
|
runId: string;
|
|
2140
2263
|
trackingId: string;
|
|
@@ -2183,6 +2306,27 @@ declare class GraphyAiSdk {
|
|
|
2183
2306
|
grainSummary?: string | undefined;
|
|
2184
2307
|
} | undefined;
|
|
2185
2308
|
warnings?: string[] | undefined;
|
|
2309
|
+
budget?: {
|
|
2310
|
+
limits: {
|
|
2311
|
+
maxWallClockMs?: number | undefined;
|
|
2312
|
+
maxTotalTokens?: number | undefined;
|
|
2313
|
+
maxCostUsd?: number | undefined;
|
|
2314
|
+
trackUsage?: boolean | undefined;
|
|
2315
|
+
};
|
|
2316
|
+
consumed: {
|
|
2317
|
+
wallClockMs: number;
|
|
2318
|
+
inputTokens: number;
|
|
2319
|
+
inputCachedTokens: number;
|
|
2320
|
+
inputUncachedTokens: number;
|
|
2321
|
+
outputTokens: number;
|
|
2322
|
+
totalTokens: number;
|
|
2323
|
+
costUsd: number | null;
|
|
2324
|
+
costEnforcementSkipped?: boolean | undefined;
|
|
2325
|
+
};
|
|
2326
|
+
exceeded: boolean;
|
|
2327
|
+
exceededDimensions: ("wallClockMs" | "totalTokens" | "costUsd")[];
|
|
2328
|
+
exceededSummary?: string | undefined;
|
|
2329
|
+
} | undefined;
|
|
2186
2330
|
run?: {
|
|
2187
2331
|
runId: string;
|
|
2188
2332
|
trackingId: string;
|
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 a}from"zod";class o 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 s=e=>e instanceof o,l=e=>"progress"===e.type,c=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type;class g{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return l(e)}static isCompleteEvent(e){return c(e)}static isErrorEvent(e){return m(e)}stream(t,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,a){return e(this,void 0,void 0,function*(){var e,s,d,u,g;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const b=yield this.makeRequest(i,n,a),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,y=t(this.parseSSE(b));!(e=(h=yield y.next()).done);f=!0){u=h.value,f=!1;const e=u;if(l(e)&&r&&r(e),c(e))return e.data;if(m(e)){const t=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new o(e.error,{code:e.code,retryable:null!==(g=e.retryable)&&void 0!==g&&g})}}}catch(e){s={error:e}}finally{try{f||e||!(d=y.return)||(yield d.call(y))}finally{if(s)throw s.error}}const n=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${n}ms`),new o("Stream ended without completion")}return yield b.json()}catch(e){const t=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof o)throw e;throw e}finally{const e=Date.now()-p;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}}})}uploadMultipart(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,i,n);return yield e.json()})}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 o("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let r="",a="",s="";try{for(;;){const{done:e,value:o}=yield n(t.read());if(e)break;r+=i.decode(o,{stream:!0});const l=r.split(/\r?\n/);r=l.pop()||"";for(const e of l)if(e.startsWith("event: "))a=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=JSON.parse(s);let t;if("progress"===a){const i=e;t=Object.assign({type:"progress"},i)}else if("complete"===a)t={type:"complete",data:e};else if("error"===a){const i=e;t=Object.assign({type:"error"},i)}else if("preview"===a){const i=e;t=Object.assign(Object.assign({},i),{type:"preview"})}else{if("reasoning"!==a){a="",s="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield n(t),"complete"===a||"error"===a)return yield n(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}a="",s=""}}}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 o("Invalid endpoint: must start with /");const a=new URL(e,this.baseUrl);if(a.origin!==new URL(this.baseUrl).origin)throw new o("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${a}`);const s=new AbortController,l=setTimeout(()=>s.abort(),this.timeout),c=()=>s.abort();i&&i.addEventListener("abort",c);try{const l=yield fetch(a,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:s.signal},"POST"===r&&{body:JSON.stringify(t)}));if(!l.ok){let a,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(a=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===a)&&(l.status>=500||429===l.status),m=new o(s,{status:l.status,code:a,retryable:c});if(c&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const a=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${a}ms (attempt ${n+1})`),yield this.sleep(a),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(a){if(a instanceof o)throw a;if(a instanceof Error&&"AbortError"===a.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),a;if(n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const a=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${a}ms`),yield this.sleep(a),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,a),new o("Network error",{retryable:!0})}finally{clearTimeout(l),i&&i.removeEventListener("abort",c)}})}makeMultipartRequest(t,i,n){return e(this,arguments,void 0,function*(e,t,i,n=1){if(!e.startsWith("/"))throw new o("Invalid endpoint: must start with /");const r=new URL(e,this.baseUrl);if(r.origin!==new URL(this.baseUrl).origin)throw new o("Endpoint resolved to unexpected origin");const a=new AbortController,s=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();i&&i.addEventListener("abort",l);try{const s=yield fetch(r,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:a.signal});if(!s.ok){let r,a=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?a=t.message:"string"==typeof t.error&&(a=t.error),"string"==typeof t.code&&(r=t.code)}}catch(e){}const l=s.status>=500||429===s.status,c=new o(a,{status:s.status,code:r,retryable:l});if(l&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return yield this.sleep(r),this.makeMultipartRequest(e,t,i,n+1)}throw c}return s}catch(r){if(r instanceof o)throw r;if(r instanceof Error&&"AbortError"===r.name)throw r;if(n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return yield this.sleep(r),this.makeMultipartRequest(e,t,i,n+1)}throw new o("Network error",{retryable:!0})}finally{clearTimeout(s),i&&i.removeEventListener("abort",l)}})}}const p=a.enum(["EN_GB","EN_US"]),h=a.custom(e=>null!=e&&"object"==typeof e),f=a.enum(["low","medium","high"]),y=a.enum(["none","low","medium","high"]),b=a.enum(["agentic","fast"]),v=3e5,w=5e5,x=10,j=a.object({maxWallClockMs:a.number().positive().max(v).optional(),maxTotalTokens:a.number().int().positive().max(w).optional(),maxCostUsd:a.number().positive().max(10).optional()}),$=a.object({callId:a.string().max(256).optional(),locale:p.optional(),effort:f.optional(),storytellingEffort:y.optional().default("low"),budget:j.optional(),executionMode:b.optional(),enforceTableRowCap:a.boolean().optional()}),k=a.object({steps:a.array(a.string()),postProcess:a.object({measureRelevance:a.enum(["prompt-named","derived","magnitude"]).optional(),grain:a.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:a.string().optional(),comparison:a.string().optional()}).optional(),droppedMeasures:a.array(a.string()).optional(),rowCount:a.number().int().nonnegative(),totalRowCountBeforeSlice:a.number().int().positive().optional(),displayedRowCount:a.number().int().nonnegative().optional(),columnKeys:a.array(a.string()),activeFilters:a.array(a.string()).optional(),grainSummary:a.string().optional()}),S=a.object({runId:a.string(),trackingId:a.string(),callId:a.string().optional()}),C=1e4,R=a.enum(["comparison","relationship","distribution","composition"]),T=a.object({config:h,userPrompt:a.string().max(C).optional().default(""),metadata:$.optional(),chartFamily:R.optional()}),E=T.extend({maxSuggestionCount:a.number().int().min(1).max(4).optional()}),I=a.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),O=a.object({dataPrepPrompt:a.string(),chartType:I,summary:a.string()}),A=T.extend({userPrompt:a.string().max(C),mutationReceipt:k.optional(),exploreFindingSummary:a.string().max(500).optional()}),P=a.object({response:a.object({message:a.string()}),config:h,run:S.optional()}),U=a.object({suggestions:a.array(O),run:S.optional()}),B=a.object({finding:a.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:a.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:a.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:a.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:a.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:R.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:a.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),F=a.object({topic:a.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:a.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:a.number().int().min(1).describe("Number of findings in this story."),findings:a.array(B).describe("Child findings, sorted by quadrant score desc.")}),q=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),stories:a.array(F),run:S.optional()});T.extend({mutationReceipt:k.optional()});const M=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,run:S.optional()}),D=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,mutationReceipt:k.optional(),warnings:a.array(a.string()).optional(),run:S.optional()}),N=a.enum(["explore","mutate","narrate","annotate"]),K=a.object({agent:N,summary:a.string(),steps:a.array(a.string()).optional()}),L=T.extend({userPrompt:a.string().max(C),stages:a.array(N).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:a.string().max(500).optional()}),G=D.extend({reasoning:a.array(K),stories:a.array(F).optional()}),W=a.enum(["high","medium","low"]),z=a.object({confidence:W,needsUserInput:a.boolean(),warnings:a.array(a.string()),cellConfidence:a.array(a.object({rowIndex:a.number().int().nonnegative(),columnKey:a.string(),confidence:W,quote:a.string().optional()})).optional()}),_=a.object({score:a.number().min(0).max(1),issues:a.array(a.string()),sufficient:a.boolean(),summary:a.string()}),H=5e5,J=8,X=2097152,Q=7340032,V=2,Y=6291456,Z=8388608,ee=2,te=Y,ie=Z,ne=12582912,re=12;function ae(e){return 4*Math.ceil(e/3)}const oe=ae(X),se=ae(Q),le=ae(Y),ce=ae(Z),me=ae(te),de=ae(ie),ue=ae(ne);function ge(e){return e.replace(/\s+/g,"")}function pe(e){const t=ge(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const he=/^image\/(png|jpeg|jpg|webp|gif)$/i,fe=a.object({mimeType:a.string().min(1).refine(e=>he.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:a.string().min(1).max(oe).refine(pe,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ye=a.enum(["image","document","spreadsheet"]),be=fe.extend({kind:a.literal("image")}),ve=a.object({kind:a.literal("document"),mimeType:a.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:a.string().min(1).max(le).refine(pe,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),we=a.object({kind:a.literal("spreadsheet"),mimeType:a.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:a.string().min(1).max(me).refine(pe,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:a.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),xe=a.discriminatedUnion("kind",[be,ve,we]),je=a.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),$e=a.object({id:a.string().uuid(),uri:a.string(),kind:ye,mimeType:a.string(),filename:a.string().optional(),sizeBytes:a.number().int().positive(),expiresAt:a.string().datetime()}),ke=a.object({sourceText:a.string().max(H).default(""),images:a.array(fe).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:a.array(xe).max(12).optional(),attachmentRefs:a.array(je).max(12).optional(),metadata:$.optional()}).superRefine((e,t)=>{var i,n,r;const a=e.sourceText.trim(),o=null!==(i=e.images)&&void 0!==i?i:[],s=null!==(n=e.attachments)&&void 0!==n?n:[],l=null!==(r=e.attachmentRefs)&&void 0!==r?r:[];if(o.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(l.length>0&&s.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or inline `attachments`, not both.",path:["attachmentRefs"]});if(l.length>0&&o.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or deprecated `images`, not both.",path:["attachmentRefs"]});if(0===a.length&&0===o.length&&0===s.length&&0===l.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(l.length>0)return;if(o.length>0){o.reduce((e,t)=>e+ge(t.dataBase64).length,0)>se&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let c=0,m=0,d=0,u=0,g=0,p=0,h=0;for(const e of s){const t=ge(e.dataBase64).length;switch(h+=t,e.kind){case"image":c+=1,u+=t;break;case"document":m+=1,g+=t;break;case"spreadsheet":d+=1,p+=t}}c>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),d>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=c<=8&&m<=2&&d<=2;s.length>0&&f&&(u>se&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>ce&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>de&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>ue&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function Se(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ge(e.dataBase64)}}function Ce(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ge(e.dataBase64)}}function Re(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ge(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const Te=a.object({response:a.object({message:a.string()}),config:h,extractMeta:z.nullable(),lastAccuracyEvaluation:_.optional(),run:S.optional()}),Ee=a.object({config:h,response:a.object({message:a.string(),steps:a.array(a.string())}),run:S.optional()}),Ie=U,Oe=a.enum(["deal-breaker","pro","con","family","continuity"]),Ae=a.object({kind:Oe,label:a.string(),weight:a.number(),reason:a.string()}),Pe=a.enum(["ok","disqualified"]),Ue=a.object({rank:a.number().int().positive(),type:I,score:a.number(),verdict:Pe,factors:a.array(Ae)}),Be=a.object({config:h,chartFamily:R.optional(),metadata:$.optional()}),Fe=a.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),qe=a.object({kind:Fe,message:a.string()}),Me=a.enum(["sum","avg","count","min","max"]),De=a.object({dimensionName:a.string(),dimensionLabel:a.string(),measureName:a.string().nullable(),measureLabel:a.string().nullable(),fn:Me,chartType:I,score:a.number(),message:a.string()}),Ne=a.object({ranking:a.array(Ue),observations:a.array(qe).optional().default([]),suggestions:a.array(De).optional().default([]),run:S.optional()}),Ke=a.object({prompt:a.string(),datasetSummary:a.string().optional(),mustShow:a.array(a.string()).optional(),unacceptable:a.array(a.string()).optional(),acceptableChartFamilies:a.array(a.string()).optional()}),Le=a.object({config:h.optional(),chartImage:a.string().optional(),data:a.unknown().optional(),rubric:Ke.optional(),userPrompt:a.string().optional(),metadata:$.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ge=a.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),We=a.enum(["info","low","medium","high"]),ze=a.object({category:Ge,severity:We,observation:a.string(),rationale:a.string().optional(),suggestedChange:a.string().optional(),configPaths:a.array(a.string()).optional()}),_e=a.object({overallSummary:a.string(),overallSeverity:a.enum(["none","low","medium","high"]).optional(),issues:a.array(ze)}),He=a.object({dataFidelity:a.number().min(0).max(1),promptRelevance:a.number().min(0).max(1),chartTypeAppropriateness:a.number().min(0).max(1),readability:a.number().min(0).max(1),honesty:a.number().min(0).max(1),composite:a.number().min(0).max(1),rationale:a.string().optional()}),Je=a.object({capturedAt:a.string(),chartId:a.string()}),Xe=a.object({response:a.object({message:a.string(),steps:a.array(a.string()),critiqueCommitted:a.boolean()}),critiqueReport:_e.nullable(),chartVisionAudit:Je.nullable().optional().default(null),rubricScores:He.nullable().optional().default(null),run:S.optional()}),Qe="/api/v0";class Ve{constructor(e){this.client=new g(e)}generateGraph(t,i,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,a=r(t,["storytellingOptions"]),o=yield this.client.fetch(`${Qe}/generate`,a,i,n),s=Ee.parse(o);return this.stripStorytelling(s,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,n=r(t,["storytellingOptions"]),a=yield this.client.stream(`${Qe}/generate`,n,i);return this.wrapStreamWithStorytellingStripping(a,e)})}generateNarrative(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/narrate`,t,i,n);return P.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/suggestions`,t,i,n);return U.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/explore`,t,i,n);return q.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/annotate`,t,i,n);return M.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/mutate`,t,i,n);return D.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/mutate`,t,i)})}generatePipeline(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/pipeline`,t,i,n);return G.parse(e)})}generatePipelineStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/pipeline`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/evaluate`,t,void 0,i);return Ne.parse(e)})}judge(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/judge`,t,void 0,i);return Xe.parse(e)})}judgeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/judge`,t,i)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/extract`,t,i,n);return Te.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/extract`,t,i)})}uploadAttachment(t,i,n){return e(this,void 0,void 0,function*(){const e=new FormData,r=null==i?void 0:i.filename;"undefined"!=typeof File&&t instanceof File?e.append("file",t):r?e.append("file",t,r):e.append("file",t,"upload"),r&&e.append("filename",r);const a=yield this.client.uploadMultipart(`${Qe}/attachments`,e,n);return $e.parse(a)})}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,a,o,s;try{for(var l,m=!0,d=t(e);!(i=(l=yield n(d.next())).done);m=!0){s=l.value,m=!1;const e=s;if(c(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){a={error:e}}finally{try{m||i||!(o=d.return)||(yield n(o.call(d)))}finally{if(a)throw a.error}}})}}export{Me as AggregationFunctionSchema,De as AggregationSuggestionSchema,I as AiChartTypeEnum,$e as AttachmentUploadResponseSchema,Ge as ChartCritiqueIssueCategorySchema,ze as ChartCritiqueIssueSchema,We as ChartCritiqueIssueSeveritySchema,_e as ChartCritiqueReportSchema,R as ChartFamilySchema,Ue as ChartFitEntrySchema,Oe as ChartFitFactorKindSchema,Ae as ChartFitFactorSchema,Pe as ChartFitVerdictSchema,Ke as ChartJudgeRubricSchema,Fe as DataObservationKindSchema,qe as DataObservationSchema,Be as EvaluateParamsSchema,Ne as EvaluateResponseSchema,b as ExecutionModeSchema,B as ExploreFindingSchema,F as ExploreStorySchema,_ as ExtractAccuracyEvaluationSchema,xe as ExtractAttachmentInputSchema,ye as ExtractAttachmentKindSchema,W as ExtractConfidenceSchema,ke as ExtractFromProseParamsSchema,Te as ExtractFromProseResponseSchema,z as ExtractMetaSchema,M as GenerateAnnotationsResponseSchema,q as GenerateExplorationResponseSchema,Ee as GenerateGraphResponseSchema,Ie as GenerateGraphSuggestionsResponseSchema,D as GenerateMutationResponseSchema,A as GenerateNarrativeParamsSchema,P as GenerateNarrativeResponseSchema,L as GeneratePipelineParamsSchema,G as GeneratePipelineResponseSchema,E as GenerateSuggestionsParamsSchema,U as GenerateSuggestionsResponseSchema,T as GraphGenerationRequestSchema,Ve as GraphyAiSdk,o as GraphyApiError,j as InvocationBudgetSchema,f as InvocationEffortSchema,Le as JudgeParamsSchema,Xe as JudgeResponseSchema,x as MAX_BUDGET_COST_USD,w as MAX_BUDGET_TOTAL_TOKENS,v as MAX_BUDGET_WALL_CLOCK_MS,re as MAX_EXTRACT_ATTACHMENTS,ne as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,V as MAX_EXTRACT_DOCUMENTS,Z as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,Y as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,J as MAX_EXTRACT_IMAGES,Q as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,X as MAX_EXTRACT_IMAGE_DECODED_BYTES,ee as MAX_EXTRACT_SPREADSHEETS,ie as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,te as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,H as MAX_SOURCE_TEXT_LENGTH,C as MAX_USER_PROMPT_LENGTH,$ as MetadataSchema,k as MutateNarrationReceiptSchema,N as PipelineAgentNameSchema,K as PipelineStageReasoningSchema,He as RubricScoresSchema,S as RunContextSchema,y as StorytellingEffortSchema,O as SuggestionSchema,Se as buildImageAttachment,Ce as buildPdfAttachment,Re as buildSpreadsheetAttachment,c as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,d as isPreviewEvent,l as isProgressEvent,u as isReasoningEvent};
|
|
1
|
+
import{__awaiter as e,__asyncValues as t,__asyncGenerator as n,__await as i,__rest as r}from"tslib";import{z as a}from"zod";class o extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const s=e=>e instanceof o,l=e=>"progress"===e.type,c=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type;class g{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return l(e)}static isCompleteEvent(e){return c(e)}static isErrorEvent(e){return m(e)}stream(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i);return this.parseSSE(e)})}fetch(n,i,r,a){return e(this,void 0,void 0,function*(){var e,s,d,u,g;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${n}`);try{const y=yield this.makeRequest(n,i,a),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,b=t(this.parseSSE(y));!(e=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(l(e)&&r&&r(e),c(e))return e.data;if(m(e)){const t=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${n} ${t}ms`,e.error),new o(e.error,{code:e.code,retryable:null!==(g=e.retryable)&&void 0!==g&&g})}}}catch(e){s={error:e}}finally{try{f||e||!(d=b.return)||(yield d.call(b))}finally{if(s)throw s.error}}const i=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${n} ${i}ms`),new o("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${n} ${t}ms`,e),e instanceof o)throw e;throw e}finally{const e=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${n} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,i);return yield e.json()})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return n(this,arguments,function*(){if(!e.body)throw new o("Response body is null");const t=e.body.getReader(),n=new TextDecoder;let r="",a="",s="";try{for(;;){const{done:e,value:o}=yield i(t.read());if(e)break;r+=n.decode(o,{stream:!0});const l=r.split(/\r?\n/);r=l.pop()||"";for(const e of l)if(e.startsWith("event: "))a=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=JSON.parse(s);let t;if("progress"===a){const n=e;t=Object.assign({type:"progress"},n)}else if("complete"===a)t={type:"complete",data:e};else if("error"===a){const n=e;t=Object.assign({type:"error"},n)}else if("preview"===a){const n=e;t=Object.assign(Object.assign({},n),{type:"preview"})}else{if("reasoning"!==a){a="",s="";continue}{const n=e;t=Object.assign(Object.assign({},n),{type:"reasoning"})}}if(yield yield i(t),"complete"===a||"error"===a)return yield i(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}a="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1,r="POST"){if(!e.startsWith("/"))throw new o("Invalid endpoint: must start with /");const a=new URL(e,this.baseUrl);if(a.origin!==new URL(this.baseUrl).origin)throw new o("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${a}`);const s=new AbortController,l=setTimeout(()=>s.abort(),this.timeout),c=()=>s.abort();n&&n.addEventListener("abort",c);try{const l=yield fetch(a,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:s.signal},"POST"===r&&{body:JSON.stringify(t)}));if(!l.ok){let a,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(a=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===a)&&(l.status>=500||429===l.status),m=new o(s,{status:l.status,code:a,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const a=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${a}ms (attempt ${i+1})`),yield this.sleep(a),this.makeRequest(e,t,n,i+1,r)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(a){if(a instanceof o)throw a;if(a instanceof Error&&"AbortError"===a.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),a;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const a=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${a}ms`),yield this.sleep(a),this.makeRequest(e,t,n,i+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,a),new o("Network error",{retryable:!0})}finally{clearTimeout(l),n&&n.removeEventListener("abort",c)}})}makeMultipartRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1){if(!e.startsWith("/"))throw new o("Invalid endpoint: must start with /");const r=new URL(e,this.baseUrl);if(r.origin!==new URL(this.baseUrl).origin)throw new o("Endpoint resolved to unexpected origin");const a=new AbortController,s=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();n&&n.addEventListener("abort",l);try{const s=yield fetch(r,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:a.signal});if(!s.ok){let r,a=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?a=t.message:"string"==typeof t.error&&(a=t.error),"string"==typeof t.code&&(r=t.code)}}catch(e){}const l=s.status>=500||429===s.status,c=new o(a,{status:s.status,code:r,retryable:l});if(l&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(r),this.makeMultipartRequest(e,t,n,i+1)}throw c}return s}catch(r){if(r instanceof o)throw r;if(r instanceof Error&&"AbortError"===r.name)throw r;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(r),this.makeMultipartRequest(e,t,n,i+1)}throw new o("Network error",{retryable:!0})}finally{clearTimeout(s),n&&n.removeEventListener("abort",l)}})}}const p=a.enum(["EN_GB","EN_US"]),h=a.custom(e=>null!=e&&"object"==typeof e),f=a.enum(["low","medium","high"]),b=a.enum(["none","low","medium","high"]),y=a.enum(["agentic","fast"]),v=3e5,w=5e5,x=10,j=a.object({maxWallClockMs:a.number().positive().max(v).optional(),maxTotalTokens:a.number().int().positive().max(w).optional(),maxCostUsd:a.number().positive().max(10).optional(),trackUsage:a.boolean().optional()}),k=a.object({wallClockMs:a.number(),inputTokens:a.number(),inputCachedTokens:a.number(),inputUncachedTokens:a.number(),outputTokens:a.number(),totalTokens:a.number(),costUsd:a.number().nullable(),costEnforcementSkipped:a.boolean().optional()}),$=a.object({limits:j,consumed:k,exceeded:a.boolean(),exceededDimensions:a.array(a.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:a.string().optional()}),S=a.object({callId:a.string().max(256).optional(),locale:p.optional(),effort:f.optional(),storytellingEffort:b.optional().default("low"),budget:j.optional(),executionMode:y.optional(),enforceTableRowCap:a.boolean().optional()}),C=a.object({steps:a.array(a.string()),postProcess:a.object({measureRelevance:a.enum(["prompt-named","derived","magnitude"]).optional(),grain:a.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:a.string().optional(),comparison:a.string().optional()}).optional(),droppedMeasures:a.array(a.string()).optional(),rowCount:a.number().int().nonnegative(),totalRowCountBeforeSlice:a.number().int().positive().optional(),displayedRowCount:a.number().int().nonnegative().optional(),columnKeys:a.array(a.string()),activeFilters:a.array(a.string()).optional(),grainSummary:a.string().optional()}),T=a.object({runId:a.string(),trackingId:a.string(),callId:a.string().optional()}),R=1e4,E=a.enum(["comparison","relationship","distribution","composition"]),I=a.object({config:h,userPrompt:a.string().max(R).optional().default(""),metadata:S.optional(),chartFamily:E.optional()}),O=I.extend({maxSuggestionCount:a.number().int().min(1).max(4).optional()}),A=a.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),P=a.object({dataPrepPrompt:a.string(),chartType:A,summary:a.string()}),U=I.extend({userPrompt:a.string().max(R),mutationReceipt:C.optional(),exploreFindingSummary:a.string().max(500).optional()}),B=a.object({response:a.object({message:a.string()}),config:h,run:T.optional()}),M=a.object({suggestions:a.array(P),run:T.optional()}),F=a.object({finding:a.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:a.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:a.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:a.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:a.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:E.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:a.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),q=a.object({topic:a.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:a.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:a.number().int().min(1).describe("Number of findings in this story."),findings:a.array(F).describe("Child findings, sorted by quadrant score desc.")}),D=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),stories:a.array(q),run:T.optional()});I.extend({mutationReceipt:C.optional()});const N=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,run:T.optional()}),K=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,mutationReceipt:C.optional(),warnings:a.array(a.string()).optional(),budget:$.optional(),run:T.optional()}),L=a.enum(["explore","mutate","narrate","annotate"]),G=a.object({agent:L,summary:a.string(),steps:a.array(a.string()).optional()}),W=I.extend({userPrompt:a.string().max(R),stages:a.array(L).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:a.string().max(500).optional()}),z=K.extend({reasoning:a.array(G),stories:a.array(q).optional()}),_=a.enum(["high","medium","low"]),H=a.object({confidence:_,needsUserInput:a.boolean(),warnings:a.array(a.string()),cellConfidence:a.array(a.object({rowIndex:a.number().int().nonnegative(),columnKey:a.string(),confidence:_,quote:a.string().optional()})).optional()}),J=a.object({score:a.number().min(0).max(1),issues:a.array(a.string()),sufficient:a.boolean(),summary:a.string()}),X=5e5,Q=8,V=2097152,Y=7340032,Z=2,ee=6291456,te=8388608,ne=2,ie=ee,re=te,ae=12582912,oe=12;function se(e){return 4*Math.ceil(e/3)}const le=se(V),ce=se(Y),me=se(ee),de=se(te),ue=se(ie),ge=se(re),pe=se(ae);function he(e){return e.replace(/\s+/g,"")}function fe(e){const t=he(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const be=/^image\/(png|jpeg|jpg|webp|gif)$/i,ye=a.object({mimeType:a.string().min(1).refine(e=>be.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:a.string().min(1).max(le).refine(fe,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ve=a.enum(["image","document","spreadsheet"]),we=ye.extend({kind:a.literal("image")}),xe=a.object({kind:a.literal("document"),mimeType:a.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:a.string().min(1).max(me).refine(fe,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),je=a.object({kind:a.literal("spreadsheet"),mimeType:a.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:a.string().min(1).max(ue).refine(fe,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:a.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"]}),ke=a.discriminatedUnion("kind",[we,xe,je]),$e=a.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),Se=a.object({id:a.string().uuid(),uri:a.string(),kind:ve,mimeType:a.string(),filename:a.string().optional(),sizeBytes:a.number().int().positive(),expiresAt:a.string().datetime()}),Ce=a.object({sourceText:a.string().max(X).default(""),images:a.array(ye).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:a.array(ke).max(12).optional(),attachmentRefs:a.array($e).max(12).optional(),metadata:S.optional()}).superRefine((e,t)=>{var n,i,r;const a=e.sourceText.trim(),o=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(i=e.attachments)&&void 0!==i?i:[],l=null!==(r=e.attachmentRefs)&&void 0!==r?r:[];if(o.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(l.length>0&&s.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or inline `attachments`, not both.",path:["attachmentRefs"]});if(l.length>0&&o.length>0)return void t.addIssue({code:"custom",message:"Use either `attachmentRefs` or deprecated `images`, not both.",path:["attachmentRefs"]});if(0===a.length&&0===o.length&&0===s.length&&0===l.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(l.length>0)return;if(o.length>0){o.reduce((e,t)=>e+he(t.dataBase64).length,0)>ce&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let c=0,m=0,d=0,u=0,g=0,p=0,h=0;for(const e of s){const t=he(e.dataBase64).length;switch(h+=t,e.kind){case"image":c+=1,u+=t;break;case"document":m+=1,g+=t;break;case"spreadsheet":d+=1,p+=t}}c>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),d>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=c<=8&&m<=2&&d<=2;s.length>0&&f&&(u>ce&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>de&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>ge&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>pe&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function Te(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:he(e.dataBase64)}}function Re(e){return{kind:"document",mimeType:"application/pdf",dataBase64:he(e.dataBase64)}}function Ee(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:he(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const Ie=a.object({response:a.object({message:a.string()}),config:h,extractMeta:H.nullable(),lastAccuracyEvaluation:J.optional(),run:T.optional()}),Oe=a.object({config:h,response:a.object({message:a.string(),steps:a.array(a.string())}),run:T.optional()}),Ae=M,Pe=a.enum(["deal-breaker","pro","con","family","continuity"]),Ue=a.object({kind:Pe,label:a.string(),weight:a.number(),reason:a.string()}),Be=a.enum(["ok","disqualified"]),Me=a.object({rank:a.number().int().positive(),type:A,score:a.number(),verdict:Be,factors:a.array(Ue)}),Fe=a.object({config:h,chartFamily:E.optional(),metadata:S.optional()}),qe=a.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),De=a.object({kind:qe,message:a.string()}),Ne=a.enum(["sum","avg","count","min","max"]),Ke=a.object({dimensionName:a.string(),dimensionLabel:a.string(),measureName:a.string().nullable(),measureLabel:a.string().nullable(),fn:Ne,chartType:A,score:a.number(),message:a.string()}),Le=a.object({ranking:a.array(Me),observations:a.array(De).optional().default([]),suggestions:a.array(Ke).optional().default([]),run:T.optional()}),Ge=a.object({prompt:a.string(),datasetSummary:a.string().optional(),mustShow:a.array(a.string()).optional(),unacceptable:a.array(a.string()).optional(),acceptableChartFamilies:a.array(a.string()).optional()}),We=a.object({config:h.optional(),chartImage:a.string().optional(),data:a.unknown().optional(),rubric:Ge.optional(),userPrompt:a.string().optional(),metadata:S.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),ze=a.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),_e=a.enum(["info","low","medium","high"]),He=a.object({category:ze,severity:_e,observation:a.string(),rationale:a.string().optional(),suggestedChange:a.string().optional(),configPaths:a.array(a.string()).optional()}),Je=a.object({overallSummary:a.string(),overallSeverity:a.enum(["none","low","medium","high"]).optional(),issues:a.array(He)}),Xe=a.object({dataFidelity:a.number().min(0).max(1),promptRelevance:a.number().min(0).max(1),chartTypeAppropriateness:a.number().min(0).max(1),readability:a.number().min(0).max(1),honesty:a.number().min(0).max(1),composite:a.number().min(0).max(1),rationale:a.string().optional()}),Qe=a.object({capturedAt:a.string(),chartId:a.string()}),Ve=a.object({response:a.object({message:a.string(),steps:a.array(a.string()),critiqueCommitted:a.boolean()}),critiqueReport:Je.nullable(),chartVisionAudit:Qe.nullable().optional().default(null),rubricScores:Xe.nullable().optional().default(null),run:T.optional()}),Ye="/api/v0";class Ze{constructor(e){this.client=new g(e)}generateGraph(t,n,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,a=r(t,["storytellingOptions"]),o=yield this.client.fetch(`${Ye}/generate`,a,n,i),s=Oe.parse(o);return this.stripStorytelling(s,e)})}generateGraphStream(t,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,i=r(t,["storytellingOptions"]),a=yield this.client.stream(`${Ye}/generate`,i,n);return this.wrapStreamWithStorytellingStripping(a,e)})}generateNarrative(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/narrate`,t,n,i);return B.parse(e)})}generateNarrativeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ye}/narrate`,t,n)})}generateSuggestions(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/suggestions`,t,n,i);return M.parse(e)})}generateSuggestionsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ye}/suggestions`,t,n)})}generateExploration(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/explore`,t,n,i);return D.parse(e)})}generateExplorationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ye}/explore`,t,n)})}generateAnnotations(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/annotate`,t,n,i);return N.parse(e)})}generateAnnotationsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ye}/annotate`,t,n)})}generateMutation(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/mutate`,t,n,i);return K.parse(e)})}generateMutationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ye}/mutate`,t,n)})}generatePipeline(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/pipeline`,t,n,i);return z.parse(e)})}generatePipelineStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ye}/pipeline`,t,n)})}evaluate(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/evaluate`,t,void 0,n);return Le.parse(e)})}judge(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/judge`,t,void 0,n);return Ve.parse(e)})}judgeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ye}/judge`,t,n)})}extractFromProse(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ye}/extract`,t,n,i);return Ie.parse(e)})}extractFromProseStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ye}/extract`,t,n)})}uploadAttachment(t,n,i){return e(this,void 0,void 0,function*(){const e=new FormData,r=null==n?void 0:n.filename;"undefined"!=typeof File&&t instanceof File?e.append("file",t):r?e.append("file",t,r):e.append("file",t,"upload"),r&&e.append("filename",r);const a=yield this.client.uploadMultipart(`${Ye}/attachments`,e,i);return Se.parse(a)})}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 n(this,arguments,function*(){var n,a,o,s;try{for(var l,m=!0,d=t(e);!(n=(l=yield i(d.next())).done);m=!0){s=l.value,m=!1;const e=s;if(c(e)){const t=this.stripStorytelling(e.data,r);yield yield i(Object.assign(Object.assign({},e),{data:t}))}else yield yield i(e)}}catch(e){a={error:e}}finally{try{m||n||!(o=d.return)||(yield i(o.call(d)))}finally{if(a)throw a.error}}})}}export{Ne as AggregationFunctionSchema,Ke as AggregationSuggestionSchema,A as AiChartTypeEnum,Se as AttachmentUploadResponseSchema,ze as ChartCritiqueIssueCategorySchema,He as ChartCritiqueIssueSchema,_e as ChartCritiqueIssueSeveritySchema,Je as ChartCritiqueReportSchema,E as ChartFamilySchema,Me as ChartFitEntrySchema,Pe as ChartFitFactorKindSchema,Ue as ChartFitFactorSchema,Be as ChartFitVerdictSchema,Ge as ChartJudgeRubricSchema,qe as DataObservationKindSchema,De as DataObservationSchema,Fe as EvaluateParamsSchema,Le as EvaluateResponseSchema,y as ExecutionModeSchema,F as ExploreFindingSchema,q as ExploreStorySchema,J as ExtractAccuracyEvaluationSchema,ke as ExtractAttachmentInputSchema,ve as ExtractAttachmentKindSchema,_ as ExtractConfidenceSchema,Ce as ExtractFromProseParamsSchema,Ie as ExtractFromProseResponseSchema,H as ExtractMetaSchema,N as GenerateAnnotationsResponseSchema,D as GenerateExplorationResponseSchema,Oe as GenerateGraphResponseSchema,Ae as GenerateGraphSuggestionsResponseSchema,K as GenerateMutationResponseSchema,U as GenerateNarrativeParamsSchema,B as GenerateNarrativeResponseSchema,W as GeneratePipelineParamsSchema,z as GeneratePipelineResponseSchema,O as GenerateSuggestionsParamsSchema,M as GenerateSuggestionsResponseSchema,I as GraphGenerationRequestSchema,Ze as GraphyAiSdk,o as GraphyApiError,j as InvocationBudgetSchema,f as InvocationEffortSchema,We as JudgeParamsSchema,Ve as JudgeResponseSchema,x as MAX_BUDGET_COST_USD,w as MAX_BUDGET_TOTAL_TOKENS,v as MAX_BUDGET_WALL_CLOCK_MS,oe as MAX_EXTRACT_ATTACHMENTS,ae as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,Z as MAX_EXTRACT_DOCUMENTS,te as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,ee as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,Q as MAX_EXTRACT_IMAGES,Y as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,V as MAX_EXTRACT_IMAGE_DECODED_BYTES,ne as MAX_EXTRACT_SPREADSHEETS,re as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,ie as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,X as MAX_SOURCE_TEXT_LENGTH,R as MAX_USER_PROMPT_LENGTH,S as MetadataSchema,C as MutateNarrationReceiptSchema,L as PipelineAgentNameSchema,G as PipelineStageReasoningSchema,Xe as RubricScoresSchema,T as RunContextSchema,b as StorytellingEffortSchema,P as SuggestionSchema,Te as buildImageAttachment,Re as buildPdfAttachment,Ee as buildSpreadsheetAttachment,c as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,d as isPreviewEvent,l as isProgressEvent,u 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.6.2-beta.
|
|
4
|
+
"version": "1.6.2-beta.1782148741262",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"files": [
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
20
|
"zod": "^4.3.6",
|
|
21
|
-
"@graphysdk/core": "1.6.2-beta.
|
|
21
|
+
"@graphysdk/core": "1.6.2-beta.1782148741262"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|