@graphysdk/agents-sdk 1.6.1 → 1.6.2-beta.1782128674332
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 +159 -2
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("zod");class 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=1e4,b=t.z.enum(["comparison","relationship","distribution","composition"]),z=t.z.object({config:c,userPrompt:t.z.string().max(y).optional().default(""),metadata:h.optional(),chartFamily:b.optional()}),x=z.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),v=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),S=t.z.object({dataPrepPrompt:t.z.string(),chartType:v,summary:t.z.string()}),w=z.extend({userPrompt:t.z.string().max(y),mutationReceipt:f.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),_=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),E=t.z.object({suggestions:t.z.array(S)}),T=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:b.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.")}),C=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(T).describe("Child findings, sorted by quadrant score desc.")}),A=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(C)});z.extend({mutationReceipt:f.optional()});const j=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),R=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()}),$=t.z.enum(["explore","mutate","narrate","annotate"]),k=t.z.object({agent:$,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),O=z.extend({userPrompt:t.z.string().max(y),stages:t.z.array($).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),M=R.extend({reasoning:t.z.array(k),stories:t.z.array(C).optional()}),D=t.z.enum(["high","medium","low"]),P=t.z.object({confidence:D,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:D,quote:t.z.string().optional()})).optional()}),I=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()}),G=5e5,B=2097152,U=7340032,F=6291456,X=8388608,N=F,q=X,L=12582912;function K(e){return 4*Math.ceil(e/3)}const H=K(B),W=K(U),Y=K(F),J=K(X),V=K(N),Q=K(q),Z=K(L);function ee(e){return e.replace(/\s+/g,"")}function te(e){const t=ee(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const re=/^image\/(png|jpeg|jpg|webp|gif)$/i,ae=t.z.object({mimeType:t.z.string().min(1).refine(e=>re.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(H).refine(te,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ie=t.z.enum(["image","document","spreadsheet"]),ne=ae.extend({kind:t.z.literal("image")}),oe=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(Y).refine(te,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),se=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(V).refine(te,{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"]}),ce=t.z.discriminatedUnion("kind",[ne,oe,se]),le=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"),me=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),kind:ie,mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().positive(),expiresAt:t.z.string().datetime()}),pe=t.z.object({sourceText:t.z.string().max(G).default(""),images:t.z.array(ae).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(ce).max(12).optional(),attachmentRefs:t.z.array(le).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+ee(t.dataBase64).length,0)>W&&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=ee(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>W&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>J&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>Q&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>Z&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const de=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:P.nullable(),lastAccuracyEvaluation:I.optional()}),ue=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),ge=E,he=t.z.enum(["deal-breaker","pro","con","family","continuity"]),fe=t.z.object({kind:he,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),ye=t.z.enum(["ok","disqualified"]),be=t.z.object({rank:t.z.number().int().positive(),type:v,score:t.z.number(),verdict:ye,factors:t.z.array(fe)}),ze=t.z.object({config:c,chartFamily:b.optional(),metadata:h.optional()}),xe=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"]),ve=t.z.object({kind:xe,message:t.z.string()}),Se=t.z.enum(["sum","avg","count","min","max"]),we=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:Se,chartType:v,score:t.z.number(),message:t.z.string()}),_e=t.z.object({ranking:t.z.array(be),observations:t.z.array(ve).optional().default([]),suggestions:t.z.array(we).optional().default([])}),Ee=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()}),Te=t.z.object({config:c.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:Ee.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."}),Ce=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Ae=t.z.enum(["info","low","medium","high"]),je=t.z.object({category:Ce,severity:Ae,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),Re=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(je)}),$e=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()}),ke=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),Oe=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:Re.nullable(),chartVisionAudit:ke.nullable().optional().default(null),rubricScores:$e.nullable().optional().default(null)}),Me="/api/v0";exports.AggregationFunctionSchema=Se,exports.AggregationSuggestionSchema=we,exports.AiChartTypeEnum=v,exports.AttachmentUploadResponseSchema=me,exports.ChartCritiqueIssueCategorySchema=Ce,exports.ChartCritiqueIssueSchema=je,exports.ChartCritiqueIssueSeveritySchema=Ae,exports.ChartCritiqueReportSchema=Re,exports.ChartFamilySchema=b,exports.ChartFitEntrySchema=be,exports.ChartFitFactorKindSchema=he,exports.ChartFitFactorSchema=fe,exports.ChartFitVerdictSchema=ye,exports.ChartJudgeRubricSchema=Ee,exports.DataObservationKindSchema=xe,exports.DataObservationSchema=ve,exports.EvaluateParamsSchema=ze,exports.EvaluateResponseSchema=_e,exports.ExecutionModeSchema=p,exports.ExploreFindingSchema=T,exports.ExploreStorySchema=C,exports.ExtractAccuracyEvaluationSchema=I,exports.ExtractAttachmentInputSchema=ce,exports.ExtractAttachmentKindSchema=ie,exports.ExtractConfidenceSchema=D,exports.ExtractFromProseParamsSchema=pe,exports.ExtractFromProseResponseSchema=de,exports.ExtractMetaSchema=P,exports.GenerateAnnotationsResponseSchema=j,exports.GenerateExplorationResponseSchema=A,exports.GenerateGraphResponseSchema=ue,exports.GenerateGraphSuggestionsResponseSchema=ge,exports.GenerateMutationResponseSchema=R,exports.GenerateNarrativeParamsSchema=w,exports.GenerateNarrativeResponseSchema=_,exports.GeneratePipelineParamsSchema=O,exports.GeneratePipelineResponseSchema=M,exports.GenerateSuggestionsParamsSchema=x,exports.GenerateSuggestionsResponseSchema=E,exports.GraphGenerationRequestSchema=z,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(`${Me}/generate`,n,r,a),s=ue.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(`${Me}/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(`${Me}/narrate`,t,r,a);return _.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Me}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Me}/suggestions`,t,r,a);return E.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Me}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Me}/explore`,t,r,a);return A.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Me}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Me}/annotate`,t,r,a);return j.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Me}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Me}/mutate`,t,r,a);return R.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Me}/mutate`,t,r)})}generatePipeline(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Me}/pipeline`,t,r,a);return M.parse(e)})}generatePipelineStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Me}/pipeline`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Me}/evaluate`,t,void 0,r);return _e.parse(e)})}judge(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Me}/judge`,t,void 0,r);return Oe.parse(e)})}judgeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Me}/judge`,t,r)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Me}/extract`,t,r,a);return de.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Me}/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(`${Me}/attachments`,e,a);return me.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=Te,exports.JudgeResponseSchema=Oe,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=L,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=X,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=F,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=U,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=B,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=q,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=N,exports.MAX_SOURCE_TEXT_LENGTH=G,exports.MAX_USER_PROMPT_LENGTH=y,exports.MetadataSchema=h,exports.MutateNarrationReceiptSchema=f,exports.PipelineAgentNameSchema=$,exports.PipelineStageReasoningSchema=k,exports.RubricScoresSchema=$e,exports.StorytellingEffortSchema=m,exports.SuggestionSchema=S,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ee(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ee(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ee(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},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()}),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;
|
package/dist/index.d.ts
CHANGED
|
@@ -368,6 +368,13 @@ declare const MutateNarrationReceiptSchema: z.ZodObject<{
|
|
|
368
368
|
}, z.core.$strip>;
|
|
369
369
|
type MutateNarrationReceipt = z.infer<typeof MutateNarrationReceiptSchema>;
|
|
370
370
|
type Metadata = z.infer<typeof MetadataSchema>;
|
|
371
|
+
/** Correlates one agent HTTP request across Langfuse, Grafana Tempo, and feedback. */
|
|
372
|
+
declare const RunContextSchema: z.ZodObject<{
|
|
373
|
+
runId: z.ZodString;
|
|
374
|
+
trackingId: z.ZodString;
|
|
375
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
376
|
+
}, z.core.$strip>;
|
|
377
|
+
type RunContext = z.infer<typeof RunContextSchema>;
|
|
371
378
|
/** Mirrors `MAX_USER_PROMPT_LENGTH` in the agents-api request schema. */
|
|
372
379
|
declare const MAX_USER_PROMPT_LENGTH = 10000;
|
|
373
380
|
/**
|
|
@@ -590,6 +597,11 @@ declare const GenerateNarrativeResponseSchema: z.ZodObject<{
|
|
|
590
597
|
message: z.ZodString;
|
|
591
598
|
}, z.core.$strip>;
|
|
592
599
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
600
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
601
|
+
runId: z.ZodString;
|
|
602
|
+
trackingId: z.ZodString;
|
|
603
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
604
|
+
}, z.core.$strip>>;
|
|
593
605
|
}, z.core.$strip>;
|
|
594
606
|
type GenerateNarrativeResponse = z.infer<typeof GenerateNarrativeResponseSchema>;
|
|
595
607
|
declare const GenerateSuggestionsResponseSchema: z.ZodObject<{
|
|
@@ -619,6 +631,11 @@ declare const GenerateSuggestionsResponseSchema: z.ZodObject<{
|
|
|
619
631
|
}>;
|
|
620
632
|
summary: z.ZodString;
|
|
621
633
|
}, z.core.$strip>>;
|
|
634
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
635
|
+
runId: z.ZodString;
|
|
636
|
+
trackingId: z.ZodString;
|
|
637
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
638
|
+
}, z.core.$strip>>;
|
|
622
639
|
}, z.core.$strip>;
|
|
623
640
|
type GenerateSuggestionsResponse = z.infer<typeof GenerateSuggestionsResponseSchema>;
|
|
624
641
|
type GenerateExplorationParams = GraphGenerationRequest;
|
|
@@ -688,6 +705,11 @@ declare const GenerateExplorationResponseSchema: z.ZodObject<{
|
|
|
688
705
|
evidenceSummary: z.ZodString;
|
|
689
706
|
}, z.core.$strip>>;
|
|
690
707
|
}, z.core.$strip>>;
|
|
708
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
709
|
+
runId: z.ZodString;
|
|
710
|
+
trackingId: z.ZodString;
|
|
711
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
712
|
+
}, z.core.$strip>>;
|
|
691
713
|
}, z.core.$strip>;
|
|
692
714
|
type GenerateExplorationResponse = z.infer<typeof GenerateExplorationResponseSchema>;
|
|
693
715
|
declare const GenerateAnnotationsParamsSchema: z.ZodObject<{
|
|
@@ -760,6 +782,11 @@ declare const GenerateAnnotationsResponseSchema: z.ZodObject<{
|
|
|
760
782
|
steps: z.ZodArray<z.ZodString>;
|
|
761
783
|
}, z.core.$strip>;
|
|
762
784
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
785
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
786
|
+
runId: z.ZodString;
|
|
787
|
+
trackingId: z.ZodString;
|
|
788
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
789
|
+
}, z.core.$strip>>;
|
|
763
790
|
}, z.core.$strip>;
|
|
764
791
|
type GenerateAnnotationsResponse = z.infer<typeof GenerateAnnotationsResponseSchema>;
|
|
765
792
|
type GenerateMutationParams = GraphGenerationRequest;
|
|
@@ -795,6 +822,11 @@ declare const GenerateMutationResponseSchema: z.ZodObject<{
|
|
|
795
822
|
grainSummary: z.ZodOptional<z.ZodString>;
|
|
796
823
|
}, z.core.$strip>>;
|
|
797
824
|
warnings: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
825
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
826
|
+
runId: z.ZodString;
|
|
827
|
+
trackingId: z.ZodString;
|
|
828
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
829
|
+
}, z.core.$strip>>;
|
|
798
830
|
}, z.core.$strip>;
|
|
799
831
|
type GenerateMutationResponse = z.infer<typeof GenerateMutationResponseSchema>;
|
|
800
832
|
declare const PipelineAgentNameSchema: z.ZodEnum<{
|
|
@@ -896,6 +928,11 @@ declare const GeneratePipelineResponseSchema: z.ZodObject<{
|
|
|
896
928
|
grainSummary: z.ZodOptional<z.ZodString>;
|
|
897
929
|
}, z.core.$strip>>;
|
|
898
930
|
warnings: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
931
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
932
|
+
runId: z.ZodString;
|
|
933
|
+
trackingId: z.ZodString;
|
|
934
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
935
|
+
}, z.core.$strip>>;
|
|
899
936
|
reasoning: z.ZodArray<z.ZodObject<{
|
|
900
937
|
agent: z.ZodEnum<{
|
|
901
938
|
explore: "explore";
|
|
@@ -1138,6 +1175,11 @@ declare const ExtractFromProseResponseSchema: z.ZodObject<{
|
|
|
1138
1175
|
sufficient: z.ZodBoolean;
|
|
1139
1176
|
summary: z.ZodString;
|
|
1140
1177
|
}, z.core.$strip>>;
|
|
1178
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
1179
|
+
runId: z.ZodString;
|
|
1180
|
+
trackingId: z.ZodString;
|
|
1181
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
1182
|
+
}, z.core.$strip>>;
|
|
1141
1183
|
}, z.core.$strip>;
|
|
1142
1184
|
type ExtractFromProseResponse = z.infer<typeof ExtractFromProseResponseSchema>;
|
|
1143
1185
|
interface StorytellingOptions {
|
|
@@ -1154,6 +1196,11 @@ declare const GenerateGraphResponseSchema: z.ZodObject<{
|
|
|
1154
1196
|
message: z.ZodString;
|
|
1155
1197
|
steps: z.ZodArray<z.ZodString>;
|
|
1156
1198
|
}, z.core.$strip>;
|
|
1199
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
1200
|
+
runId: z.ZodString;
|
|
1201
|
+
trackingId: z.ZodString;
|
|
1202
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
1203
|
+
}, z.core.$strip>>;
|
|
1157
1204
|
}, z.core.$strip>;
|
|
1158
1205
|
type GenerateGraphResponse = z.infer<typeof GenerateGraphResponseSchema>;
|
|
1159
1206
|
/** @deprecated Use {@link GenerateSuggestionsParams} instead. */
|
|
@@ -1188,6 +1235,11 @@ declare const GenerateGraphSuggestionsResponseSchema: z.ZodObject<{
|
|
|
1188
1235
|
}>;
|
|
1189
1236
|
summary: z.ZodString;
|
|
1190
1237
|
}, z.core.$strip>>;
|
|
1238
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
1239
|
+
runId: z.ZodString;
|
|
1240
|
+
trackingId: z.ZodString;
|
|
1241
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
1242
|
+
}, z.core.$strip>>;
|
|
1191
1243
|
}, z.core.$strip>;
|
|
1192
1244
|
/** Kind of factor that contributed to a chart-type's score. Mirrors `Factor.kind` in agents-api. */
|
|
1193
1245
|
declare const ChartFitFactorKindSchema: z.ZodEnum<{
|
|
@@ -1503,6 +1555,11 @@ declare const EvaluateResponseSchema: z.ZodObject<{
|
|
|
1503
1555
|
score: z.ZodNumber;
|
|
1504
1556
|
message: z.ZodString;
|
|
1505
1557
|
}, z.core.$strip>>>>;
|
|
1558
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
1559
|
+
runId: z.ZodString;
|
|
1560
|
+
trackingId: z.ZodString;
|
|
1561
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
1562
|
+
}, z.core.$strip>>;
|
|
1506
1563
|
}, z.core.$strip>;
|
|
1507
1564
|
type EvaluateResponse = z.infer<typeof EvaluateResponseSchema>;
|
|
1508
1565
|
/** Optional benchmark rubric. When present, the judge also returns {@link RubricScores}. */
|
|
@@ -1702,6 +1759,11 @@ declare const JudgeResponseSchema: z.ZodObject<{
|
|
|
1702
1759
|
composite: z.ZodNumber;
|
|
1703
1760
|
rationale: z.ZodOptional<z.ZodString>;
|
|
1704
1761
|
}, z.core.$strip>>>>;
|
|
1762
|
+
run: z.ZodOptional<z.ZodObject<{
|
|
1763
|
+
runId: z.ZodString;
|
|
1764
|
+
trackingId: z.ZodString;
|
|
1765
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
1766
|
+
}, z.core.$strip>>;
|
|
1705
1767
|
}, z.core.$strip>;
|
|
1706
1768
|
type JudgeResponse = z.infer<typeof JudgeResponseSchema>;
|
|
1707
1769
|
|
|
@@ -1748,6 +1810,11 @@ declare class GraphyAiSdk {
|
|
|
1748
1810
|
message: string;
|
|
1749
1811
|
steps: string[];
|
|
1750
1812
|
};
|
|
1813
|
+
run?: {
|
|
1814
|
+
runId: string;
|
|
1815
|
+
trackingId: string;
|
|
1816
|
+
callId?: string | undefined;
|
|
1817
|
+
} | undefined;
|
|
1751
1818
|
}>;
|
|
1752
1819
|
/**
|
|
1753
1820
|
* Streams chart generation events via SSE.
|
|
@@ -1763,6 +1830,11 @@ declare class GraphyAiSdk {
|
|
|
1763
1830
|
message: string;
|
|
1764
1831
|
steps: string[];
|
|
1765
1832
|
};
|
|
1833
|
+
run?: {
|
|
1834
|
+
runId: string;
|
|
1835
|
+
trackingId: string;
|
|
1836
|
+
callId?: string | undefined;
|
|
1837
|
+
} | undefined;
|
|
1766
1838
|
}>>>;
|
|
1767
1839
|
/**
|
|
1768
1840
|
* Generates a narrative for a chart. The agent updates `config.content.title`,
|
|
@@ -1780,6 +1852,11 @@ declare class GraphyAiSdk {
|
|
|
1780
1852
|
message: string;
|
|
1781
1853
|
};
|
|
1782
1854
|
config: _graphysdk_core_node.GraphConfig;
|
|
1855
|
+
run?: {
|
|
1856
|
+
runId: string;
|
|
1857
|
+
trackingId: string;
|
|
1858
|
+
callId?: string | undefined;
|
|
1859
|
+
} | undefined;
|
|
1783
1860
|
}>;
|
|
1784
1861
|
/**
|
|
1785
1862
|
* Streams narrative generation events via SSE.
|
|
@@ -1794,6 +1871,11 @@ declare class GraphyAiSdk {
|
|
|
1794
1871
|
message: string;
|
|
1795
1872
|
};
|
|
1796
1873
|
config: _graphysdk_core_node.GraphConfig;
|
|
1874
|
+
run?: {
|
|
1875
|
+
runId: string;
|
|
1876
|
+
trackingId: string;
|
|
1877
|
+
callId?: string | undefined;
|
|
1878
|
+
} | undefined;
|
|
1797
1879
|
}>>>;
|
|
1798
1880
|
/**
|
|
1799
1881
|
* Generates chart type and prompt suggestions for a given chart configuration.
|
|
@@ -1810,6 +1892,11 @@ declare class GraphyAiSdk {
|
|
|
1810
1892
|
chartType: "line" | "areaStacked" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table" | "mekko";
|
|
1811
1893
|
summary: string;
|
|
1812
1894
|
}[];
|
|
1895
|
+
run?: {
|
|
1896
|
+
runId: string;
|
|
1897
|
+
trackingId: string;
|
|
1898
|
+
callId?: string | undefined;
|
|
1899
|
+
} | undefined;
|
|
1813
1900
|
}>;
|
|
1814
1901
|
/**
|
|
1815
1902
|
* Streams suggestion generation events via SSE.
|
|
@@ -1825,6 +1912,11 @@ declare class GraphyAiSdk {
|
|
|
1825
1912
|
chartType: "line" | "areaStacked" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "bubble" | "waterfall" | "table" | "mekko";
|
|
1826
1913
|
summary: string;
|
|
1827
1914
|
}[];
|
|
1915
|
+
run?: {
|
|
1916
|
+
runId: string;
|
|
1917
|
+
trackingId: string;
|
|
1918
|
+
callId?: string | undefined;
|
|
1919
|
+
} | undefined;
|
|
1828
1920
|
}>>>;
|
|
1829
1921
|
/**
|
|
1830
1922
|
* Runs the exploration agent against a chart's dataset.
|
|
@@ -1854,6 +1946,11 @@ declare class GraphyAiSdk {
|
|
|
1854
1946
|
evidenceSummary: string;
|
|
1855
1947
|
}[];
|
|
1856
1948
|
}[];
|
|
1949
|
+
run?: {
|
|
1950
|
+
runId: string;
|
|
1951
|
+
trackingId: string;
|
|
1952
|
+
callId?: string | undefined;
|
|
1953
|
+
} | undefined;
|
|
1857
1954
|
}>;
|
|
1858
1955
|
/**
|
|
1859
1956
|
* Streams exploration agent events via SSE.
|
|
@@ -1882,6 +1979,11 @@ declare class GraphyAiSdk {
|
|
|
1882
1979
|
evidenceSummary: string;
|
|
1883
1980
|
}[];
|
|
1884
1981
|
}[];
|
|
1982
|
+
run?: {
|
|
1983
|
+
runId: string;
|
|
1984
|
+
trackingId: string;
|
|
1985
|
+
callId?: string | undefined;
|
|
1986
|
+
} | undefined;
|
|
1885
1987
|
}>>>;
|
|
1886
1988
|
/**
|
|
1887
1989
|
* Runs the annotation-tools agent to add annotations to a chart.
|
|
@@ -1898,6 +2000,11 @@ declare class GraphyAiSdk {
|
|
|
1898
2000
|
steps: string[];
|
|
1899
2001
|
};
|
|
1900
2002
|
config: _graphysdk_core_node.GraphConfig;
|
|
2003
|
+
run?: {
|
|
2004
|
+
runId: string;
|
|
2005
|
+
trackingId: string;
|
|
2006
|
+
callId?: string | undefined;
|
|
2007
|
+
} | undefined;
|
|
1901
2008
|
}>;
|
|
1902
2009
|
/**
|
|
1903
2010
|
* Streams annotation-tools agent events via SSE.
|
|
@@ -1913,6 +2020,11 @@ declare class GraphyAiSdk {
|
|
|
1913
2020
|
steps: string[];
|
|
1914
2021
|
};
|
|
1915
2022
|
config: _graphysdk_core_node.GraphConfig;
|
|
2023
|
+
run?: {
|
|
2024
|
+
runId: string;
|
|
2025
|
+
trackingId: string;
|
|
2026
|
+
callId?: string | undefined;
|
|
2027
|
+
} | undefined;
|
|
1916
2028
|
}>>>;
|
|
1917
2029
|
/**
|
|
1918
2030
|
* Runs the mutate agent to apply dataset transformations (filter, select, derive,
|
|
@@ -1948,6 +2060,11 @@ declare class GraphyAiSdk {
|
|
|
1948
2060
|
grainSummary?: string | undefined;
|
|
1949
2061
|
} | undefined;
|
|
1950
2062
|
warnings?: string[] | undefined;
|
|
2063
|
+
run?: {
|
|
2064
|
+
runId: string;
|
|
2065
|
+
trackingId: string;
|
|
2066
|
+
callId?: string | undefined;
|
|
2067
|
+
} | undefined;
|
|
1951
2068
|
}>;
|
|
1952
2069
|
/**
|
|
1953
2070
|
* Streams mutate agent events via SSE.
|
|
@@ -1980,6 +2097,11 @@ declare class GraphyAiSdk {
|
|
|
1980
2097
|
grainSummary?: string | undefined;
|
|
1981
2098
|
} | undefined;
|
|
1982
2099
|
warnings?: string[] | undefined;
|
|
2100
|
+
run?: {
|
|
2101
|
+
runId: string;
|
|
2102
|
+
trackingId: string;
|
|
2103
|
+
callId?: string | undefined;
|
|
2104
|
+
} | undefined;
|
|
1983
2105
|
}>>>;
|
|
1984
2106
|
/**
|
|
1985
2107
|
* Runs an ordered agent pipeline (`POST /v0/pipeline`) on one shared server session.
|
|
@@ -2013,6 +2135,11 @@ declare class GraphyAiSdk {
|
|
|
2013
2135
|
grainSummary?: string | undefined;
|
|
2014
2136
|
} | undefined;
|
|
2015
2137
|
warnings?: string[] | undefined;
|
|
2138
|
+
run?: {
|
|
2139
|
+
runId: string;
|
|
2140
|
+
trackingId: string;
|
|
2141
|
+
callId?: string | undefined;
|
|
2142
|
+
} | undefined;
|
|
2016
2143
|
stories?: {
|
|
2017
2144
|
topic: string;
|
|
2018
2145
|
score: number;
|
|
@@ -2056,6 +2183,11 @@ declare class GraphyAiSdk {
|
|
|
2056
2183
|
grainSummary?: string | undefined;
|
|
2057
2184
|
} | undefined;
|
|
2058
2185
|
warnings?: string[] | undefined;
|
|
2186
|
+
run?: {
|
|
2187
|
+
runId: string;
|
|
2188
|
+
trackingId: string;
|
|
2189
|
+
callId?: string | undefined;
|
|
2190
|
+
} | undefined;
|
|
2059
2191
|
stories?: {
|
|
2060
2192
|
topic: string;
|
|
2061
2193
|
score: number;
|
|
@@ -2118,6 +2250,11 @@ declare class GraphyAiSdk {
|
|
|
2118
2250
|
score: number;
|
|
2119
2251
|
message: string;
|
|
2120
2252
|
}[];
|
|
2253
|
+
run?: {
|
|
2254
|
+
runId: string;
|
|
2255
|
+
trackingId: string;
|
|
2256
|
+
callId?: string | undefined;
|
|
2257
|
+
} | undefined;
|
|
2121
2258
|
}>;
|
|
2122
2259
|
/**
|
|
2123
2260
|
* Runs the chart judge on a chart and returns a structured critique. The judge is config-optional:
|
|
@@ -2167,6 +2304,11 @@ declare class GraphyAiSdk {
|
|
|
2167
2304
|
composite: number;
|
|
2168
2305
|
rationale?: string | undefined;
|
|
2169
2306
|
} | null;
|
|
2307
|
+
run?: {
|
|
2308
|
+
runId: string;
|
|
2309
|
+
trackingId: string;
|
|
2310
|
+
callId?: string | undefined;
|
|
2311
|
+
} | undefined;
|
|
2170
2312
|
}>;
|
|
2171
2313
|
/**
|
|
2172
2314
|
* Streams chart-judge events via SSE. See {@link judge} for the request shape and semantics.
|
|
@@ -2207,6 +2349,11 @@ declare class GraphyAiSdk {
|
|
|
2207
2349
|
composite: number;
|
|
2208
2350
|
rationale?: string | undefined;
|
|
2209
2351
|
} | null;
|
|
2352
|
+
run?: {
|
|
2353
|
+
runId: string;
|
|
2354
|
+
trackingId: string;
|
|
2355
|
+
callId?: string | undefined;
|
|
2356
|
+
} | undefined;
|
|
2210
2357
|
}>>>;
|
|
2211
2358
|
/**
|
|
2212
2359
|
* Runs the extract agent to build a chart-ready dataset from unstructured prose, images, and/or PDFs.
|
|
@@ -2243,6 +2390,11 @@ declare class GraphyAiSdk {
|
|
|
2243
2390
|
sufficient: boolean;
|
|
2244
2391
|
summary: string;
|
|
2245
2392
|
} | undefined;
|
|
2393
|
+
run?: {
|
|
2394
|
+
runId: string;
|
|
2395
|
+
trackingId: string;
|
|
2396
|
+
callId?: string | undefined;
|
|
2397
|
+
} | undefined;
|
|
2246
2398
|
}>;
|
|
2247
2399
|
/**
|
|
2248
2400
|
* Streams extract-agent events via SSE.
|
|
@@ -2278,6 +2430,11 @@ declare class GraphyAiSdk {
|
|
|
2278
2430
|
sufficient: boolean;
|
|
2279
2431
|
summary: string;
|
|
2280
2432
|
} | undefined;
|
|
2433
|
+
run?: {
|
|
2434
|
+
runId: string;
|
|
2435
|
+
trackingId: string;
|
|
2436
|
+
callId?: string | undefined;
|
|
2437
|
+
} | undefined;
|
|
2281
2438
|
}>>>;
|
|
2282
2439
|
/**
|
|
2283
2440
|
* Uploads a file to the staged attachment store (`POST /v0/attachments`).
|
|
@@ -2294,5 +2451,5 @@ declare class GraphyAiSdk {
|
|
|
2294
2451
|
private wrapStreamWithStorytellingStripping;
|
|
2295
2452
|
}
|
|
2296
2453
|
|
|
2297
|
-
export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, AttachmentUploadResponseSchema, ChartCritiqueIssueCategorySchema, ChartCritiqueIssueSchema, ChartCritiqueIssueSeveritySchema, ChartCritiqueReportSchema, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, ChartJudgeRubricSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeParamsSchema, GenerateNarrativeResponseSchema, GeneratePipelineParamsSchema, GeneratePipelineResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, JudgeParamsSchema, JudgeResponseSchema, MAX_BUDGET_COST_USD, MAX_BUDGET_TOTAL_TOKENS, MAX_BUDGET_WALL_CLOCK_MS, MAX_EXTRACT_ATTACHMENTS, MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES, MAX_EXTRACT_DOCUMENTS, MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES, MAX_EXTRACT_DOCUMENT_DECODED_BYTES, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, MutateNarrationReceiptSchema, PipelineAgentNameSchema, PipelineStageReasoningSchema, RubricScoresSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
|
|
2298
|
-
export type { AggregationFunction, AggregationSuggestion, AiChartType, AttachmentUploadResponse, ChartCritiqueIssue, ChartCritiqueIssueCategory, ChartCritiqueIssueSeverity, ChartCritiqueReport, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, ChartJudgeRubric, ClientConfig, CompleteEvent, DataObservation, DataObservationKind, ErrorEvent, EvaluateParams, EvaluateResponse, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GeneratePipelineParams, GeneratePipelineResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, JudgeParams, JudgeResponse, Logger, Metadata, MutateNarrationReceipt, PipelineAgentName, PipelineStageReasoning, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, RubricScores, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
|
|
2454
|
+
export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, AttachmentUploadResponseSchema, ChartCritiqueIssueCategorySchema, ChartCritiqueIssueSchema, ChartCritiqueIssueSeveritySchema, ChartCritiqueReportSchema, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, ChartJudgeRubricSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeParamsSchema, GenerateNarrativeResponseSchema, GeneratePipelineParamsSchema, GeneratePipelineResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, JudgeParamsSchema, JudgeResponseSchema, MAX_BUDGET_COST_USD, MAX_BUDGET_TOTAL_TOKENS, MAX_BUDGET_WALL_CLOCK_MS, MAX_EXTRACT_ATTACHMENTS, MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES, MAX_EXTRACT_DOCUMENTS, MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES, MAX_EXTRACT_DOCUMENT_DECODED_BYTES, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, MutateNarrationReceiptSchema, PipelineAgentNameSchema, PipelineStageReasoningSchema, RubricScoresSchema, RunContextSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
|
|
2455
|
+
export type { AggregationFunction, AggregationSuggestion, AiChartType, AttachmentUploadResponse, ChartCritiqueIssue, ChartCritiqueIssueCategory, ChartCritiqueIssueSeverity, ChartCritiqueReport, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, ChartJudgeRubric, ClientConfig, CompleteEvent, DataObservation, DataObservationKind, ErrorEvent, EvaluateParams, EvaluateResponse, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractAttachmentInput, ExtractAttachmentKind, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractImageInput, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GeneratePipelineParams, GeneratePipelineResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, JudgeParams, JudgeResponse, Logger, Metadata, MutateNarrationReceipt, PipelineAgentName, PipelineStageReasoning, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, RubricScores, RunContext, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e,__asyncValues as t,__asyncGenerator as i,__await as n,__rest as r}from"tslib";import{z as 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,c=e=>"progress"===e.type,l=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 c(e)}static isCompleteEvent(e){return l(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(c(e)&&r&&r(e),l(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 c=r.split(/\r?\n/);r=c.pop()||"";for(const e of c)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,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();i&&i.addEventListener("abort",l);try{const c=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(!c.ok){let a,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&&(a=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===a)&&(c.status>=500||429===c.status),m=new o(s,{status:c.status,code:a,retryable:l});if(l&&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} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}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(c),i&&i.removeEventListener("abort",l)}})}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),c=()=>a.abort();i&&i.addEventListener("abort",c);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 c=s.status>=500||429===s.status,l=new o(a,{status:s.status,code:r,retryable:c});if(c&&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 l}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",c)}})}}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=1e4,C=a.enum(["comparison","relationship","distribution","composition"]),R=a.object({config:h,userPrompt:a.string().max(S).optional().default(""),metadata:$.optional(),chartFamily:C.optional()}),T=R.extend({maxSuggestionCount:a.number().int().min(1).max(4).optional()}),E=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:E,summary:a.string()}),I=R.extend({userPrompt:a.string().max(S),mutationReceipt:k.optional(),exploreFindingSummary:a.string().max(500).optional()}),A=a.object({response:a.object({message:a.string()}),config:h}),P=a.object({suggestions:a.array(O)}),U=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:C.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.")}),B=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(U).describe("Child findings, sorted by quadrant score desc.")}),F=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),stories:a.array(B)});R.extend({mutationReceipt:k.optional()});const q=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h}),M=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,mutationReceipt:k.optional(),warnings:a.array(a.string()).optional()}),D=a.enum(["explore","mutate","narrate","annotate"]),N=a.object({agent:D,summary:a.string(),steps:a.array(a.string()).optional()}),K=R.extend({userPrompt:a.string().max(S),stages:a.array(D).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:a.string().max(500).optional()}),L=M.extend({reasoning:a.array(N),stories:a.array(B).optional()}),G=a.enum(["high","medium","low"]),W=a.object({confidence:G,needsUserInput:a.boolean(),warnings:a.array(a.string()),cellConfidence:a.array(a.object({rowIndex:a.number().int().nonnegative(),columnKey:a.string(),confidence:G,quote:a.string().optional()})).optional()}),z=a.object({score:a.number().min(0).max(1),issues:a.array(a.string()),sufficient:a.boolean(),summary:a.string()}),_=5e5,H=8,J=2097152,X=7340032,Q=2,V=6291456,Y=8388608,Z=2,ee=V,te=Y,ie=12582912,ne=12;function re(e){return 4*Math.ceil(e/3)}const ae=re(J),oe=re(X),se=re(V),ce=re(Y),le=re(ee),me=re(te),de=re(ie);function ue(e){return e.replace(/\s+/g,"")}function ge(e){const t=ue(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const pe=/^image\/(png|jpeg|jpg|webp|gif)$/i,he=a.object({mimeType:a.string().min(1).refine(e=>pe.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:a.string().min(1).max(ae).refine(ge,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),fe=a.enum(["image","document","spreadsheet"]),ye=he.extend({kind:a.literal("image")}),be=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(se).refine(ge,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ve=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(le).refine(ge,{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"]}),we=a.discriminatedUnion("kind",[ye,be,ve]),xe=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"),je=a.object({id:a.string().uuid(),uri:a.string(),kind:fe,mimeType:a.string(),filename:a.string().optional(),sizeBytes:a.number().int().positive(),expiresAt:a.string().datetime()}),$e=a.object({sourceText:a.string().max(_).default(""),images:a.array(he).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:a.array(we).max(12).optional(),attachmentRefs:a.array(xe).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:[],c=null!==(r=e.attachmentRefs)&&void 0!==r?r:[];if(o.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(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===a.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+ue(t.dataBase64).length,0)>oe&&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,d=0,u=0,g=0,p=0,h=0;for(const e of s){const t=ue(e.dataBase64).length;switch(h+=t,e.kind){case"image":l+=1,u+=t;break;case"document":m+=1,g+=t;break;case"spreadsheet":d+=1,p+=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"]}),d>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&d<=2;s.length>0&&f&&(u>oe&&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>me&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>de&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function ke(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ue(e.dataBase64)}}function Se(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ue(e.dataBase64)}}function Ce(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ue(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const Re=a.object({response:a.object({message:a.string()}),config:h,extractMeta:W.nullable(),lastAccuracyEvaluation:z.optional()}),Te=a.object({config:h,response:a.object({message:a.string(),steps:a.array(a.string())})}),Ee=P,Oe=a.enum(["deal-breaker","pro","con","family","continuity"]),Ie=a.object({kind:Oe,label:a.string(),weight:a.number(),reason:a.string()}),Ae=a.enum(["ok","disqualified"]),Pe=a.object({rank:a.number().int().positive(),type:E,score:a.number(),verdict:Ae,factors:a.array(Ie)}),Ue=a.object({config:h,chartFamily:C.optional(),metadata:$.optional()}),Be=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"]),Fe=a.object({kind:Be,message:a.string()}),qe=a.enum(["sum","avg","count","min","max"]),Me=a.object({dimensionName:a.string(),dimensionLabel:a.string(),measureName:a.string().nullable(),measureLabel:a.string().nullable(),fn:qe,chartType:E,score:a.number(),message:a.string()}),De=a.object({ranking:a.array(Pe),observations:a.array(Fe).optional().default([]),suggestions:a.array(Me).optional().default([])}),Ne=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()}),Ke=a.object({config:h.optional(),chartImage:a.string().optional(),data:a.unknown().optional(),rubric:Ne.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."}),Le=a.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Ge=a.enum(["info","low","medium","high"]),We=a.object({category:Le,severity:Ge,observation:a.string(),rationale:a.string().optional(),suggestedChange:a.string().optional(),configPaths:a.array(a.string()).optional()}),ze=a.object({overallSummary:a.string(),overallSeverity:a.enum(["none","low","medium","high"]).optional(),issues:a.array(We)}),_e=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()}),He=a.object({capturedAt:a.string(),chartId:a.string()}),Je=a.object({response:a.object({message:a.string(),steps:a.array(a.string()),critiqueCommitted:a.boolean()}),critiqueReport:ze.nullable(),chartVisionAudit:He.nullable().optional().default(null),rubricScores:_e.nullable().optional().default(null)}),Xe="/api/v0";class Qe{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(`${Xe}/generate`,a,i,n),s=Te.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(`${Xe}/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(`${Xe}/narrate`,t,i,n);return A.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Xe}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Xe}/suggestions`,t,i,n);return P.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Xe}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Xe}/explore`,t,i,n);return F.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Xe}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Xe}/annotate`,t,i,n);return q.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Xe}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Xe}/mutate`,t,i,n);return M.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Xe}/mutate`,t,i)})}generatePipeline(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Xe}/pipeline`,t,i,n);return L.parse(e)})}generatePipelineStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Xe}/pipeline`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Xe}/evaluate`,t,void 0,i);return De.parse(e)})}judge(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Xe}/judge`,t,void 0,i);return Je.parse(e)})}judgeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Xe}/judge`,t,i)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Xe}/extract`,t,i,n);return Re.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Xe}/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(`${Xe}/attachments`,e,n);return je.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 c,m=!0,d=t(e);!(i=(c=yield n(d.next())).done);m=!0){s=c.value,m=!1;const e=s;if(l(e)){const t=this.stripStorytelling(e.data,r);yield yield n(Object.assign(Object.assign({},e),{data:t}))}else yield yield n(e)}}catch(e){a={error:e}}finally{try{m||i||!(o=d.return)||(yield n(o.call(d)))}finally{if(a)throw a.error}}})}}export{qe as AggregationFunctionSchema,Me as AggregationSuggestionSchema,E as AiChartTypeEnum,je as AttachmentUploadResponseSchema,Le as ChartCritiqueIssueCategorySchema,We as ChartCritiqueIssueSchema,Ge as ChartCritiqueIssueSeveritySchema,ze as ChartCritiqueReportSchema,C as ChartFamilySchema,Pe as ChartFitEntrySchema,Oe as ChartFitFactorKindSchema,Ie as ChartFitFactorSchema,Ae as ChartFitVerdictSchema,Ne as ChartJudgeRubricSchema,Be as DataObservationKindSchema,Fe as DataObservationSchema,Ue as EvaluateParamsSchema,De as EvaluateResponseSchema,b as ExecutionModeSchema,U as ExploreFindingSchema,B as ExploreStorySchema,z as ExtractAccuracyEvaluationSchema,we as ExtractAttachmentInputSchema,fe as ExtractAttachmentKindSchema,G as ExtractConfidenceSchema,$e as ExtractFromProseParamsSchema,Re as ExtractFromProseResponseSchema,W as ExtractMetaSchema,q as GenerateAnnotationsResponseSchema,F as GenerateExplorationResponseSchema,Te as GenerateGraphResponseSchema,Ee as GenerateGraphSuggestionsResponseSchema,M as GenerateMutationResponseSchema,I as GenerateNarrativeParamsSchema,A as GenerateNarrativeResponseSchema,K as GeneratePipelineParamsSchema,L as GeneratePipelineResponseSchema,T as GenerateSuggestionsParamsSchema,P as GenerateSuggestionsResponseSchema,R as GraphGenerationRequestSchema,Qe as GraphyAiSdk,o as GraphyApiError,j as InvocationBudgetSchema,f as InvocationEffortSchema,Ke as JudgeParamsSchema,Je as JudgeResponseSchema,x as MAX_BUDGET_COST_USD,w as MAX_BUDGET_TOTAL_TOKENS,v as MAX_BUDGET_WALL_CLOCK_MS,ne as MAX_EXTRACT_ATTACHMENTS,ie as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,Q as MAX_EXTRACT_DOCUMENTS,Y as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,V as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,H as MAX_EXTRACT_IMAGES,X as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,J as MAX_EXTRACT_IMAGE_DECODED_BYTES,Z as MAX_EXTRACT_SPREADSHEETS,te as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,ee as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,_ as MAX_SOURCE_TEXT_LENGTH,S as MAX_USER_PROMPT_LENGTH,$ as MetadataSchema,k as MutateNarrationReceiptSchema,D as PipelineAgentNameSchema,N as PipelineStageReasoningSchema,_e as RubricScoresSchema,y as StorytellingEffortSchema,O as SuggestionSchema,ke as buildImageAttachment,Se as buildPdfAttachment,Ce as buildSpreadsheetAttachment,l as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,d as isPreviewEvent,c as isProgressEvent,u as isReasoningEvent};
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@graphysdk/agents-sdk",
|
|
3
3
|
"author": "Graphy",
|
|
4
|
-
"version": "1.6.
|
|
4
|
+
"version": "1.6.2-beta.1782128674332",
|
|
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.
|
|
21
|
+
"@graphysdk/core": "1.6.2-beta.1782128674332"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|