@graphysdk/agents-sdk 1.6.1-beta.1781110873995 → 1.6.1
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 +28 -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 m,l,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));!(m=(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){l={error:e}}finally{try{f||m||!(p=y.return)||(yield p.call(y))}finally{if(l)throw l.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}}})}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),m=()=>s.abort();a&&a.addEventListener("abort",m);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 m=!("QUOTA_EXCEEDED"===o)&&(c.status>=500||429===c.status),l=new r(s,{status:c.status,code:o,retryable:m});if(m&&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}`),l}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",m)}})}}const s=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),m=t.z.enum(["low","medium","high"]),l=t.z.enum(["none","low","medium","high"]),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:m.optional(),storytellingEffort:l.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()}),_=z.extend({userPrompt:t.z.string().max(y),mutationReceipt:f.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),w=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.")}),j=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 A=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"]),O=t.z.object({agent:$,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),k=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()}),D=R.extend({reasoning:t.z.array(O),stories:t.z.array(C).optional()}),P=t.z.enum(["high","medium","low"]),M=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()}),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,X=7340032,F=6291456,N=8388608,U=F,q=N,L=12582912;function K(e){return 4*Math.ceil(e/3)}const H=K(B),W=K(X),Y=K(F),J=K(N),V=K(U),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]),me=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(),metadata:h.optional()}).superRefine((e,t)=>{var r,a;const i=e.sourceText.trim(),n=null!==(r=e.images)&&void 0!==r?r:[],o=null!==(a=e.attachments)&&void 0!==a?a:[];if(n.length>0&&o.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===i.length&&0===n.length&&0===o.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(n.length>0){n.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 s=0,c=0,m=0,l=0,p=0,d=0,u=0;for(const e of o){const t=ee(e.dataBase64).length;switch(u+=t,e.kind){case"image":s+=1,l+=t;break;case"document":c+=1,p+=t;break;case"spreadsheet":m+=1,d+=t}}s>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const g=s<=8&&c<=2&&m<=2;o.length>0&&g&&(l>W&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>J&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>Q&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>Z&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const le=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:M.nullable(),lastAccuracyEvaluation:I.optional()}),pe=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),de=E,ue=t.z.enum(["deal-breaker","pro","con","family","continuity"]),ge=t.z.object({kind:ue,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),he=t.z.enum(["ok","disqualified"]),fe=t.z.object({rank:t.z.number().int().positive(),type:v,score:t.z.number(),verdict:he,factors:t.z.array(ge)}),ye=t.z.object({config:c,chartFamily:b.optional(),metadata:h.optional()}),be=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"]),ze=t.z.object({kind:be,message:t.z.string()}),xe=t.z.enum(["sum","avg","count","min","max"]),ve=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:xe,chartType:v,score:t.z.number(),message:t.z.string()}),Se=t.z.object({ranking:t.z.array(fe),observations:t.z.array(ze).optional().default([]),suggestions:t.z.array(ve).optional().default([])}),_e=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),we=t.z.object({config:c.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:_e.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."}),Ee=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Te=t.z.enum(["info","low","medium","high"]),Ce=t.z.object({category:Ee,severity:Te,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),je=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Ce)}),Ae=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()}),Re=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),$e=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:je.nullable(),chartVisionAudit:Re.nullable().optional().default(null),rubricScores:Ae.nullable().optional().default(null)}),Oe="/api/v0";exports.AggregationFunctionSchema=xe,exports.AggregationSuggestionSchema=ve,exports.AiChartTypeEnum=v,exports.ChartCritiqueIssueCategorySchema=Ee,exports.ChartCritiqueIssueSchema=Ce,exports.ChartCritiqueIssueSeveritySchema=Te,exports.ChartCritiqueReportSchema=je,exports.ChartFamilySchema=b,exports.ChartFitEntrySchema=fe,exports.ChartFitFactorKindSchema=ue,exports.ChartFitFactorSchema=ge,exports.ChartFitVerdictSchema=he,exports.ChartJudgeRubricSchema=_e,exports.DataObservationKindSchema=be,exports.DataObservationSchema=ze,exports.EvaluateParamsSchema=ye,exports.EvaluateResponseSchema=Se,exports.ExecutionModeSchema=p,exports.ExploreFindingSchema=T,exports.ExploreStorySchema=C,exports.ExtractAccuracyEvaluationSchema=I,exports.ExtractAttachmentInputSchema=ce,exports.ExtractAttachmentKindSchema=ie,exports.ExtractConfidenceSchema=P,exports.ExtractFromProseParamsSchema=me,exports.ExtractFromProseResponseSchema=le,exports.ExtractMetaSchema=M,exports.GenerateAnnotationsResponseSchema=A,exports.GenerateExplorationResponseSchema=j,exports.GenerateGraphResponseSchema=pe,exports.GenerateGraphSuggestionsResponseSchema=de,exports.GenerateMutationResponseSchema=R,exports.GenerateNarrativeParamsSchema=_,exports.GenerateNarrativeResponseSchema=w,exports.GeneratePipelineParamsSchema=k,exports.GeneratePipelineResponseSchema=D,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(`${Oe}/generate`,n,r,a),s=pe.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(`${Oe}/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(`${Oe}/narrate`,t,r,a);return w.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/suggestions`,t,r,a);return E.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/explore`,t,r,a);return j.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/annotate`,t,r,a);return A.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/mutate`,t,r,a);return R.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/mutate`,t,r)})}generatePipeline(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/pipeline`,t,r,a);return D.parse(e)})}generatePipelineStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/pipeline`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/evaluate`,t,void 0,r);return Se.parse(e)})}judge(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/judge`,t,void 0,r);return $e.parse(e)})}judgeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/judge`,t,r)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/extract`,t,r,a);return le.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/extract`,t,r)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,r){return e.__asyncGenerator(this,arguments,function*(){var a,n,o,s;try{for(var c,m=!0,l=e.__asyncValues(t);!(a=(c=yield e.__await(l.next())).done);m=!0){s=c.value,m=!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{m||a||!(o=l.return)||(yield e.__await(o.call(l)))}finally{if(n)throw n.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.InvocationEffortSchema=m,exports.JudgeParamsSchema=we,exports.JudgeResponseSchema=$e,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=N,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=F,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=X,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=U,exports.MAX_SOURCE_TEXT_LENGTH=G,exports.MAX_USER_PROMPT_LENGTH=y,exports.MetadataSchema=h,exports.MutateNarrationReceiptSchema=f,exports.PipelineAgentNameSchema=$,exports.PipelineStageReasoningSchema=O,exports.RubricScoresSchema=Ae,exports.StorytellingEffortSchema=l,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=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;
|
package/dist/index.d.ts
CHANGED
|
@@ -1008,6 +1008,20 @@ declare const ExtractAttachmentInputSchema: z.ZodDiscriminatedUnion<[z.ZodObject
|
|
|
1008
1008
|
filename: z.ZodOptional<z.ZodString>;
|
|
1009
1009
|
}, z.core.$strip>], "kind">;
|
|
1010
1010
|
type ExtractAttachmentInput = z.infer<typeof ExtractAttachmentInputSchema>;
|
|
1011
|
+
declare const AttachmentUploadResponseSchema: z.ZodObject<{
|
|
1012
|
+
id: z.ZodString;
|
|
1013
|
+
uri: z.ZodString;
|
|
1014
|
+
kind: z.ZodEnum<{
|
|
1015
|
+
image: "image";
|
|
1016
|
+
document: "document";
|
|
1017
|
+
spreadsheet: "spreadsheet";
|
|
1018
|
+
}>;
|
|
1019
|
+
mimeType: z.ZodString;
|
|
1020
|
+
filename: z.ZodOptional<z.ZodString>;
|
|
1021
|
+
sizeBytes: z.ZodNumber;
|
|
1022
|
+
expiresAt: z.ZodString;
|
|
1023
|
+
}, z.core.$strip>;
|
|
1024
|
+
type AttachmentUploadResponse = z.infer<typeof AttachmentUploadResponseSchema>;
|
|
1011
1025
|
/**
|
|
1012
1026
|
* Request body for `POST /v0/extract`. Mirrors `ExtractFromProseRequestSchema` in agents-api.
|
|
1013
1027
|
*
|
|
@@ -1034,6 +1048,7 @@ declare const ExtractFromProseParamsSchema: z.ZodObject<{
|
|
|
1034
1048
|
dataBase64: z.ZodString;
|
|
1035
1049
|
filename: z.ZodOptional<z.ZodString>;
|
|
1036
1050
|
}, z.core.$strip>], "kind">>>;
|
|
1051
|
+
attachmentRefs: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
1037
1052
|
metadata: z.ZodOptional<z.ZodObject<{
|
|
1038
1053
|
callId: z.ZodOptional<z.ZodString>;
|
|
1039
1054
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
@@ -2264,9 +2279,20 @@ declare class GraphyAiSdk {
|
|
|
2264
2279
|
summary: string;
|
|
2265
2280
|
} | undefined;
|
|
2266
2281
|
}>>>;
|
|
2282
|
+
/**
|
|
2283
|
+
* Uploads a file to the staged attachment store (`POST /v0/attachments`).
|
|
2284
|
+
*
|
|
2285
|
+
* @param file - File or Blob to upload (browser `File` or Node `Blob`).
|
|
2286
|
+
* @param options - Optional filename override when `file` has no name.
|
|
2287
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
2288
|
+
* @returns Staged attachment metadata including `graphy://attachments/{id}` URI.
|
|
2289
|
+
*/
|
|
2290
|
+
uploadAttachment(file: Blob, options?: {
|
|
2291
|
+
filename?: string;
|
|
2292
|
+
}, signal?: AbortSignal): Promise<AttachmentUploadResponse>;
|
|
2267
2293
|
private stripStorytelling;
|
|
2268
2294
|
private wrapStreamWithStorytellingStripping;
|
|
2269
2295
|
}
|
|
2270
2296
|
|
|
2271
|
-
export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, 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 };
|
|
2272
|
-
export type { AggregationFunction, AggregationSuggestion, AiChartType, 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 };
|
|
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 };
|
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}}})}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)}})}}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()}),S=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()}),k=1e4,C=a.enum(["comparison","relationship","distribution","composition"]),T=a.object({config:h,userPrompt:a.string().max(k).optional().default(""),metadata:$.optional(),chartFamily:C.optional()}),O=T.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"]),R=a.object({dataPrepPrompt:a.string(),chartType:E,summary:a.string()}),P=T.extend({userPrompt:a.string().max(k),mutationReceipt:S.optional(),exploreFindingSummary:a.string().max(500).optional()}),I=a.object({response:a.object({message:a.string()}),config:h}),A=a.object({suggestions:a.array(R)}),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: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.")}),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.")}),U=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),stories:a.array(F)});T.extend({mutationReceipt:S.optional()});const q=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h}),D=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,mutationReceipt:S.optional(),warnings:a.array(a.string()).optional()}),N=a.enum(["explore","mutate","narrate","annotate"]),K=a.object({agent:N,summary:a.string(),steps:a.array(a.string()).optional()}),M=T.extend({userPrompt:a.string().max(k),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()}),L=D.extend({reasoning:a.array(K),stories:a.array(F).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()}),_=a.object({score:a.number().min(0).max(1),issues:a.array(a.string()),sufficient:a.boolean(),summary:a.string()}),z=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.object({sourceText:a.string().max(z).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(),metadata:$.optional()}).superRefine((e,t)=>{var i,n;const r=e.sourceText.trim(),a=null!==(i=e.images)&&void 0!==i?i:[],o=null!==(n=e.attachments)&&void 0!==n?n:[];if(a.length>0&&o.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===r.length&&0===a.length&&0===o.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(a.length>0){a.reduce((e,t)=>e+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 s=0,c=0,l=0,m=0,d=0,u=0,g=0;for(const e of o){const t=ue(e.dataBase64).length;switch(g+=t,e.kind){case"image":s+=1,m+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":l+=1,u+=t}}s>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),l>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const p=s<=8&&c<=2&&l<=2;o.length>0&&p&&(m>oe&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ce&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>me&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>de&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function je(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ue(e.dataBase64)}}function $e(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ue(e.dataBase64)}}function Se(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 ke=a.object({response:a.object({message:a.string()}),config:h,extractMeta:W.nullable(),lastAccuracyEvaluation:_.optional()}),Ce=a.object({config:h,response:a.object({message:a.string(),steps:a.array(a.string())})}),Te=A,Oe=a.enum(["deal-breaker","pro","con","family","continuity"]),Ee=a.object({kind:Oe,label:a.string(),weight:a.number(),reason:a.string()}),Re=a.enum(["ok","disqualified"]),Pe=a.object({rank:a.number().int().positive(),type:E,score:a.number(),verdict:Re,factors:a.array(Ee)}),Ie=a.object({config:h,chartFamily:C.optional(),metadata:$.optional()}),Ae=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"]),Be=a.object({kind:Ae,message:a.string()}),Fe=a.enum(["sum","avg","count","min","max"]),Ue=a.object({dimensionName:a.string(),dimensionLabel:a.string(),measureName:a.string().nullable(),measureLabel:a.string().nullable(),fn:Fe,chartType:E,score:a.number(),message:a.string()}),qe=a.object({ranking:a.array(Pe),observations:a.array(Be).optional().default([]),suggestions:a.array(Ue).optional().default([])}),De=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()}),Ne=a.object({config:h.optional(),chartImage:a.string().optional(),data:a.unknown().optional(),rubric:De.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."}),Ke=a.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Me=a.enum(["info","low","medium","high"]),Le=a.object({category:Ke,severity:Me,observation:a.string(),rationale:a.string().optional(),suggestedChange:a.string().optional(),configPaths:a.array(a.string()).optional()}),Ge=a.object({overallSummary:a.string(),overallSeverity:a.enum(["none","low","medium","high"]).optional(),issues:a.array(Le)}),We=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()}),_e=a.object({capturedAt:a.string(),chartId:a.string()}),ze=a.object({response:a.object({message:a.string(),steps:a.array(a.string()),critiqueCommitted:a.boolean()}),critiqueReport:Ge.nullable(),chartVisionAudit:_e.nullable().optional().default(null),rubricScores:We.nullable().optional().default(null)}),He="/api/v0";class Je{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(`${He}/generate`,a,i,n),s=Ce.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(`${He}/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(`${He}/narrate`,t,i,n);return I.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/suggestions`,t,i,n);return A.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/explore`,t,i,n);return U.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/annotate`,t,i,n);return q.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/mutate`,t,i,n);return D.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/mutate`,t,i)})}generatePipeline(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/pipeline`,t,i,n);return L.parse(e)})}generatePipelineStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/pipeline`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/evaluate`,t,void 0,i);return qe.parse(e)})}judge(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/judge`,t,void 0,i);return ze.parse(e)})}judgeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/judge`,t,i)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/extract`,t,i,n);return ke.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/extract`,t,i)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,r){return i(this,arguments,function*(){var i,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{Fe as AggregationFunctionSchema,Ue as AggregationSuggestionSchema,E as AiChartTypeEnum,Ke as ChartCritiqueIssueCategorySchema,Le as ChartCritiqueIssueSchema,Me as ChartCritiqueIssueSeveritySchema,Ge as ChartCritiqueReportSchema,C as ChartFamilySchema,Pe as ChartFitEntrySchema,Oe as ChartFitFactorKindSchema,Ee as ChartFitFactorSchema,Re as ChartFitVerdictSchema,De as ChartJudgeRubricSchema,Ae as DataObservationKindSchema,Be as DataObservationSchema,Ie as EvaluateParamsSchema,qe as EvaluateResponseSchema,b as ExecutionModeSchema,B as ExploreFindingSchema,F as ExploreStorySchema,_ as ExtractAccuracyEvaluationSchema,we as ExtractAttachmentInputSchema,fe as ExtractAttachmentKindSchema,G as ExtractConfidenceSchema,xe as ExtractFromProseParamsSchema,ke as ExtractFromProseResponseSchema,W as ExtractMetaSchema,q as GenerateAnnotationsResponseSchema,U as GenerateExplorationResponseSchema,Ce as GenerateGraphResponseSchema,Te as GenerateGraphSuggestionsResponseSchema,D as GenerateMutationResponseSchema,P as GenerateNarrativeParamsSchema,I as GenerateNarrativeResponseSchema,M as GeneratePipelineParamsSchema,L as GeneratePipelineResponseSchema,O as GenerateSuggestionsParamsSchema,A as GenerateSuggestionsResponseSchema,T as GraphGenerationRequestSchema,Je as GraphyAiSdk,o as GraphyApiError,j as InvocationBudgetSchema,f as InvocationEffortSchema,Ne as JudgeParamsSchema,ze 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,z as MAX_SOURCE_TEXT_LENGTH,k as MAX_USER_PROMPT_LENGTH,$ as MetadataSchema,S as MutateNarrationReceiptSchema,N as PipelineAgentNameSchema,K as PipelineStageReasoningSchema,We as RubricScoresSchema,y as StorytellingEffortSchema,R as SuggestionSchema,je as buildImageAttachment,$e as buildPdfAttachment,Se 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,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};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@graphysdk/agents-sdk",
|
|
3
3
|
"author": "Graphy",
|
|
4
|
-
"version": "1.6.1
|
|
4
|
+
"version": "1.6.1",
|
|
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.1
|
|
21
|
+
"@graphysdk/core": "1.6.1"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|