@graphysdk/agents-sdk 1.5.0 → 1.6.0-beta.1780414747038

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("tslib"),t=require("zod");class r extends Error{constructor(e,t){var r;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(r=null==t?void 0:t.retryable)&&void 0!==r&&r}}const a=e=>"progress"===e.type,s=e=>"complete"===e.type,i=e=>"error"===e.type;class n{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return a(e)}static isCompleteEvent(e){return s(e)}static isErrorEvent(e){return i(e)}stream(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,a);return this.parseSSE(e)})}fetch(t,n,o,c){return e.__awaiter(this,void 0,void 0,function*(){var m,l,d,p,u;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,n,c),x=b.headers.get("content-type");if(null==x?void 0:x.includes("text/event-stream")){try{for(var h,f=!0,y=e.__asyncValues(this.parseSSE(b));!(m=(h=yield y.next()).done);f=!0){p=h.value,f=!1;const e=p;if(a(e)&&o&&o(e),s(e))return e.data;if(i(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||!(d=y.return)||(yield d.call(y))}finally{if(l)throw l.error}}const n=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${n}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const a=Date.now()-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(),s=new TextDecoder;let i="",n="",o="";try{for(;;){const{done:t,value:r}=yield e.__await(a.read());if(t)break;i+=s.decode(r,{stream:!0});const c=i.split(/\r?\n/);i=c.pop()||"";for(const t of c)if(t.startsWith("event: "))n=t.slice(7).trim();else if(t.startsWith("data: "))o+=(o?"\n":"")+t.slice(6);else if(""===t.trim()&&o){try{const t=JSON.parse(o);let r;if("progress"===n){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===n)r={type:"complete",data:t};else if("error"===n){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===n){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==n){n="",o="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===n||"error"===n)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}n="",o=""}}}finally{a.releaseLock()}})}makeRequest(t,a,s){return e.__awaiter(this,arguments,void 0,function*(e,t,a,s=1,i="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const n=new URL(e,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${s}/${this.retryConfig.attempts}: ${n}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),m=()=>o.abort();a&&a.addEventListener("abort",m);try{const c=yield fetch(n,Object.assign({method:i,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:o.signal},"POST"===i&&{body:JSON.stringify(t)}));if(!c.ok){const n=c.status>=500||429===c.status;let o,m=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?m=t.message:"string"==typeof t.error&&(m=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=new r(m,{status:c.status,code:o,retryable:n});if(n&&s<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,s-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${s+1})`),yield this.sleep(r),this.makeRequest(e,t,a,s+1,i)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${m}`),l}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),n;if(s<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,s-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,a,s+1,i)}throw this.logger.error(`${this.tag} Network error: ${e}`,n),new r("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",m)}})}}const o=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),m=t.z.enum(["low","medium","high"]),l=t.z.enum(["none","low","medium","high"]),d=t.z.enum(["agentic","fast"]),p=t.z.object({maxWallClockMs:t.z.number().positive().optional(),maxTotalTokens:t.z.number().int().positive().optional(),maxCostUsd:t.z.number().positive().optional()}),u=t.z.object({callId:t.z.string().max(256).optional(),locale:o.optional(),effort:m.optional(),storytellingEffort:l.optional().default("low"),budget:p.optional(),executionMode:d.optional()}),g=1e4,h=t.z.object({config:c,userPrompt:t.z.string().max(g).optional().default(""),metadata:u.optional()}),f=h.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),y=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),b=t.z.object({dataPrepPrompt:t.z.string(),chartType:y,summary:t.z.string()}),x=h.extend({userPrompt:t.z.string().max(g)}),v=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),z=t.z.object({suggestions:t.z.array(b)}),_=t.z.enum(["comparison","relationship","distribution","composition"]),S=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:_.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),w=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(S).describe("Child findings, sorted by quadrant score desc.")}),E=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(w)}),T=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),A=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),C=t.z.enum(["high","medium","low"]),j=t.z.object({confidence:C,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:C,quote:t.z.string().optional()})).optional()}),$=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()}),R=5e5,k=2097152,O=7340032,D=6291456,M=8388608,P=D,I=M,G=12582912;function B(e){return 4*Math.ceil(e/3)}const X=B(k),N=B(O),F=B(D),U=B(M),q=B(P),K=B(I),L=B(G);function H(e){return e.replace(/\s+/g,"")}function Y(e){const t=H(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const W=/^image\/(png|jpeg|jpg|webp|gif)$/i,V=t.z.object({mimeType:t.z.string().min(1).refine(e=>W.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(X).refine(Y,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),J=t.z.enum(["image","document","spreadsheet"]),Z=V.extend({kind:t.z.literal("image")}),Q=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(F).refine(Y,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ee=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(q).refine(Y,{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"]}),te=t.z.discriminatedUnion("kind",[Z,Q,ee]),re=t.z.object({sourceText:t.z.string().max(R).default(""),images:t.z.array(V).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(te).max(12).optional(),metadata:u.optional()}).superRefine((e,t)=>{var r,a;const s=e.sourceText.trim(),i=null!==(r=e.images)&&void 0!==r?r:[],n=null!==(a=e.attachments)&&void 0!==a?a:[];if(i.length>0&&n.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===s.length&&0===i.length&&0===n.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(i.length>0){i.reduce((e,t)=>e+H(t.dataBase64).length,0)>N&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,m=0,l=0,d=0,p=0,u=0;for(const e of n){const t=H(e.dataBase64).length;switch(u+=t,e.kind){case"image":o+=1,l+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":m+=1,p+=t}}o>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const g=o<=8&&c<=2&&m<=2;n.length>0&&g&&(l>N&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>U&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>K&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>L&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const ae=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:j.nullable(),lastAccuracyEvaluation:$.optional()}),se=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),ie=z,ne=t.z.enum(["deal-breaker","pro","con","family","continuity"]),oe=t.z.object({kind:ne,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),ce=t.z.enum(["ok","disqualified"]),me=t.z.object({rank:t.z.number().int().positive(),type:y,score:t.z.number(),verdict:ce,factors:t.z.array(oe)}),le=t.z.object({config:c,chartFamily:_.optional(),metadata:u.optional()}),de=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"]),pe=t.z.object({kind:de,message:t.z.string()}),ue=t.z.enum(["sum","avg","count","min","max"]),ge=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:ue,chartType:y,score:t.z.number(),message:t.z.string()}),he=t.z.object({ranking:t.z.array(me),observations:t.z.array(pe).optional().default([]),suggestions:t.z.array(ge).optional().default([])}),fe="/api/v0";exports.AggregationFunctionSchema=ue,exports.AggregationSuggestionSchema=ge,exports.AiChartTypeEnum=y,exports.ChartFamilySchema=_,exports.ChartFitEntrySchema=me,exports.ChartFitFactorKindSchema=ne,exports.ChartFitFactorSchema=oe,exports.ChartFitVerdictSchema=ce,exports.DataObservationKindSchema=de,exports.DataObservationSchema=pe,exports.EvaluateParamsSchema=le,exports.EvaluateResponseSchema=he,exports.ExecutionModeSchema=d,exports.ExploreFindingSchema=S,exports.ExploreStorySchema=w,exports.ExtractAccuracyEvaluationSchema=$,exports.ExtractAttachmentInputSchema=te,exports.ExtractAttachmentKindSchema=J,exports.ExtractConfidenceSchema=C,exports.ExtractFromProseParamsSchema=re,exports.ExtractFromProseResponseSchema=ae,exports.ExtractMetaSchema=j,exports.GenerateAnnotationsResponseSchema=T,exports.GenerateExplorationResponseSchema=E,exports.GenerateGraphResponseSchema=se,exports.GenerateGraphSuggestionsResponseSchema=ie,exports.GenerateMutationResponseSchema=A,exports.GenerateNarrativeParamsSchema=x,exports.GenerateNarrativeResponseSchema=v,exports.GenerateSuggestionsParamsSchema=f,exports.GenerateSuggestionsResponseSchema=z,exports.GraphGenerationRequestSchema=h,exports.GraphyAiSdk=class{constructor(e){this.client=new n(e)}generateGraph(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:s}=t,i=e.__rest(t,["storytellingOptions"]),n=yield this.client.fetch(`${fe}/generate`,i,r,a),o=se.parse(n);return this.stripStorytelling(o,s)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,s=e.__rest(t,["storytellingOptions"]),i=yield this.client.stream(`${fe}/generate`,s,r);return this.wrapStreamWithStorytellingStripping(i,a)})}generateNarrative(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/narrate`,t,r,a);return v.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/suggestions`,t,r,a);return z.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/explore`,t,r,a);return E.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/annotate`,t,r,a);return T.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/mutate`,t,r,a);return A.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/mutate`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/evaluate`,t,void 0,r);return he.parse(e)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${fe}/extract`,t,r,a);return ae.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${fe}/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,i,n,o;try{for(var c,m=!0,l=e.__asyncValues(t);!(a=(c=yield e.__await(l.next())).done);m=!0){o=c.value,m=!1;const t=o;if(s(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){i={error:e}}finally{try{m||a||!(n=l.return)||(yield e.__await(n.call(l)))}finally{if(i)throw i.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=p,exports.InvocationEffortSchema=m,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=G,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=M,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=D,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=O,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=k,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=I,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=P,exports.MAX_SOURCE_TEXT_LENGTH=R,exports.MAX_USER_PROMPT_LENGTH=g,exports.MetadataSchema=u,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=b,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:H(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:H(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:H(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=s,exports.isErrorEvent=i,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 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){const o=c.status>=500||429===c.status;let s,m=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?m=t.message:"string"==typeof t.error&&(m=t.error),"string"==typeof t.code&&(s=t.code)}}catch(e){}const l=new r(m,{status:c.status,code:s,retryable:o});if(o&&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}) - ${m}`),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()}),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()}),P=R.extend({reasoning:t.z.array(O),stories:t.z.array(C).optional()}),D=t.z.enum(["high","medium","low"]),M=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,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),Z=K(q),Q=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>Z&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>Q&&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=D,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=P,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 P.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;
package/dist/index.d.ts CHANGED
@@ -292,10 +292,15 @@ declare const ExecutionModeSchema: z.ZodEnum<{
292
292
  fast: "fast";
293
293
  }>;
294
294
  type ExecutionMode = z.infer<typeof ExecutionModeSchema>;
295
+ /** Absolute budget caps. Mirror `MAX_BUDGET_*` in `apps/agents-api/src/modules/api/api.types.ts`. */
296
+ declare const MAX_BUDGET_WALL_CLOCK_MS = 300000;
297
+ declare const MAX_BUDGET_TOTAL_TOKENS = 500000;
298
+ declare const MAX_BUDGET_COST_USD = 10;
295
299
  /**
296
300
  * Optional per-request invocation budget. Mirrors `InvocationBudgetSchema` in
297
- * `apps/agents-api/src/modules/api/api.types.ts`. All fields are optional — the
298
- * server merges whatever is provided with its own defaults.
301
+ * `apps/agents-api/src/modules/api/api.types.ts`. All fields are optional — the server merges
302
+ * whatever is provided with its own defaults, then clamps it to the agent's ceiling (a client can
303
+ * only lower its budget, never raise it above the per-agent limit).
299
304
  */
300
305
  declare const InvocationBudgetSchema: z.ZodObject<{
301
306
  maxWallClockMs: z.ZodOptional<z.ZodNumber>;
@@ -334,9 +339,47 @@ declare const MetadataSchema: z.ZodObject<{
334
339
  fast: "fast";
335
340
  }>>;
336
341
  }, z.core.$strip>;
342
+ /** Provenance from a prior mutate invocation; forwarded to narrate/annotate. Kept in sync with agents-api. */
343
+ declare const MutateNarrationReceiptSchema: z.ZodObject<{
344
+ steps: z.ZodArray<z.ZodString>;
345
+ postProcess: z.ZodOptional<z.ZodObject<{
346
+ measureRelevance: z.ZodOptional<z.ZodEnum<{
347
+ "prompt-named": "prompt-named";
348
+ derived: "derived";
349
+ magnitude: "magnitude";
350
+ }>>;
351
+ grain: z.ZodOptional<z.ZodEnum<{
352
+ "remap-x": "remap-x";
353
+ groupBy: "groupBy";
354
+ reshape: "reshape";
355
+ compositeX: "compositeX";
356
+ }>>;
357
+ chartType: z.ZodOptional<z.ZodString>;
358
+ comparison: z.ZodOptional<z.ZodString>;
359
+ }, z.core.$strip>>;
360
+ droppedMeasures: z.ZodOptional<z.ZodArray<z.ZodString>>;
361
+ rowCount: z.ZodNumber;
362
+ totalRowCountBeforeSlice: z.ZodOptional<z.ZodNumber>;
363
+ displayedRowCount: z.ZodOptional<z.ZodNumber>;
364
+ columnKeys: z.ZodArray<z.ZodString>;
365
+ activeFilters: z.ZodOptional<z.ZodArray<z.ZodString>>;
366
+ grainSummary: z.ZodOptional<z.ZodString>;
367
+ }, z.core.$strip>;
368
+ type MutateNarrationReceipt = z.infer<typeof MutateNarrationReceiptSchema>;
337
369
  type Metadata = z.infer<typeof MetadataSchema>;
338
370
  /** Mirrors `MAX_USER_PROMPT_LENGTH` in the agents-api request schema. */
339
371
  declare const MAX_USER_PROMPT_LENGTH = 10000;
372
+ /**
373
+ * Abela chart family — classifies the question-shape a finding is answering. Downstream
374
+ * chart-generator picks the concrete chart type from this family + the data shape.
375
+ */
376
+ declare const ChartFamilySchema: z.ZodEnum<{
377
+ comparison: "comparison";
378
+ relationship: "relationship";
379
+ distribution: "distribution";
380
+ composition: "composition";
381
+ }>;
382
+ type ChartFamily = z.infer<typeof ChartFamilySchema>;
340
383
  /**
341
384
  * Shared request body for every agent endpoint (`/v0/generate`, `/v0/narrate`,
342
385
  * `/v0/explore`, `/v0/annotate`, etc.). Mirrors `GraphGenerationRequestSchema`
@@ -372,6 +415,12 @@ declare const GraphGenerationRequestSchema: z.ZodObject<{
372
415
  fast: "fast";
373
416
  }>>;
374
417
  }, z.core.$strip>>;
418
+ chartFamily: z.ZodOptional<z.ZodEnum<{
419
+ comparison: "comparison";
420
+ relationship: "relationship";
421
+ distribution: "distribution";
422
+ composition: "composition";
423
+ }>>;
375
424
  }, z.core.$strip>;
376
425
  type GraphGenerationRequest = z.input<typeof GraphGenerationRequestSchema>;
377
426
  /** Request body for `POST /v0/suggestions` only. `maxSuggestionCount` max must match agents-api `PROMPT_SUGGESTIONS_UPPER_BOUND`. */
@@ -405,6 +454,12 @@ declare const GenerateSuggestionsParamsSchema: z.ZodObject<{
405
454
  fast: "fast";
406
455
  }>>;
407
456
  }, z.core.$strip>>;
457
+ chartFamily: z.ZodOptional<z.ZodEnum<{
458
+ comparison: "comparison";
459
+ relationship: "relationship";
460
+ distribution: "distribution";
461
+ composition: "composition";
462
+ }>>;
408
463
  maxSuggestionCount: z.ZodOptional<z.ZodNumber>;
409
464
  }, z.core.$strip>;
410
465
  type GenerateSuggestionsParams = z.input<typeof GenerateSuggestionsParamsSchema>;
@@ -491,7 +546,39 @@ declare const GenerateNarrativeParamsSchema: z.ZodObject<{
491
546
  fast: "fast";
492
547
  }>>;
493
548
  }, z.core.$strip>>;
549
+ chartFamily: z.ZodOptional<z.ZodEnum<{
550
+ comparison: "comparison";
551
+ relationship: "relationship";
552
+ distribution: "distribution";
553
+ composition: "composition";
554
+ }>>;
494
555
  userPrompt: z.ZodString;
556
+ mutationReceipt: z.ZodOptional<z.ZodObject<{
557
+ steps: z.ZodArray<z.ZodString>;
558
+ postProcess: z.ZodOptional<z.ZodObject<{
559
+ measureRelevance: z.ZodOptional<z.ZodEnum<{
560
+ "prompt-named": "prompt-named";
561
+ derived: "derived";
562
+ magnitude: "magnitude";
563
+ }>>;
564
+ grain: z.ZodOptional<z.ZodEnum<{
565
+ "remap-x": "remap-x";
566
+ groupBy: "groupBy";
567
+ reshape: "reshape";
568
+ compositeX: "compositeX";
569
+ }>>;
570
+ chartType: z.ZodOptional<z.ZodString>;
571
+ comparison: z.ZodOptional<z.ZodString>;
572
+ }, z.core.$strip>>;
573
+ droppedMeasures: z.ZodOptional<z.ZodArray<z.ZodString>>;
574
+ rowCount: z.ZodNumber;
575
+ totalRowCountBeforeSlice: z.ZodOptional<z.ZodNumber>;
576
+ displayedRowCount: z.ZodOptional<z.ZodNumber>;
577
+ columnKeys: z.ZodArray<z.ZodString>;
578
+ activeFilters: z.ZodOptional<z.ZodArray<z.ZodString>>;
579
+ grainSummary: z.ZodOptional<z.ZodString>;
580
+ }, z.core.$strip>>;
581
+ exploreFindingSummary: z.ZodOptional<z.ZodString>;
495
582
  }, z.core.$strip>;
496
583
  type GenerateNarrativeParams = z.input<typeof GenerateNarrativeParamsSchema>;
497
584
  declare const GenerateNarrativeResponseSchema: z.ZodObject<{
@@ -531,17 +618,6 @@ declare const GenerateSuggestionsResponseSchema: z.ZodObject<{
531
618
  }, z.core.$strip>;
532
619
  type GenerateSuggestionsResponse = z.infer<typeof GenerateSuggestionsResponseSchema>;
533
620
  type GenerateExplorationParams = GraphGenerationRequest;
534
- /**
535
- * Abela chart family — classifies the question-shape a finding is answering. Downstream
536
- * chart-generator picks the concrete chart type from this family + the data shape.
537
- */
538
- declare const ChartFamilySchema: z.ZodEnum<{
539
- comparison: "comparison";
540
- relationship: "relationship";
541
- distribution: "distribution";
542
- composition: "composition";
543
- }>;
544
- type ChartFamily = z.infer<typeof ChartFamilySchema>;
545
621
  /** A single structured finding produced by the explore agent. */
546
622
  declare const ExploreFindingSchema: z.ZodObject<{
547
623
  finding: z.ZodString;
@@ -610,7 +686,69 @@ declare const GenerateExplorationResponseSchema: z.ZodObject<{
610
686
  }, z.core.$strip>>;
611
687
  }, z.core.$strip>;
612
688
  type GenerateExplorationResponse = z.infer<typeof GenerateExplorationResponseSchema>;
613
- type GenerateAnnotationsParams = GraphGenerationRequest;
689
+ declare const GenerateAnnotationsParamsSchema: z.ZodObject<{
690
+ config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
691
+ userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
692
+ metadata: z.ZodOptional<z.ZodObject<{
693
+ callId: z.ZodOptional<z.ZodString>;
694
+ locale: z.ZodOptional<z.ZodEnum<{
695
+ EN_GB: "EN_GB";
696
+ EN_US: "EN_US";
697
+ }>>;
698
+ effort: z.ZodOptional<z.ZodEnum<{
699
+ low: "low";
700
+ medium: "medium";
701
+ high: "high";
702
+ }>>;
703
+ storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
704
+ low: "low";
705
+ medium: "medium";
706
+ high: "high";
707
+ none: "none";
708
+ }>>>;
709
+ budget: z.ZodOptional<z.ZodObject<{
710
+ maxWallClockMs: z.ZodOptional<z.ZodNumber>;
711
+ maxTotalTokens: z.ZodOptional<z.ZodNumber>;
712
+ maxCostUsd: z.ZodOptional<z.ZodNumber>;
713
+ }, z.core.$strip>>;
714
+ executionMode: z.ZodOptional<z.ZodEnum<{
715
+ agentic: "agentic";
716
+ fast: "fast";
717
+ }>>;
718
+ }, z.core.$strip>>;
719
+ chartFamily: z.ZodOptional<z.ZodEnum<{
720
+ comparison: "comparison";
721
+ relationship: "relationship";
722
+ distribution: "distribution";
723
+ composition: "composition";
724
+ }>>;
725
+ mutationReceipt: z.ZodOptional<z.ZodObject<{
726
+ steps: z.ZodArray<z.ZodString>;
727
+ postProcess: z.ZodOptional<z.ZodObject<{
728
+ measureRelevance: z.ZodOptional<z.ZodEnum<{
729
+ "prompt-named": "prompt-named";
730
+ derived: "derived";
731
+ magnitude: "magnitude";
732
+ }>>;
733
+ grain: z.ZodOptional<z.ZodEnum<{
734
+ "remap-x": "remap-x";
735
+ groupBy: "groupBy";
736
+ reshape: "reshape";
737
+ compositeX: "compositeX";
738
+ }>>;
739
+ chartType: z.ZodOptional<z.ZodString>;
740
+ comparison: z.ZodOptional<z.ZodString>;
741
+ }, z.core.$strip>>;
742
+ droppedMeasures: z.ZodOptional<z.ZodArray<z.ZodString>>;
743
+ rowCount: z.ZodNumber;
744
+ totalRowCountBeforeSlice: z.ZodOptional<z.ZodNumber>;
745
+ displayedRowCount: z.ZodOptional<z.ZodNumber>;
746
+ columnKeys: z.ZodArray<z.ZodString>;
747
+ activeFilters: z.ZodOptional<z.ZodArray<z.ZodString>>;
748
+ grainSummary: z.ZodOptional<z.ZodString>;
749
+ }, z.core.$strip>>;
750
+ }, z.core.$strip>;
751
+ type GenerateAnnotationsParams = z.input<typeof GenerateAnnotationsParamsSchema>;
614
752
  declare const GenerateAnnotationsResponseSchema: z.ZodObject<{
615
753
  response: z.ZodObject<{
616
754
  message: z.ZodString;
@@ -626,8 +764,163 @@ declare const GenerateMutationResponseSchema: z.ZodObject<{
626
764
  steps: z.ZodArray<z.ZodString>;
627
765
  }, z.core.$strip>;
628
766
  config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
767
+ mutationReceipt: z.ZodOptional<z.ZodObject<{
768
+ steps: z.ZodArray<z.ZodString>;
769
+ postProcess: z.ZodOptional<z.ZodObject<{
770
+ measureRelevance: z.ZodOptional<z.ZodEnum<{
771
+ "prompt-named": "prompt-named";
772
+ derived: "derived";
773
+ magnitude: "magnitude";
774
+ }>>;
775
+ grain: z.ZodOptional<z.ZodEnum<{
776
+ "remap-x": "remap-x";
777
+ groupBy: "groupBy";
778
+ reshape: "reshape";
779
+ compositeX: "compositeX";
780
+ }>>;
781
+ chartType: z.ZodOptional<z.ZodString>;
782
+ comparison: z.ZodOptional<z.ZodString>;
783
+ }, z.core.$strip>>;
784
+ droppedMeasures: z.ZodOptional<z.ZodArray<z.ZodString>>;
785
+ rowCount: z.ZodNumber;
786
+ totalRowCountBeforeSlice: z.ZodOptional<z.ZodNumber>;
787
+ displayedRowCount: z.ZodOptional<z.ZodNumber>;
788
+ columnKeys: z.ZodArray<z.ZodString>;
789
+ activeFilters: z.ZodOptional<z.ZodArray<z.ZodString>>;
790
+ grainSummary: z.ZodOptional<z.ZodString>;
791
+ }, z.core.$strip>>;
792
+ warnings: z.ZodOptional<z.ZodArray<z.ZodString>>;
629
793
  }, z.core.$strip>;
630
794
  type GenerateMutationResponse = z.infer<typeof GenerateMutationResponseSchema>;
795
+ declare const PipelineAgentNameSchema: z.ZodEnum<{
796
+ explore: "explore";
797
+ mutate: "mutate";
798
+ narrate: "narrate";
799
+ annotate: "annotate";
800
+ }>;
801
+ type PipelineAgentName = z.infer<typeof PipelineAgentNameSchema>;
802
+ declare const PipelineStageReasoningSchema: z.ZodObject<{
803
+ agent: z.ZodEnum<{
804
+ explore: "explore";
805
+ mutate: "mutate";
806
+ narrate: "narrate";
807
+ annotate: "annotate";
808
+ }>;
809
+ summary: z.ZodString;
810
+ steps: z.ZodOptional<z.ZodArray<z.ZodString>>;
811
+ }, z.core.$strip>;
812
+ type PipelineStageReasoning = z.infer<typeof PipelineStageReasoningSchema>;
813
+ /**
814
+ * Request body for `POST /v0/pipeline` — ordered agent stages on one shared server session.
815
+ */
816
+ declare const GeneratePipelineParamsSchema: z.ZodObject<{
817
+ config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
818
+ metadata: z.ZodOptional<z.ZodObject<{
819
+ callId: z.ZodOptional<z.ZodString>;
820
+ locale: z.ZodOptional<z.ZodEnum<{
821
+ EN_GB: "EN_GB";
822
+ EN_US: "EN_US";
823
+ }>>;
824
+ effort: z.ZodOptional<z.ZodEnum<{
825
+ low: "low";
826
+ medium: "medium";
827
+ high: "high";
828
+ }>>;
829
+ storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
830
+ low: "low";
831
+ medium: "medium";
832
+ high: "high";
833
+ none: "none";
834
+ }>>>;
835
+ budget: z.ZodOptional<z.ZodObject<{
836
+ maxWallClockMs: z.ZodOptional<z.ZodNumber>;
837
+ maxTotalTokens: z.ZodOptional<z.ZodNumber>;
838
+ maxCostUsd: z.ZodOptional<z.ZodNumber>;
839
+ }, z.core.$strip>>;
840
+ executionMode: z.ZodOptional<z.ZodEnum<{
841
+ agentic: "agentic";
842
+ fast: "fast";
843
+ }>>;
844
+ }, z.core.$strip>>;
845
+ chartFamily: z.ZodOptional<z.ZodEnum<{
846
+ comparison: "comparison";
847
+ relationship: "relationship";
848
+ distribution: "distribution";
849
+ composition: "composition";
850
+ }>>;
851
+ userPrompt: z.ZodString;
852
+ stages: z.ZodArray<z.ZodEnum<{
853
+ explore: "explore";
854
+ mutate: "mutate";
855
+ narrate: "narrate";
856
+ annotate: "annotate";
857
+ }>>;
858
+ exploreFindingSummary: z.ZodOptional<z.ZodString>;
859
+ }, z.core.$strip>;
860
+ type GeneratePipelineParams = z.input<typeof GeneratePipelineParamsSchema>;
861
+ declare const GeneratePipelineResponseSchema: z.ZodObject<{
862
+ response: z.ZodObject<{
863
+ message: z.ZodString;
864
+ steps: z.ZodArray<z.ZodString>;
865
+ }, z.core.$strip>;
866
+ config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
867
+ mutationReceipt: z.ZodOptional<z.ZodObject<{
868
+ steps: z.ZodArray<z.ZodString>;
869
+ postProcess: z.ZodOptional<z.ZodObject<{
870
+ measureRelevance: z.ZodOptional<z.ZodEnum<{
871
+ "prompt-named": "prompt-named";
872
+ derived: "derived";
873
+ magnitude: "magnitude";
874
+ }>>;
875
+ grain: z.ZodOptional<z.ZodEnum<{
876
+ "remap-x": "remap-x";
877
+ groupBy: "groupBy";
878
+ reshape: "reshape";
879
+ compositeX: "compositeX";
880
+ }>>;
881
+ chartType: z.ZodOptional<z.ZodString>;
882
+ comparison: z.ZodOptional<z.ZodString>;
883
+ }, z.core.$strip>>;
884
+ droppedMeasures: z.ZodOptional<z.ZodArray<z.ZodString>>;
885
+ rowCount: z.ZodNumber;
886
+ totalRowCountBeforeSlice: z.ZodOptional<z.ZodNumber>;
887
+ displayedRowCount: z.ZodOptional<z.ZodNumber>;
888
+ columnKeys: z.ZodArray<z.ZodString>;
889
+ activeFilters: z.ZodOptional<z.ZodArray<z.ZodString>>;
890
+ grainSummary: z.ZodOptional<z.ZodString>;
891
+ }, z.core.$strip>>;
892
+ warnings: z.ZodOptional<z.ZodArray<z.ZodString>>;
893
+ reasoning: z.ZodArray<z.ZodObject<{
894
+ agent: z.ZodEnum<{
895
+ explore: "explore";
896
+ mutate: "mutate";
897
+ narrate: "narrate";
898
+ annotate: "annotate";
899
+ }>;
900
+ summary: z.ZodString;
901
+ steps: z.ZodOptional<z.ZodArray<z.ZodString>>;
902
+ }, z.core.$strip>>;
903
+ stories: z.ZodOptional<z.ZodArray<z.ZodObject<{
904
+ topic: z.ZodString;
905
+ score: z.ZodNumber;
906
+ count: z.ZodNumber;
907
+ findings: z.ZodArray<z.ZodObject<{
908
+ finding: z.ZodString;
909
+ confidence: z.ZodNumber;
910
+ relevance: z.ZodNumber;
911
+ topic: z.ZodString;
912
+ chartHint: z.ZodString;
913
+ chartFamily: z.ZodEnum<{
914
+ comparison: "comparison";
915
+ relationship: "relationship";
916
+ distribution: "distribution";
917
+ composition: "composition";
918
+ }>;
919
+ evidenceSummary: z.ZodString;
920
+ }, z.core.$strip>>;
921
+ }, z.core.$strip>>>;
922
+ }, z.core.$strip>;
923
+ type GeneratePipelineResponse = z.infer<typeof GeneratePipelineResponseSchema>;
631
924
  /** Mirrors agents-api `extractConfidenceSchema`. */
632
925
  declare const ExtractConfidenceSchema: z.ZodEnum<{
633
926
  low: "low";
@@ -1189,6 +1482,204 @@ declare const EvaluateResponseSchema: z.ZodObject<{
1189
1482
  }, z.core.$strip>>>>;
1190
1483
  }, z.core.$strip>;
1191
1484
  type EvaluateResponse = z.infer<typeof EvaluateResponseSchema>;
1485
+ /** Optional benchmark rubric. When present, the judge also returns {@link RubricScores}. */
1486
+ declare const ChartJudgeRubricSchema: z.ZodObject<{
1487
+ prompt: z.ZodString;
1488
+ datasetSummary: z.ZodOptional<z.ZodString>;
1489
+ mustShow: z.ZodOptional<z.ZodArray<z.ZodString>>;
1490
+ unacceptable: z.ZodOptional<z.ZodArray<z.ZodString>>;
1491
+ acceptableChartFamilies: z.ZodOptional<z.ZodArray<z.ZodString>>;
1492
+ }, z.core.$strip>;
1493
+ type ChartJudgeRubric = z.infer<typeof ChartJudgeRubricSchema>;
1494
+ /**
1495
+ * Request body for `POST /v0/judge`. The judge is config-optional: provide a `config`, a rendered
1496
+ * `chartImage` (URL or `data:` URL), or both, plus an optional `data` dataset for deterministic
1497
+ * profiling and an optional `rubric` to also receive a numeric scorecard. At least one of `config`
1498
+ * / `chartImage` must be supplied.
1499
+ */
1500
+ declare const JudgeParamsSchema: z.ZodObject<{
1501
+ config: z.ZodOptional<z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>>;
1502
+ chartImage: z.ZodOptional<z.ZodString>;
1503
+ data: z.ZodOptional<z.ZodUnknown>;
1504
+ rubric: z.ZodOptional<z.ZodObject<{
1505
+ prompt: z.ZodString;
1506
+ datasetSummary: z.ZodOptional<z.ZodString>;
1507
+ mustShow: z.ZodOptional<z.ZodArray<z.ZodString>>;
1508
+ unacceptable: z.ZodOptional<z.ZodArray<z.ZodString>>;
1509
+ acceptableChartFamilies: z.ZodOptional<z.ZodArray<z.ZodString>>;
1510
+ }, z.core.$strip>>;
1511
+ userPrompt: z.ZodOptional<z.ZodString>;
1512
+ metadata: z.ZodOptional<z.ZodObject<{
1513
+ callId: z.ZodOptional<z.ZodString>;
1514
+ locale: z.ZodOptional<z.ZodEnum<{
1515
+ EN_GB: "EN_GB";
1516
+ EN_US: "EN_US";
1517
+ }>>;
1518
+ effort: z.ZodOptional<z.ZodEnum<{
1519
+ low: "low";
1520
+ medium: "medium";
1521
+ high: "high";
1522
+ }>>;
1523
+ storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
1524
+ low: "low";
1525
+ medium: "medium";
1526
+ high: "high";
1527
+ none: "none";
1528
+ }>>>;
1529
+ budget: z.ZodOptional<z.ZodObject<{
1530
+ maxWallClockMs: z.ZodOptional<z.ZodNumber>;
1531
+ maxTotalTokens: z.ZodOptional<z.ZodNumber>;
1532
+ maxCostUsd: z.ZodOptional<z.ZodNumber>;
1533
+ }, z.core.$strip>>;
1534
+ executionMode: z.ZodOptional<z.ZodEnum<{
1535
+ agentic: "agentic";
1536
+ fast: "fast";
1537
+ }>>;
1538
+ }, z.core.$strip>>;
1539
+ }, z.core.$strip>;
1540
+ type JudgeParams = z.input<typeof JudgeParamsSchema>;
1541
+ declare const ChartCritiqueIssueCategorySchema: z.ZodEnum<{
1542
+ layout: "layout";
1543
+ color_contrast: "color_contrast";
1544
+ typography: "typography";
1545
+ clutter: "clutter";
1546
+ encoding: "encoding";
1547
+ labels_legends: "labels_legends";
1548
+ title_caption: "title_caption";
1549
+ other: "other";
1550
+ }>;
1551
+ type ChartCritiqueIssueCategory = z.infer<typeof ChartCritiqueIssueCategorySchema>;
1552
+ declare const ChartCritiqueIssueSeveritySchema: z.ZodEnum<{
1553
+ low: "low";
1554
+ medium: "medium";
1555
+ high: "high";
1556
+ info: "info";
1557
+ }>;
1558
+ type ChartCritiqueIssueSeverity = z.infer<typeof ChartCritiqueIssueSeveritySchema>;
1559
+ declare const ChartCritiqueIssueSchema: z.ZodObject<{
1560
+ category: z.ZodEnum<{
1561
+ layout: "layout";
1562
+ color_contrast: "color_contrast";
1563
+ typography: "typography";
1564
+ clutter: "clutter";
1565
+ encoding: "encoding";
1566
+ labels_legends: "labels_legends";
1567
+ title_caption: "title_caption";
1568
+ other: "other";
1569
+ }>;
1570
+ severity: z.ZodEnum<{
1571
+ low: "low";
1572
+ medium: "medium";
1573
+ high: "high";
1574
+ info: "info";
1575
+ }>;
1576
+ observation: z.ZodString;
1577
+ rationale: z.ZodOptional<z.ZodString>;
1578
+ suggestedChange: z.ZodOptional<z.ZodString>;
1579
+ configPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
1580
+ }, z.core.$strip>;
1581
+ type ChartCritiqueIssue = z.infer<typeof ChartCritiqueIssueSchema>;
1582
+ declare const ChartCritiqueReportSchema: z.ZodObject<{
1583
+ overallSummary: z.ZodString;
1584
+ overallSeverity: z.ZodOptional<z.ZodEnum<{
1585
+ low: "low";
1586
+ medium: "medium";
1587
+ high: "high";
1588
+ none: "none";
1589
+ }>>;
1590
+ issues: z.ZodArray<z.ZodObject<{
1591
+ category: z.ZodEnum<{
1592
+ layout: "layout";
1593
+ color_contrast: "color_contrast";
1594
+ typography: "typography";
1595
+ clutter: "clutter";
1596
+ encoding: "encoding";
1597
+ labels_legends: "labels_legends";
1598
+ title_caption: "title_caption";
1599
+ other: "other";
1600
+ }>;
1601
+ severity: z.ZodEnum<{
1602
+ low: "low";
1603
+ medium: "medium";
1604
+ high: "high";
1605
+ info: "info";
1606
+ }>;
1607
+ observation: z.ZodString;
1608
+ rationale: z.ZodOptional<z.ZodString>;
1609
+ suggestedChange: z.ZodOptional<z.ZodString>;
1610
+ configPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
1611
+ }, z.core.$strip>>;
1612
+ }, z.core.$strip>;
1613
+ type ChartCritiqueReport = z.infer<typeof ChartCritiqueReportSchema>;
1614
+ /** Numeric scorecard, present only when a rubric was supplied. Each dimension is in `[0, 1]`. */
1615
+ declare const RubricScoresSchema: z.ZodObject<{
1616
+ dataFidelity: z.ZodNumber;
1617
+ promptRelevance: z.ZodNumber;
1618
+ chartTypeAppropriateness: z.ZodNumber;
1619
+ readability: z.ZodNumber;
1620
+ honesty: z.ZodNumber;
1621
+ composite: z.ZodNumber;
1622
+ rationale: z.ZodOptional<z.ZodString>;
1623
+ }, z.core.$strip>;
1624
+ type RubricScores = z.infer<typeof RubricScoresSchema>;
1625
+ /**
1626
+ * Response body for `POST /v0/judge`.
1627
+ *
1628
+ * `chartVisionAudit` and `rubricScores` are nullable-with-default so the SDK tolerates a server
1629
+ * that omits them (e.g. an older deployment) — consumers can treat them as `value | null`.
1630
+ */
1631
+ declare const JudgeResponseSchema: z.ZodObject<{
1632
+ response: z.ZodObject<{
1633
+ message: z.ZodString;
1634
+ steps: z.ZodArray<z.ZodString>;
1635
+ critiqueCommitted: z.ZodBoolean;
1636
+ }, z.core.$strip>;
1637
+ critiqueReport: z.ZodNullable<z.ZodObject<{
1638
+ overallSummary: z.ZodString;
1639
+ overallSeverity: z.ZodOptional<z.ZodEnum<{
1640
+ low: "low";
1641
+ medium: "medium";
1642
+ high: "high";
1643
+ none: "none";
1644
+ }>>;
1645
+ issues: z.ZodArray<z.ZodObject<{
1646
+ category: z.ZodEnum<{
1647
+ layout: "layout";
1648
+ color_contrast: "color_contrast";
1649
+ typography: "typography";
1650
+ clutter: "clutter";
1651
+ encoding: "encoding";
1652
+ labels_legends: "labels_legends";
1653
+ title_caption: "title_caption";
1654
+ other: "other";
1655
+ }>;
1656
+ severity: z.ZodEnum<{
1657
+ low: "low";
1658
+ medium: "medium";
1659
+ high: "high";
1660
+ info: "info";
1661
+ }>;
1662
+ observation: z.ZodString;
1663
+ rationale: z.ZodOptional<z.ZodString>;
1664
+ suggestedChange: z.ZodOptional<z.ZodString>;
1665
+ configPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
1666
+ }, z.core.$strip>>;
1667
+ }, z.core.$strip>>;
1668
+ chartVisionAudit: z.ZodDefault<z.ZodOptional<z.ZodNullable<z.ZodObject<{
1669
+ capturedAt: z.ZodString;
1670
+ chartId: z.ZodString;
1671
+ }, z.core.$strip>>>>;
1672
+ rubricScores: z.ZodDefault<z.ZodOptional<z.ZodNullable<z.ZodObject<{
1673
+ dataFidelity: z.ZodNumber;
1674
+ promptRelevance: z.ZodNumber;
1675
+ chartTypeAppropriateness: z.ZodNumber;
1676
+ readability: z.ZodNumber;
1677
+ honesty: z.ZodNumber;
1678
+ composite: z.ZodNumber;
1679
+ rationale: z.ZodOptional<z.ZodString>;
1680
+ }, z.core.$strip>>>>;
1681
+ }, z.core.$strip>;
1682
+ type JudgeResponse = z.infer<typeof JudgeResponseSchema>;
1192
1683
 
1193
1684
  /**
1194
1685
  * Client SDK for the Graphy AI Agents API.
@@ -1416,6 +1907,23 @@ declare class GraphyAiSdk {
1416
1907
  steps: string[];
1417
1908
  };
1418
1909
  config: _graphysdk_core_node.GraphConfig;
1910
+ mutationReceipt?: {
1911
+ steps: string[];
1912
+ rowCount: number;
1913
+ columnKeys: string[];
1914
+ postProcess?: {
1915
+ measureRelevance?: "prompt-named" | "derived" | "magnitude" | undefined;
1916
+ grain?: "remap-x" | "groupBy" | "reshape" | "compositeX" | undefined;
1917
+ chartType?: string | undefined;
1918
+ comparison?: string | undefined;
1919
+ } | undefined;
1920
+ droppedMeasures?: string[] | undefined;
1921
+ totalRowCountBeforeSlice?: number | undefined;
1922
+ displayedRowCount?: number | undefined;
1923
+ activeFilters?: string[] | undefined;
1924
+ grainSummary?: string | undefined;
1925
+ } | undefined;
1926
+ warnings?: string[] | undefined;
1419
1927
  }>;
1420
1928
  /**
1421
1929
  * Streams mutate agent events via SSE.
@@ -1431,6 +1939,113 @@ declare class GraphyAiSdk {
1431
1939
  steps: string[];
1432
1940
  };
1433
1941
  config: _graphysdk_core_node.GraphConfig;
1942
+ mutationReceipt?: {
1943
+ steps: string[];
1944
+ rowCount: number;
1945
+ columnKeys: string[];
1946
+ postProcess?: {
1947
+ measureRelevance?: "prompt-named" | "derived" | "magnitude" | undefined;
1948
+ grain?: "remap-x" | "groupBy" | "reshape" | "compositeX" | undefined;
1949
+ chartType?: string | undefined;
1950
+ comparison?: string | undefined;
1951
+ } | undefined;
1952
+ droppedMeasures?: string[] | undefined;
1953
+ totalRowCountBeforeSlice?: number | undefined;
1954
+ displayedRowCount?: number | undefined;
1955
+ activeFilters?: string[] | undefined;
1956
+ grainSummary?: string | undefined;
1957
+ } | undefined;
1958
+ warnings?: string[] | undefined;
1959
+ }>>>;
1960
+ /**
1961
+ * Runs an ordered agent pipeline (`POST /v0/pipeline`) on one shared server session.
1962
+ * Each stage receives accumulated reasoning from prior stages.
1963
+ */
1964
+ generatePipeline(data: GeneratePipelineParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
1965
+ response: {
1966
+ message: string;
1967
+ steps: string[];
1968
+ };
1969
+ config: _graphysdk_core_node.GraphConfig;
1970
+ reasoning: {
1971
+ agent: "explore" | "mutate" | "narrate" | "annotate";
1972
+ summary: string;
1973
+ steps?: string[] | undefined;
1974
+ }[];
1975
+ mutationReceipt?: {
1976
+ steps: string[];
1977
+ rowCount: number;
1978
+ columnKeys: string[];
1979
+ postProcess?: {
1980
+ measureRelevance?: "prompt-named" | "derived" | "magnitude" | undefined;
1981
+ grain?: "remap-x" | "groupBy" | "reshape" | "compositeX" | undefined;
1982
+ chartType?: string | undefined;
1983
+ comparison?: string | undefined;
1984
+ } | undefined;
1985
+ droppedMeasures?: string[] | undefined;
1986
+ totalRowCountBeforeSlice?: number | undefined;
1987
+ displayedRowCount?: number | undefined;
1988
+ activeFilters?: string[] | undefined;
1989
+ grainSummary?: string | undefined;
1990
+ } | undefined;
1991
+ warnings?: string[] | undefined;
1992
+ stories?: {
1993
+ topic: string;
1994
+ score: number;
1995
+ count: number;
1996
+ findings: {
1997
+ finding: string;
1998
+ confidence: number;
1999
+ relevance: number;
2000
+ topic: string;
2001
+ chartHint: string;
2002
+ chartFamily: "comparison" | "relationship" | "distribution" | "composition";
2003
+ evidenceSummary: string;
2004
+ }[];
2005
+ }[] | undefined;
2006
+ }>;
2007
+ generatePipelineStream(data: GeneratePipelineParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
2008
+ response: {
2009
+ message: string;
2010
+ steps: string[];
2011
+ };
2012
+ config: _graphysdk_core_node.GraphConfig;
2013
+ reasoning: {
2014
+ agent: "explore" | "mutate" | "narrate" | "annotate";
2015
+ summary: string;
2016
+ steps?: string[] | undefined;
2017
+ }[];
2018
+ mutationReceipt?: {
2019
+ steps: string[];
2020
+ rowCount: number;
2021
+ columnKeys: string[];
2022
+ postProcess?: {
2023
+ measureRelevance?: "prompt-named" | "derived" | "magnitude" | undefined;
2024
+ grain?: "remap-x" | "groupBy" | "reshape" | "compositeX" | undefined;
2025
+ chartType?: string | undefined;
2026
+ comparison?: string | undefined;
2027
+ } | undefined;
2028
+ droppedMeasures?: string[] | undefined;
2029
+ totalRowCountBeforeSlice?: number | undefined;
2030
+ displayedRowCount?: number | undefined;
2031
+ activeFilters?: string[] | undefined;
2032
+ grainSummary?: string | undefined;
2033
+ } | undefined;
2034
+ warnings?: string[] | undefined;
2035
+ stories?: {
2036
+ topic: string;
2037
+ score: number;
2038
+ count: number;
2039
+ findings: {
2040
+ finding: string;
2041
+ confidence: number;
2042
+ relevance: number;
2043
+ topic: string;
2044
+ chartHint: string;
2045
+ chartFamily: "comparison" | "relationship" | "distribution" | "composition";
2046
+ evidenceSummary: string;
2047
+ }[];
2048
+ }[] | undefined;
1434
2049
  }>>>;
1435
2050
  /**
1436
2051
  * Scores every supported chart type against the dataset in the provided `GraphConfig` and
@@ -1480,6 +2095,95 @@ declare class GraphyAiSdk {
1480
2095
  message: string;
1481
2096
  }[];
1482
2097
  }>;
2098
+ /**
2099
+ * Runs the chart judge on a chart and returns a structured critique. The judge is config-optional:
2100
+ * pass a `config`, a rendered `chartImage` (URL or `data:` URL), or both, plus an optional `data`
2101
+ * dataset for deterministic profiling. When a `rubric` is supplied, the response also carries a
2102
+ * numeric {@link RubricScores} scorecard — the single code path used by both product and benchmark.
2103
+ *
2104
+ * @remarks
2105
+ * - At least one of `config` / `chartImage` must be provided.
2106
+ * - Deterministic data-shape and (config-only) chart-type-fit issues are auto-seeded into
2107
+ * `critiqueReport.issues` in addition to the model's findings.
2108
+ * - Scoring is impartial: the model judges from the image + dataset, never from a config.
2109
+ *
2110
+ * @param data - Request body (`config?`, `chartImage?`, `data?`, `rubric?`, `userPrompt?`, metadata).
2111
+ * @param signal - Optional `AbortSignal` to cancel the request.
2112
+ * @returns The critique report, vision audit, and optional rubric scorecard.
2113
+ * @throws {GraphyApiError} When the API returns an error or the network request fails.
2114
+ */
2115
+ judge(data: JudgeParams, signal?: AbortSignal): Promise<{
2116
+ response: {
2117
+ message: string;
2118
+ steps: string[];
2119
+ critiqueCommitted: boolean;
2120
+ };
2121
+ critiqueReport: {
2122
+ overallSummary: string;
2123
+ issues: {
2124
+ category: "layout" | "color_contrast" | "typography" | "clutter" | "encoding" | "labels_legends" | "title_caption" | "other";
2125
+ severity: "low" | "medium" | "high" | "info";
2126
+ observation: string;
2127
+ rationale?: string | undefined;
2128
+ suggestedChange?: string | undefined;
2129
+ configPaths?: string[] | undefined;
2130
+ }[];
2131
+ overallSeverity?: "low" | "medium" | "high" | "none" | undefined;
2132
+ } | null;
2133
+ chartVisionAudit: {
2134
+ capturedAt: string;
2135
+ chartId: string;
2136
+ } | null;
2137
+ rubricScores: {
2138
+ dataFidelity: number;
2139
+ promptRelevance: number;
2140
+ chartTypeAppropriateness: number;
2141
+ readability: number;
2142
+ honesty: number;
2143
+ composite: number;
2144
+ rationale?: string | undefined;
2145
+ } | null;
2146
+ }>;
2147
+ /**
2148
+ * Streams chart-judge events via SSE. See {@link judge} for the request shape and semantics.
2149
+ *
2150
+ * @param data - Request body (`config?`, `chartImage?`, `data?`, `rubric?`, `userPrompt?`, metadata).
2151
+ * @param signal - Optional `AbortSignal` to cancel the request.
2152
+ * @returns An async iterator yielding {@link SSEEvent} objects.
2153
+ * @throws {GraphyApiError} When the API returns an error or the network request fails.
2154
+ */
2155
+ judgeStream(data: JudgeParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
2156
+ response: {
2157
+ message: string;
2158
+ steps: string[];
2159
+ critiqueCommitted: boolean;
2160
+ };
2161
+ critiqueReport: {
2162
+ overallSummary: string;
2163
+ issues: {
2164
+ category: "layout" | "color_contrast" | "typography" | "clutter" | "encoding" | "labels_legends" | "title_caption" | "other";
2165
+ severity: "low" | "medium" | "high" | "info";
2166
+ observation: string;
2167
+ rationale?: string | undefined;
2168
+ suggestedChange?: string | undefined;
2169
+ configPaths?: string[] | undefined;
2170
+ }[];
2171
+ overallSeverity?: "low" | "medium" | "high" | "none" | undefined;
2172
+ } | null;
2173
+ chartVisionAudit: {
2174
+ capturedAt: string;
2175
+ chartId: string;
2176
+ } | null;
2177
+ rubricScores: {
2178
+ dataFidelity: number;
2179
+ promptRelevance: number;
2180
+ chartTypeAppropriateness: number;
2181
+ readability: number;
2182
+ honesty: number;
2183
+ composite: number;
2184
+ rationale?: string | undefined;
2185
+ } | null;
2186
+ }>>>;
1483
2187
  /**
1484
2188
  * Runs the extract agent to build a chart-ready dataset from unstructured prose, images, and/or PDFs.
1485
2189
  *
@@ -1555,5 +2259,5 @@ declare class GraphyAiSdk {
1555
2259
  private wrapStreamWithStorytellingStripping;
1556
2260
  }
1557
2261
 
1558
- export { AggregationFunctionSchema, AggregationSuggestionSchema, AiChartTypeEnum, ChartFamilySchema, ChartFitEntrySchema, ChartFitFactorKindSchema, ChartFitFactorSchema, ChartFitVerdictSchema, DataObservationKindSchema, DataObservationSchema, EvaluateParamsSchema, EvaluateResponseSchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractAttachmentInputSchema, ExtractAttachmentKindSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeParamsSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, MAX_EXTRACT_ATTACHMENTS, MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES, MAX_EXTRACT_DOCUMENTS, MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES, MAX_EXTRACT_DOCUMENT_DECODED_BYTES, MAX_EXTRACT_IMAGES, MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES, MAX_EXTRACT_IMAGE_DECODED_BYTES, MAX_EXTRACT_SPREADSHEETS, MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES, MAX_EXTRACT_SPREADSHEET_DECODED_BYTES, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, buildImageAttachment, buildPdfAttachment, buildSpreadsheetAttachment, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
1559
- export type { AggregationFunction, AggregationSuggestion, AiChartType, ChartFamily, ChartFitEntry, ChartFitFactor, ChartFitFactorKind, ChartFitVerdict, 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, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, Logger, Metadata, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
2262
+ 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 };
2263
+ 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 };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{__awaiter as e,__asyncValues as t,__asyncGenerator as i,__await as n,__rest as r}from"tslib";import{z as s}from"zod";class a extends Error{constructor(e,t){var i;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(i=null==t?void 0:t.retryable)&&void 0!==i&&i}}const o=e=>e instanceof a,c=e=>"progress"===e.type,l=e=>"complete"===e.type,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,s){return e(this,void 0,void 0,function*(){var e,o,d,u,g;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const y=yield this.makeRequest(i,n,s),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var p,f=!0,b=t(this.parseSSE(y));!(e=(p=yield b.next()).done);f=!0){u=p.value,f=!1;const e=u;if(c(e)&&r&&r(e),l(e))return e.data;if(m(e)){const t=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(g=e.retryable)&&void 0!==g&&g})}}}catch(e){o={error:e}}finally{try{f||e||!(d=b.return)||(yield d.call(b))}finally{if(o)throw o.error}}const n=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${n}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-h;this.logger.debug(`${this.tag} Fetch completed: ${i} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return i(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let r="",s="",o="";try{for(;;){const{done:e,value:a}=yield n(t.read());if(e)break;r+=i.decode(a,{stream:!0});const c=r.split(/\r?\n/);r=c.pop()||"";for(const e of c)if(e.startsWith("event: "))s=e.slice(7).trim();else if(e.startsWith("data: "))o+=(o?"\n":"")+e.slice(6);else if(""===e.trim()&&o){try{const e=JSON.parse(o);let t;if("progress"===s){const i=e;t=Object.assign({type:"progress"},i)}else if("complete"===s)t={type:"complete",data:e};else if("error"===s){const i=e;t=Object.assign({type:"error"},i)}else if("preview"===s){const i=e;t=Object.assign(Object.assign({},i),{type:"preview"})}else{if("reasoning"!==s){s="",o="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield n(t),"complete"===s||"error"===s)return yield n(void 0)}catch(e){this.logger.warn("Invalid SSE data format",o)}s="",o=""}}}finally{t.releaseLock()}})}makeRequest(t,i,n){return e(this,arguments,void 0,function*(e,t,i,n=1,r="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const s=new URL(e,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${s}`);const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),l=()=>o.abort();i&&i.addEventListener("abort",l);try{const c=yield fetch(s,Object.assign({method:r,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:o.signal},"POST"===r&&{body:JSON.stringify(t)}));if(!c.ok){const s=c.status>=500||429===c.status;let o,l=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?l=t.message:"string"==typeof t.error&&(l=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const m=new a(l,{status:c.status,code:o,retryable:s});if(s&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${s}ms (attempt ${n+1})`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(s){if(s instanceof a)throw s;if(s instanceof Error&&"AbortError"===s.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),s;if(n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const s=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${s}ms`),yield this.sleep(s),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new a("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const h=s.enum(["EN_GB","EN_US"]),p=s.custom(e=>null!=e&&"object"==typeof e),f=s.enum(["low","medium","high"]),b=s.enum(["none","low","medium","high"]),y=s.enum(["agentic","fast"]),v=s.object({maxWallClockMs:s.number().positive().optional(),maxTotalTokens:s.number().int().positive().optional(),maxCostUsd:s.number().positive().optional()}),w=s.object({callId:s.string().max(256).optional(),locale:h.optional(),effort:f.optional(),storytellingEffort:b.optional().default("low"),budget:v.optional(),executionMode:y.optional()}),x=1e4,j=s.object({config:p,userPrompt:s.string().max(x).optional().default(""),metadata:w.optional()}),$=j.extend({maxSuggestionCount:s.number().int().min(1).max(4).optional()}),k=s.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),S=s.object({dataPrepPrompt:s.string(),chartType:k,summary:s.string()}),C=j.extend({userPrompt:s.string().max(x)}),T=s.object({response:s.object({message:s.string()}),config:p}),O=s.object({suggestions:s.array(S)}),E=s.enum(["comparison","relationship","distribution","composition"]),I=s.object({finding:s.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:s.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:s.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:s.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:s.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:E.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:s.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),P=s.object({topic:s.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:s.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:s.number().int().min(1).describe("Number of findings in this story."),findings:s.array(I).describe("Child findings, sorted by quadrant score desc.")}),R=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),stories:s.array(P)}),B=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),A=s.object({response:s.object({message:s.string(),steps:s.array(s.string())}),config:p}),U=s.enum(["high","medium","low"]),N=s.object({confidence:U,needsUserInput:s.boolean(),warnings:s.array(s.string()),cellConfidence:s.array(s.object({rowIndex:s.number().int().nonnegative(),columnKey:s.string(),confidence:U,quote:s.string().optional()})).optional()}),q=s.object({score:s.number().min(0).max(1),issues:s.array(s.string()),sufficient:s.boolean(),summary:s.string()}),D=5e5,F=8,K=2097152,M=7340032,L=2,G=6291456,W=8388608,z=2,H=G,J=W,_=12582912,Y=12;function Z(e){return 4*Math.ceil(e/3)}const Q=Z(K),V=Z(M),X=Z(G),ee=Z(W),te=Z(H),ie=Z(J),ne=Z(_);function re(e){return e.replace(/\s+/g,"")}function se(e){const t=re(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const ae=/^image\/(png|jpeg|jpg|webp|gif)$/i,oe=s.object({mimeType:s.string().min(1).refine(e=>ae.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:s.string().min(1).max(Q).refine(se,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ce=s.enum(["image","document","spreadsheet"]),le=oe.extend({kind:s.literal("image")}),me=s.object({kind:s.literal("document"),mimeType:s.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:s.string().min(1).max(X).refine(se,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),de=s.object({kind:s.literal("spreadsheet"),mimeType:s.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:s.string().min(1).max(te).refine(se,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:s.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),ue=s.discriminatedUnion("kind",[le,me,de]),ge=s.object({sourceText:s.string().max(D).default(""),images:s.array(oe).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:s.array(ue).max(12).optional(),metadata:w.optional()}).superRefine((e,t)=>{var i,n;const r=e.sourceText.trim(),s=null!==(i=e.images)&&void 0!==i?i:[],a=null!==(n=e.attachments)&&void 0!==n?n:[];if(s.length>0&&a.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===r.length&&0===s.length&&0===a.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(s.length>0){s.reduce((e,t)=>e+re(t.dataBase64).length,0)>V&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let o=0,c=0,l=0,m=0,d=0,u=0,g=0;for(const e of a){const t=re(e.dataBase64).length;switch(g+=t,e.kind){case"image":o+=1,m+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":l+=1,u+=t}}o>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),l>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const h=o<=8&&c<=2&&l<=2;a.length>0&&h&&(m>V&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ee&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>ie&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>ne&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function he(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:re(e.dataBase64)}}function pe(e){return{kind:"document",mimeType:"application/pdf",dataBase64:re(e.dataBase64)}}function fe(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:re(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const be=s.object({response:s.object({message:s.string()}),config:p,extractMeta:N.nullable(),lastAccuracyEvaluation:q.optional()}),ye=s.object({config:p,response:s.object({message:s.string(),steps:s.array(s.string())})}),ve=O,we=s.enum(["deal-breaker","pro","con","family","continuity"]),xe=s.object({kind:we,label:s.string(),weight:s.number(),reason:s.string()}),je=s.enum(["ok","disqualified"]),$e=s.object({rank:s.number().int().positive(),type:k,score:s.number(),verdict:je,factors:s.array(xe)}),ke=s.object({config:p,chartFamily:E.optional(),metadata:w.optional()}),Se=s.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"]),Ce=s.object({kind:Se,message:s.string()}),Te=s.enum(["sum","avg","count","min","max"]),Oe=s.object({dimensionName:s.string(),dimensionLabel:s.string(),measureName:s.string().nullable(),measureLabel:s.string().nullable(),fn:Te,chartType:k,score:s.number(),message:s.string()}),Ee=s.object({ranking:s.array($e),observations:s.array(Ce).optional().default([]),suggestions:s.array(Oe).optional().default([])}),Ie="/api/v0";class Pe{constructor(e){this.client=new g(e)}generateGraph(t,i,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,s=r(t,["storytellingOptions"]),a=yield this.client.fetch(`${Ie}/generate`,s,i,n),o=ye.parse(a);return this.stripStorytelling(o,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,n=r(t,["storytellingOptions"]),s=yield this.client.stream(`${Ie}/generate`,n,i);return this.wrapStreamWithStorytellingStripping(s,e)})}generateNarrative(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/narrate`,t,i,n);return T.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/suggestions`,t,i,n);return O.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/explore`,t,i,n);return R.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/annotate`,t,i,n);return B.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/mutate`,t,i,n);return A.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/mutate`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/evaluate`,t,void 0,i);return Ee.parse(e)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Ie}/extract`,t,i,n);return be.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${Ie}/extract`,t,i)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,r){return i(this,arguments,function*(){var i,s,a,o;try{for(var c,m=!0,d=t(e);!(i=(c=yield n(d.next())).done);m=!0){o=c.value,m=!1;const e=o;if(l(e)){const t=this.stripStorytelling(e.data,r);yield yield n(Object.assign(Object.assign({},e),{data:t}))}else yield yield n(e)}}catch(e){s={error:e}}finally{try{m||i||!(a=d.return)||(yield n(a.call(d)))}finally{if(s)throw s.error}}})}}export{Te as AggregationFunctionSchema,Oe as AggregationSuggestionSchema,k as AiChartTypeEnum,E as ChartFamilySchema,$e as ChartFitEntrySchema,we as ChartFitFactorKindSchema,xe as ChartFitFactorSchema,je as ChartFitVerdictSchema,Se as DataObservationKindSchema,Ce as DataObservationSchema,ke as EvaluateParamsSchema,Ee as EvaluateResponseSchema,y as ExecutionModeSchema,I as ExploreFindingSchema,P as ExploreStorySchema,q as ExtractAccuracyEvaluationSchema,ue as ExtractAttachmentInputSchema,ce as ExtractAttachmentKindSchema,U as ExtractConfidenceSchema,ge as ExtractFromProseParamsSchema,be as ExtractFromProseResponseSchema,N as ExtractMetaSchema,B as GenerateAnnotationsResponseSchema,R as GenerateExplorationResponseSchema,ye as GenerateGraphResponseSchema,ve as GenerateGraphSuggestionsResponseSchema,A as GenerateMutationResponseSchema,C as GenerateNarrativeParamsSchema,T as GenerateNarrativeResponseSchema,$ as GenerateSuggestionsParamsSchema,O as GenerateSuggestionsResponseSchema,j as GraphGenerationRequestSchema,Pe as GraphyAiSdk,a as GraphyApiError,v as InvocationBudgetSchema,f as InvocationEffortSchema,Y as MAX_EXTRACT_ATTACHMENTS,_ as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,L as MAX_EXTRACT_DOCUMENTS,W as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,G as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,F as MAX_EXTRACT_IMAGES,M as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,K as MAX_EXTRACT_IMAGE_DECODED_BYTES,z as MAX_EXTRACT_SPREADSHEETS,J as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,H as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,D as MAX_SOURCE_TEXT_LENGTH,x as MAX_USER_PROMPT_LENGTH,w as MetadataSchema,b as StorytellingEffortSchema,S as SuggestionSchema,he as buildImageAttachment,pe as buildPdfAttachment,fe as buildSpreadsheetAttachment,l as isCompleteEvent,m as isErrorEvent,o 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}}})}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){const a=c.status>=500||429===c.status;let s,l=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?l=t.message:"string"==typeof t.error&&(l=t.error),"string"==typeof t.code&&(s=t.code)}}catch(e){}const m=new o(l,{status:c.status,code:s,retryable:a});if(a&&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}) - ${l}`),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()}),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()}),R=a.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),P=a.object({dataPrepPrompt:a.string(),chartType:R,summary:a.string()}),I=T.extend({userPrompt:a.string().max(k),mutationReceipt:S.optional(),exploreFindingSummary:a.string().max(500).optional()}),E=a.object({response:a.object({message:a.string()}),config:h}),A=a.object({suggestions:a.array(P)}),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.")}),q=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),stories:a.array(F)});T.extend({mutationReceipt:S.optional()});const U=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h}),N=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,mutationReceipt:S.optional(),warnings:a.array(a.string()).optional()}),D=a.enum(["explore","mutate","narrate","annotate"]),K=a.object({agent:D,summary:a.string(),steps:a.array(a.string()).optional()}),M=T.extend({userPrompt:a.string().max(k),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=N.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,V=7340032,X=2,Y=6291456,Z=8388608,Q=2,ee=Y,te=Z,ie=12582912,ne=12;function re(e){return 4*Math.ceil(e/3)}const ae=re(J),oe=re(V),se=re(Y),ce=re(Z),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"]),Re=a.object({kind:Oe,label:a.string(),weight:a.number(),reason:a.string()}),Pe=a.enum(["ok","disqualified"]),Ie=a.object({rank:a.number().int().positive(),type:R,score:a.number(),verdict:Pe,factors:a.array(Re)}),Ee=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"]),qe=a.object({dimensionName:a.string(),dimensionLabel:a.string(),measureName:a.string().nullable(),measureLabel:a.string().nullable(),fn:Fe,chartType:R,score:a.number(),message:a.string()}),Ue=a.object({ranking:a.array(Ie),observations:a.array(Be).optional().default([]),suggestions:a.array(qe).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()}),De=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."}),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 E.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 q.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 U.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 N.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 Ue.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,qe as AggregationSuggestionSchema,R as AiChartTypeEnum,Ke as ChartCritiqueIssueCategorySchema,Le as ChartCritiqueIssueSchema,Me as ChartCritiqueIssueSeveritySchema,Ge as ChartCritiqueReportSchema,C as ChartFamilySchema,Ie as ChartFitEntrySchema,Oe as ChartFitFactorKindSchema,Re as ChartFitFactorSchema,Pe as ChartFitVerdictSchema,Ne as ChartJudgeRubricSchema,Ae as DataObservationKindSchema,Be as DataObservationSchema,Ee as EvaluateParamsSchema,Ue 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,U as GenerateAnnotationsResponseSchema,q as GenerateExplorationResponseSchema,Ce as GenerateGraphResponseSchema,Te as GenerateGraphSuggestionsResponseSchema,N as GenerateMutationResponseSchema,I as GenerateNarrativeParamsSchema,E 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,De 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,X as MAX_EXTRACT_DOCUMENTS,Z as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,Y as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,H as MAX_EXTRACT_IMAGES,V as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,J as MAX_EXTRACT_IMAGE_DECODED_BYTES,Q 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,D as PipelineAgentNameSchema,K as PipelineStageReasoningSchema,We as RubricScoresSchema,y as StorytellingEffortSchema,P 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};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@graphysdk/agents-sdk",
3
3
  "author": "Graphy",
4
- "version": "1.5.0",
4
+ "version": "1.6.0-beta.1780414747038",
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.5.0"
21
+ "@graphysdk/core": "1.6.0-beta.1780414747038"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@rollup/plugin-commonjs": "^28.0.6",