@graphysdk/agents-sdk 1.3.0-beta.1776260762546 → 1.3.0-beta.1776929171854

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 i=e=>"progress"===e.type,n=e=>"complete"===e.type,o=e=>"error"===e.type;class s{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 i(e)}static isCompleteEvent(e){return n(e)}static isErrorEvent(e){return o(e)}stream(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,i);return this.parseSSE(e)})}fetch(t,s,a,c){return e.__awaiter(this,void 0,void 0,function*(){var l,g,d,h,u;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,s,c),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var m,y=!0,f=e.__asyncValues(this.parseSSE(b));!(l=(m=yield f.next()).done);y=!0){h=m.value,y=!1;const e=h;if(i(e)&&a&&a(e),n(e))return e.data;if(o(e)){const i=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${t} ${i}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){g={error:e}}finally{try{y||l||!(d=f.return)||(yield d.call(f))}finally{if(g)throw g.error}}const s=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${s}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const i=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${i}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-p;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 i=t.body.getReader(),n=new TextDecoder;let o="",s="",a="";try{for(;;){const{done:t,value:r}=yield e.__await(i.read());if(t)break;o+=n.decode(r,{stream:!0});const c=o.split(/\r?\n/);o=c.pop()||"";for(const t of c)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))a+=(a?"\n":"")+t.slice(6);else if(""===t.trim()&&a){try{const t=JSON.parse(a);let r;if("progress"===s){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===s)r={type:"complete",data:t};else{if("error"!==s){s="",a="";continue}{const e=t;r=Object.assign({type:"error"},e)}}if(yield yield e.__await(r),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",a)}s="",a=""}}}finally{i.releaseLock()}})}makeRequest(t,i,n){return e.__awaiter(this,arguments,void 0,function*(e,t,i,n=1,o="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const s=new URL(e,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${s}`);const a=new AbortController,c=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();i&&i.addEventListener("abort",l);try{const c=yield fetch(s,Object.assign({method:o,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:a.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!c.ok){const s=c.status>=500||429===c.status;let a,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&&(a=t.code)}}catch(e){}const g=new r(l,{status:c.status,code:a,retryable:s});if(s&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${n+1})`),yield this.sleep(r),this.makeRequest(e,t,i,n+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),g}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(s){if(s instanceof r)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 r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,i,n+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new r("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const a=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),l=t.z.enum(["none","low","medium","high"]),g=t.z.object({maxWallClockMs:t.z.number().positive().optional(),maxTotalTokens:t.z.number().int().positive().optional(),maxCostUsd:t.z.number().positive().optional()}),d=t.z.object({callId:t.z.string().max(256),locale:a.optional(),storytellingEffort:l.optional().default("low"),budget:g.optional()}),h=t.z.object({config:c,userPrompt:t.z.string().max(1e4).optional().default(""),metadata:d.optional()}),u=h.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),p=t.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),m=t.z.object({dataPrepPrompt:t.z.string(),chartType:p,summary:t.z.string()}),y=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),f=t.z.object({suggestions:t.z.array(m)}),b=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 prescriptive recipe for a downstream mutate+chart agent: filter → group → aggregate → sort → render → highlight, naming real dataset columns."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),v=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(b).describe("Child findings, sorted by quadrant score desc.")}),w=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(v)}),_=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),S=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),z=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),x="/api/v0";exports.AiChartTypeEnum=p,exports.ExploreFindingSchema=b,exports.ExploreStorySchema=v,exports.GenerateAnnotationsResponseSchema=_,exports.GenerateExplorationResponseSchema=w,exports.GenerateGraphResponseSchema=z,exports.GenerateMutationResponseSchema=S,exports.GenerateNarrativeResponseSchema=y,exports.GenerateSuggestionsParamsSchema=u,exports.GenerateSuggestionsResponseSchema=f,exports.GraphGenerationRequestSchema=h,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:n}=t,o=e.__rest(t,["storytellingOptions"]),s=yield this.client.fetch(`${x}/generate`,o,r,i),a=z.parse(s);return this.stripStorytelling(a,n)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,n=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${x}/generate`,n,r);return this.wrapStreamWithStorytellingStripping(o,i)})}generateNarrative(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${x}/narrate`,t,r,i);return y.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${x}/narrate`,t,r)})}generateSuggestions(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${x}/suggestions`,t,r,i);return f.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${x}/suggestions`,t,r)})}generateExploration(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${x}/explore`,t,r,i);return w.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${x}/explore`,t,r)})}generateAnnotations(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${x}/annotate`,t,r,i);return _.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${x}/annotate`,t,r)})}generateMutation(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${x}/mutate`,t,r,i);return S.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${x}/mutate`,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 i,o,s,a;try{for(var c,l=!0,g=e.__asyncValues(t);!(i=(c=yield e.__await(g.next())).done);l=!0){a=c.value,l=!1;const t=a;if(n(t)){const i=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:i}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||i||!(s=g.return)||(yield e.__await(s.call(g)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=d,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=m,exports.isCompleteEvent=n,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof r,exports.isProgressEvent=i;
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 i=e=>"progress"===e.type,n=e=>"complete"===e.type,o=e=>"error"===e.type;class s{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 i(e)}static isCompleteEvent(e){return n(e)}static isErrorEvent(e){return o(e)}stream(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,i);return this.parseSSE(e)})}fetch(t,s,a,c){return e.__awaiter(this,void 0,void 0,function*(){var l,g,h,p,u;const d=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,s,c),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var m,f=!0,y=e.__asyncValues(this.parseSSE(b));!(l=(m=yield y.next()).done);f=!0){p=m.value,f=!1;const e=p;if(i(e)&&a&&a(e),n(e))return e.data;if(o(e)){const i=Date.now()-d;throw this.logger.error(`${this.tag} Server error: ${t} ${i}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){g={error:e}}finally{try{f||l||!(h=y.return)||(yield h.call(y))}finally{if(g)throw g.error}}const s=Date.now()-d;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${s}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const i=Date.now()-d;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${i}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-d;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 i=t.body.getReader(),n=new TextDecoder;let o="",s="",a="";try{for(;;){const{done:t,value:r}=yield e.__await(i.read());if(t)break;o+=n.decode(r,{stream:!0});const c=o.split(/\r?\n/);o=c.pop()||"";for(const t of c)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))a+=(a?"\n":"")+t.slice(6);else if(""===t.trim()&&a){try{const t=JSON.parse(a);let r;if("progress"===s){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===s)r={type:"complete",data:t};else if("error"===s){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===s){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==s){s="",a="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",a)}s="",a=""}}}finally{i.releaseLock()}})}makeRequest(t,i,n){return e.__awaiter(this,arguments,void 0,function*(e,t,i,n=1,o="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const s=new URL(e,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${s}`);const a=new AbortController,c=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();i&&i.addEventListener("abort",l);try{const c=yield fetch(s,Object.assign({method:o,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:a.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!c.ok){const s=c.status>=500||429===c.status;let a,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&&(a=t.code)}}catch(e){}const g=new r(l,{status:c.status,code:a,retryable:s});if(s&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${n+1})`),yield this.sleep(r),this.makeRequest(e,t,i,n+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),g}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(s){if(s instanceof r)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 r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,i,n+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,s),new r("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const a=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),l=t.z.enum(["low","medium","high"]),g=t.z.enum(["none","low","medium","high"]),h=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),locale:a.optional(),effort:l.optional(),storytellingEffort:g.optional().default("low"),budget:p.optional(),executionMode:h.optional()}),d=t.z.object({config:c,userPrompt:t.z.string().max(1e4).optional().default(""),metadata:u.optional()}),m=d.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),f=t.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),y=t.z.object({dataPrepPrompt:t.z.string(),chartType:f,summary:t.z.string()}),b=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),v=t.z.object({suggestions:t.z.array(y)}),w=t.z.enum(["comparison","relationship","distribution","composition"]),x=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:w.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.")}),z=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(x).describe("Child findings, sorted by quadrant score desc.")}),S=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(z)}),_=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),$=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),E=t.z.enum(["high","medium","low"]),j=t.z.object({confidence:E,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:E,quote:t.z.string().optional()})).optional()}),C=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),O=5e5,R=t.z.object({sourceText:t.z.string().min(1).max(O),metadata:u.optional()}),k=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:j.nullable(),lastAccuracyEvaluation:C.optional()}),G=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),T=v,P="/api/v0";exports.AiChartTypeEnum=f,exports.ChartFamilySchema=w,exports.ExecutionModeSchema=h,exports.ExploreFindingSchema=x,exports.ExploreStorySchema=z,exports.ExtractAccuracyEvaluationSchema=C,exports.ExtractConfidenceSchema=E,exports.ExtractFromProseParamsSchema=R,exports.ExtractFromProseResponseSchema=k,exports.ExtractMetaSchema=j,exports.GenerateAnnotationsResponseSchema=_,exports.GenerateExplorationResponseSchema=S,exports.GenerateGraphResponseSchema=G,exports.GenerateGraphSuggestionsResponseSchema=T,exports.GenerateMutationResponseSchema=$,exports.GenerateNarrativeResponseSchema=b,exports.GenerateSuggestionsParamsSchema=m,exports.GenerateSuggestionsResponseSchema=v,exports.GraphGenerationRequestSchema=d,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:n}=t,o=e.__rest(t,["storytellingOptions"]),s=yield this.client.fetch(`${P}/generate`,o,r,i),a=G.parse(s);return this.stripStorytelling(a,n)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,n=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${P}/generate`,n,r);return this.wrapStreamWithStorytellingStripping(o,i)})}generateNarrative(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${P}/narrate`,t,r,i);return b.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${P}/narrate`,t,r)})}generateSuggestions(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${P}/suggestions`,t,r,i);return v.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${P}/suggestions`,t,r)})}generateExploration(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${P}/explore`,t,r,i);return S.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${P}/explore`,t,r)})}generateAnnotations(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${P}/annotate`,t,r,i);return _.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${P}/annotate`,t,r)})}generateMutation(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${P}/mutate`,t,r,i);return $.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${P}/mutate`,t,r)})}extractFromProse(t,r,i){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${P}/extract`,t,r,i);return k.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${P}/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 i,o,s,a;try{for(var c,l=!0,g=e.__asyncValues(t);!(i=(c=yield e.__await(g.next())).done);l=!0){a=c.value,l=!1;const t=a;if(n(t)){const i=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:i}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||i||!(s=g.return)||(yield e.__await(s.call(g)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=p,exports.InvocationEffortSchema=l,exports.MAX_SOURCE_TEXT_LENGTH=O,exports.MAX_USER_PROMPT_LENGTH=1e4,exports.MetadataSchema=u,exports.StorytellingEffortSchema=g,exports.SuggestionSchema=y,exports.isCompleteEvent=n,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=i,exports.isReasoningEvent=e=>"reasoning"===e.type;
package/dist/index.d.ts CHANGED
@@ -4,15 +4,22 @@ import { z } from 'zod';
4
4
 
5
5
  /**
6
6
  * A progress update emitted during an SSE stream.
7
- * Indicates how far along the server-side operation has progressed.
7
+ *
8
+ * Emitted from two sources:
9
+ * - **Handler kickoff** (e.g. `"Generating..."`) — only carries `message`.
10
+ * - **Agent/tool loop** (via `emitProgress()`) — also carries `agentId`, `executionId`, `iteration`, and optional `metadata`.
8
11
  */
9
12
  interface ProgressEvent {
10
13
  /** Discriminant literal identifying this as a progress event. */
11
14
  type: 'progress';
12
- /** Completion percentage from 0 to 100. */
13
- percentage: number;
14
- /** Optional human-readable progress message. */
15
- message?: string;
15
+ /** Human-readable progress message. */
16
+ message: string;
17
+ /** Identifier of the agent emitting the progress (only on agent-emitted events). */
18
+ agentId?: string;
19
+ /** Identifier for the top-level invocation (only on agent-emitted events). */
20
+ executionId?: string;
21
+ /** Agent loop iteration (only on agent-emitted events). */
22
+ iteration?: number;
16
23
  /** Optional arbitrary metadata attached by the server. */
17
24
  metadata?: Record<string, JsonValue>;
18
25
  }
@@ -39,12 +46,38 @@ interface ErrorEvent {
39
46
  /** Whether the consumer should retry the request. */
40
47
  retryable?: boolean;
41
48
  }
49
+ /**
50
+ * A preview of the current agent state, emitted incrementally while work is in progress.
51
+ *
52
+ * The business payload is spread at the top level — its shape depends on the endpoint
53
+ * (e.g. `{ config }` for generate/mutate, `{ stories }` for explore).
54
+ */
55
+ interface PreviewEvent {
56
+ /** Agent-specific fields are spread at the top level. */
57
+ [key: string]: unknown;
58
+ /** Discriminant literal identifying this as a preview event. */
59
+ type: 'preview';
60
+ }
61
+ /**
62
+ * A reasoning/thinking message emitted by an agent or tool as it works.
63
+ */
64
+ interface ReasoningEvent {
65
+ /** Discriminant literal identifying this as a reasoning event. */
66
+ type: 'reasoning';
67
+ /** Identifier of the agent emitting the reasoning. */
68
+ agentId: string;
69
+ /** Identifier for the top-level invocation this event belongs to. */
70
+ executionId: string;
71
+ /** The reasoning message produced by the model. */
72
+ message: string;
73
+ }
42
74
  /**
43
75
  * Discriminated union of all SSE event types emitted during streaming operations.
44
- * Use the type guards {@link isProgressEvent}, {@link isCompleteEvent}, and
45
- * {@link isErrorEvent} to narrow the event type.
76
+ * Use the type guards {@link isProgressEvent}, {@link isCompleteEvent},
77
+ * {@link isErrorEvent}, {@link isPreviewEvent}, and {@link isReasoningEvent}
78
+ * to narrow the event type.
46
79
  */
47
- type SSEEvent<T> = ProgressEvent | CompleteEvent<T> | ErrorEvent;
80
+ type SSEEvent<T> = ProgressEvent | CompleteEvent<T> | ErrorEvent | PreviewEvent | ReasoningEvent;
48
81
  /**
49
82
  * Logger interface for SDK diagnostic output.
50
83
  * Falls back to `console` methods when not provided in {@link ClientConfig}.
@@ -162,13 +195,13 @@ declare const isGraphyApiError: (error: unknown) => error is GraphyApiError;
162
195
  * Narrows an SSE event to a {@link ProgressEvent}.
163
196
  *
164
197
  * @param event - The SSE event to check.
165
- * @returns `true` if the event is a progress event containing percentage and optional message.
198
+ * @returns `true` if the event is a progress event.
166
199
  *
167
200
  * @example
168
201
  * ```typescript
169
202
  * for await (const event of stream) {
170
203
  * if (isProgressEvent(event)) {
171
- * updateProgressBar(event.percentage);
204
+ * log(event.message);
172
205
  * }
173
206
  * }
174
207
  * ```
@@ -206,14 +239,59 @@ declare const isCompleteEvent: <T>(event: SSEEvent<T>) => event is CompleteEvent
206
239
  * ```
207
240
  */
208
241
  declare const isErrorEvent: <T>(event: SSEEvent<T>) => event is ErrorEvent;
242
+ /**
243
+ * Narrows an SSE event to a {@link PreviewEvent} containing an incremental agent state preview.
244
+ *
245
+ * @param event - The SSE event to check.
246
+ * @returns `true` if the event is a preview event.
247
+ *
248
+ * @example
249
+ * ```typescript
250
+ * for await (const event of stream) {
251
+ * if (isPreviewEvent(event)) {
252
+ * // Business data is spread at the top level, e.g. event.config or event.stories
253
+ * renderPartialState(event);
254
+ * }
255
+ * }
256
+ * ```
257
+ */
258
+ declare const isPreviewEvent: <T>(event: SSEEvent<T>) => event is PreviewEvent;
259
+ /**
260
+ * Narrows an SSE event to a {@link ReasoningEvent} containing an agent's reasoning message.
261
+ *
262
+ * @param event - The SSE event to check.
263
+ * @returns `true` if the event is a reasoning event.
264
+ *
265
+ * @example
266
+ * ```typescript
267
+ * for await (const event of stream) {
268
+ * if (isReasoningEvent(event)) {
269
+ * appendReasoning(event.message);
270
+ * }
271
+ * }
272
+ * ```
273
+ */
274
+ declare const isReasoningEvent: <T>(event: SSEEvent<T>) => event is ReasoningEvent;
209
275
 
276
+ declare const InvocationEffortSchema: z.ZodEnum<{
277
+ low: "low";
278
+ medium: "medium";
279
+ high: "high";
280
+ }>;
281
+ type InvocationEffort = z.infer<typeof InvocationEffortSchema>;
210
282
  declare const StorytellingEffortSchema: z.ZodEnum<{
211
- none: "none";
212
283
  low: "low";
213
284
  medium: "medium";
214
285
  high: "high";
286
+ none: "none";
215
287
  }>;
216
288
  type StorytellingEffort = z.infer<typeof StorytellingEffortSchema>;
289
+ /** Mirrors `ExecutionModeSchema` in `apps/agents-api/src/modules/agents/core/types/execution-mode.js`. */
290
+ declare const ExecutionModeSchema: z.ZodEnum<{
291
+ agentic: "agentic";
292
+ fast: "fast";
293
+ }>;
294
+ type ExecutionMode = z.infer<typeof ExecutionModeSchema>;
217
295
  /**
218
296
  * Optional per-request invocation budget. Mirrors `InvocationBudgetSchema` in
219
297
  * `apps/agents-api/src/modules/api/api.types.ts`. All fields are optional — the
@@ -235,17 +313,26 @@ declare const MetadataSchema: z.ZodObject<{
235
313
  EN_GB: "EN_GB";
236
314
  EN_US: "EN_US";
237
315
  }>>;
316
+ effort: z.ZodOptional<z.ZodEnum<{
317
+ low: "low";
318
+ medium: "medium";
319
+ high: "high";
320
+ }>>;
238
321
  storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
239
- none: "none";
240
322
  low: "low";
241
323
  medium: "medium";
242
324
  high: "high";
325
+ none: "none";
243
326
  }>>>;
244
327
  budget: z.ZodOptional<z.ZodObject<{
245
328
  maxWallClockMs: z.ZodOptional<z.ZodNumber>;
246
329
  maxTotalTokens: z.ZodOptional<z.ZodNumber>;
247
330
  maxCostUsd: z.ZodOptional<z.ZodNumber>;
248
331
  }, z.core.$strip>>;
332
+ executionMode: z.ZodOptional<z.ZodEnum<{
333
+ agentic: "agentic";
334
+ fast: "fast";
335
+ }>>;
249
336
  }, z.core.$strip>;
250
337
  type Metadata = z.infer<typeof MetadataSchema>;
251
338
  /** Mirrors `MAX_USER_PROMPT_LENGTH` in the agents-api request schema. */
@@ -264,17 +351,26 @@ declare const GraphGenerationRequestSchema: z.ZodObject<{
264
351
  EN_GB: "EN_GB";
265
352
  EN_US: "EN_US";
266
353
  }>>;
354
+ effort: z.ZodOptional<z.ZodEnum<{
355
+ low: "low";
356
+ medium: "medium";
357
+ high: "high";
358
+ }>>;
267
359
  storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
268
- none: "none";
269
360
  low: "low";
270
361
  medium: "medium";
271
362
  high: "high";
363
+ none: "none";
272
364
  }>>>;
273
365
  budget: z.ZodOptional<z.ZodObject<{
274
366
  maxWallClockMs: z.ZodOptional<z.ZodNumber>;
275
367
  maxTotalTokens: z.ZodOptional<z.ZodNumber>;
276
368
  maxCostUsd: z.ZodOptional<z.ZodNumber>;
277
369
  }, z.core.$strip>>;
370
+ executionMode: z.ZodOptional<z.ZodEnum<{
371
+ agentic: "agentic";
372
+ fast: "fast";
373
+ }>>;
278
374
  }, z.core.$strip>>;
279
375
  }, z.core.$strip>;
280
376
  type GraphGenerationRequest = z.input<typeof GraphGenerationRequestSchema>;
@@ -288,17 +384,26 @@ declare const GenerateSuggestionsParamsSchema: z.ZodObject<{
288
384
  EN_GB: "EN_GB";
289
385
  EN_US: "EN_US";
290
386
  }>>;
387
+ effort: z.ZodOptional<z.ZodEnum<{
388
+ low: "low";
389
+ medium: "medium";
390
+ high: "high";
391
+ }>>;
291
392
  storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
292
- none: "none";
293
393
  low: "low";
294
394
  medium: "medium";
295
395
  high: "high";
396
+ none: "none";
296
397
  }>>>;
297
398
  budget: z.ZodOptional<z.ZodObject<{
298
399
  maxWallClockMs: z.ZodOptional<z.ZodNumber>;
299
400
  maxTotalTokens: z.ZodOptional<z.ZodNumber>;
300
401
  maxCostUsd: z.ZodOptional<z.ZodNumber>;
301
402
  }, z.core.$strip>>;
403
+ executionMode: z.ZodOptional<z.ZodEnum<{
404
+ agentic: "agentic";
405
+ fast: "fast";
406
+ }>>;
302
407
  }, z.core.$strip>>;
303
408
  maxSuggestionCount: z.ZodOptional<z.ZodNumber>;
304
409
  }, z.core.$strip>;
@@ -385,6 +490,17 @@ declare const GenerateSuggestionsResponseSchema: z.ZodObject<{
385
490
  }, z.core.$strip>;
386
491
  type GenerateSuggestionsResponse = z.infer<typeof GenerateSuggestionsResponseSchema>;
387
492
  type GenerateExplorationParams = GraphGenerationRequest;
493
+ /**
494
+ * Abela chart family — classifies the question-shape a finding is answering. Downstream
495
+ * chart-generator picks the concrete chart type from this family + the data shape.
496
+ */
497
+ declare const ChartFamilySchema: z.ZodEnum<{
498
+ comparison: "comparison";
499
+ relationship: "relationship";
500
+ distribution: "distribution";
501
+ composition: "composition";
502
+ }>;
503
+ type ChartFamily = z.infer<typeof ChartFamilySchema>;
388
504
  /** A single structured finding produced by the explore agent. */
389
505
  declare const ExploreFindingSchema: z.ZodObject<{
390
506
  finding: z.ZodString;
@@ -392,6 +508,12 @@ declare const ExploreFindingSchema: z.ZodObject<{
392
508
  relevance: z.ZodNumber;
393
509
  topic: z.ZodString;
394
510
  chartHint: z.ZodString;
511
+ chartFamily: z.ZodEnum<{
512
+ comparison: "comparison";
513
+ relationship: "relationship";
514
+ distribution: "distribution";
515
+ composition: "composition";
516
+ }>;
395
517
  evidenceSummary: z.ZodString;
396
518
  }, z.core.$strip>;
397
519
  type ExploreFinding = z.infer<typeof ExploreFindingSchema>;
@@ -411,6 +533,12 @@ declare const ExploreStorySchema: z.ZodObject<{
411
533
  relevance: z.ZodNumber;
412
534
  topic: z.ZodString;
413
535
  chartHint: z.ZodString;
536
+ chartFamily: z.ZodEnum<{
537
+ comparison: "comparison";
538
+ relationship: "relationship";
539
+ distribution: "distribution";
540
+ composition: "composition";
541
+ }>;
414
542
  evidenceSummary: z.ZodString;
415
543
  }, z.core.$strip>>;
416
544
  }, z.core.$strip>;
@@ -430,6 +558,12 @@ declare const GenerateExplorationResponseSchema: z.ZodObject<{
430
558
  relevance: z.ZodNumber;
431
559
  topic: z.ZodString;
432
560
  chartHint: z.ZodString;
561
+ chartFamily: z.ZodEnum<{
562
+ comparison: "comparison";
563
+ relationship: "relationship";
564
+ distribution: "distribution";
565
+ composition: "composition";
566
+ }>;
433
567
  evidenceSummary: z.ZodString;
434
568
  }, z.core.$strip>>;
435
569
  }, z.core.$strip>>;
@@ -453,6 +587,108 @@ declare const GenerateMutationResponseSchema: z.ZodObject<{
453
587
  config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
454
588
  }, z.core.$strip>;
455
589
  type GenerateMutationResponse = z.infer<typeof GenerateMutationResponseSchema>;
590
+ /** Mirrors agents-api `extractConfidenceSchema`. */
591
+ declare const ExtractConfidenceSchema: z.ZodEnum<{
592
+ low: "low";
593
+ medium: "medium";
594
+ high: "high";
595
+ }>;
596
+ type ExtractConfidence = z.infer<typeof ExtractConfidenceSchema>;
597
+ /** Mirrors agents-api `ExtractMeta` (trust fields after `set_dataset_rows`). */
598
+ declare const ExtractMetaSchema: z.ZodObject<{
599
+ confidence: z.ZodEnum<{
600
+ low: "low";
601
+ medium: "medium";
602
+ high: "high";
603
+ }>;
604
+ needsUserInput: z.ZodBoolean;
605
+ warnings: z.ZodArray<z.ZodString>;
606
+ cellConfidence: z.ZodOptional<z.ZodArray<z.ZodObject<{
607
+ rowIndex: z.ZodNumber;
608
+ columnKey: z.ZodString;
609
+ confidence: z.ZodEnum<{
610
+ low: "low";
611
+ medium: "medium";
612
+ high: "high";
613
+ }>;
614
+ quote: z.ZodOptional<z.ZodString>;
615
+ }, z.core.$strip>>>;
616
+ }, z.core.$strip>;
617
+ type ExtractMeta = z.infer<typeof ExtractMetaSchema>;
618
+ /** Mirrors agents-api `ExtractAccuracyLlmSchema`. */
619
+ declare const ExtractAccuracyEvaluationSchema: z.ZodObject<{
620
+ score: z.ZodNumber;
621
+ issues: z.ZodArray<z.ZodString>;
622
+ sufficient: z.ZodBoolean;
623
+ summary: z.ZodString;
624
+ }, z.core.$strip>;
625
+ type ExtractAccuracyEvaluation = z.infer<typeof ExtractAccuracyEvaluationSchema>;
626
+ /** Mirrors `MAX_SOURCE_TEXT_LENGTH` in agents-api `extract/extract.types.ts`. */
627
+ declare const MAX_SOURCE_TEXT_LENGTH = 500000;
628
+ /** Request body for `POST /v0/extract`. Mirrors `ExtractFromProseRequestSchema`. */
629
+ declare const ExtractFromProseParamsSchema: z.ZodObject<{
630
+ sourceText: z.ZodString;
631
+ metadata: z.ZodOptional<z.ZodObject<{
632
+ callId: z.ZodString;
633
+ locale: z.ZodOptional<z.ZodEnum<{
634
+ EN_GB: "EN_GB";
635
+ EN_US: "EN_US";
636
+ }>>;
637
+ effort: z.ZodOptional<z.ZodEnum<{
638
+ low: "low";
639
+ medium: "medium";
640
+ high: "high";
641
+ }>>;
642
+ storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
643
+ low: "low";
644
+ medium: "medium";
645
+ high: "high";
646
+ none: "none";
647
+ }>>>;
648
+ budget: z.ZodOptional<z.ZodObject<{
649
+ maxWallClockMs: z.ZodOptional<z.ZodNumber>;
650
+ maxTotalTokens: z.ZodOptional<z.ZodNumber>;
651
+ maxCostUsd: z.ZodOptional<z.ZodNumber>;
652
+ }, z.core.$strip>>;
653
+ executionMode: z.ZodOptional<z.ZodEnum<{
654
+ agentic: "agentic";
655
+ fast: "fast";
656
+ }>>;
657
+ }, z.core.$strip>>;
658
+ }, z.core.$strip>;
659
+ type ExtractFromProseParams = z.input<typeof ExtractFromProseParamsSchema>;
660
+ declare const ExtractFromProseResponseSchema: z.ZodObject<{
661
+ response: z.ZodObject<{
662
+ message: z.ZodString;
663
+ }, z.core.$strip>;
664
+ config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
665
+ extractMeta: z.ZodNullable<z.ZodObject<{
666
+ confidence: z.ZodEnum<{
667
+ low: "low";
668
+ medium: "medium";
669
+ high: "high";
670
+ }>;
671
+ needsUserInput: z.ZodBoolean;
672
+ warnings: z.ZodArray<z.ZodString>;
673
+ cellConfidence: z.ZodOptional<z.ZodArray<z.ZodObject<{
674
+ rowIndex: z.ZodNumber;
675
+ columnKey: z.ZodString;
676
+ confidence: z.ZodEnum<{
677
+ low: "low";
678
+ medium: "medium";
679
+ high: "high";
680
+ }>;
681
+ quote: z.ZodOptional<z.ZodString>;
682
+ }, z.core.$strip>>>;
683
+ }, z.core.$strip>>;
684
+ lastAccuracyEvaluation: z.ZodOptional<z.ZodObject<{
685
+ score: z.ZodNumber;
686
+ issues: z.ZodArray<z.ZodString>;
687
+ sufficient: z.ZodBoolean;
688
+ summary: z.ZodString;
689
+ }, z.core.$strip>>;
690
+ }, z.core.$strip>;
691
+ type ExtractFromProseResponse = z.infer<typeof ExtractFromProseResponseSchema>;
456
692
  interface StorytellingOptions {
457
693
  excludeTitle?: boolean;
458
694
  excludeSubtitle?: boolean;
@@ -469,13 +705,45 @@ declare const GenerateGraphResponseSchema: z.ZodObject<{
469
705
  }, z.core.$strip>;
470
706
  }, z.core.$strip>;
471
707
  type GenerateGraphResponse = z.infer<typeof GenerateGraphResponseSchema>;
708
+ /** @deprecated Use {@link GenerateSuggestionsParams} instead. */
709
+ type GenerateGraphSuggestionsParams = GenerateSuggestionsParams;
710
+ /** @deprecated Use {@link GenerateSuggestionsResponse} instead. */
711
+ type GenerateGraphSuggestionsResponse = GenerateSuggestionsResponse;
712
+ /** @deprecated Use {@link GenerateSuggestionsResponseSchema} instead. */
713
+ declare const GenerateGraphSuggestionsResponseSchema: z.ZodObject<{
714
+ suggestions: z.ZodArray<z.ZodObject<{
715
+ dataPrepPrompt: z.ZodString;
716
+ chartType: z.ZodEnum<{
717
+ line: "line";
718
+ bar: "bar";
719
+ groupedBar: "groupedBar";
720
+ stackedBar: "stackedBar";
721
+ "100StackedBar": "100StackedBar";
722
+ column: "column";
723
+ groupedColumn: "groupedColumn";
724
+ stackedColumn: "stackedColumn";
725
+ "100StackedColumn": "100StackedColumn";
726
+ combo: "combo";
727
+ pie: "pie";
728
+ donut: "donut";
729
+ funnel: "funnel";
730
+ heatmap: "heatmap";
731
+ scatter: "scatter";
732
+ bubble: "bubble";
733
+ waterfall: "waterfall";
734
+ table: "table";
735
+ }>;
736
+ summary: z.ZodString;
737
+ }, z.core.$strip>>;
738
+ }, z.core.$strip>;
472
739
 
473
740
  /**
474
741
  * Client SDK for the Graphy AI Agents API.
475
742
  *
476
743
  * Provides methods for AI-powered chart generation, narrative text creation,
477
- * and prompt suggestions. Each method has a request-response variant and a
478
- * streaming variant returning an `AsyncIterableIterator` of SSE events.
744
+ * prompt suggestions, exploration, annotations, mutation, and prose-to-dataset
745
+ * extraction. Each method has a request-response variant and a streaming variant
746
+ * returning an `AsyncIterableIterator` of SSE events.
479
747
  *
480
748
  * @example
481
749
  * ```typescript
@@ -614,6 +882,7 @@ declare class GraphyAiSdk {
614
882
  relevance: number;
615
883
  topic: string;
616
884
  chartHint: string;
885
+ chartFamily: "comparison" | "relationship" | "distribution" | "composition";
617
886
  evidenceSummary: string;
618
887
  }[];
619
888
  }[];
@@ -641,6 +910,7 @@ declare class GraphyAiSdk {
641
910
  relevance: number;
642
911
  topic: string;
643
912
  chartHint: string;
913
+ chartFamily: "comparison" | "relationship" | "distribution" | "composition";
644
914
  evidenceSummary: string;
645
915
  }[];
646
916
  }[];
@@ -709,9 +979,72 @@ declare class GraphyAiSdk {
709
979
  };
710
980
  config: _graphysdk_core_node.GraphConfig;
711
981
  }>>>;
982
+ /**
983
+ * Runs the extract agent to build a chart-ready dataset from unstructured prose.
984
+ *
985
+ * @param data - Parameters including `sourceText` and optional request metadata.
986
+ * @param onProgress - Optional callback invoked with progress updates.
987
+ * @param signal - Optional `AbortSignal` to cancel the request.
988
+ * @returns The updated chart config, extraction trust metadata, and optional accuracy audit.
989
+ * @throws {GraphyApiError} When the API returns an error or the network request fails.
990
+ */
991
+ extractFromProse(data: ExtractFromProseParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
992
+ response: {
993
+ message: string;
994
+ };
995
+ config: _graphysdk_core_node.GraphConfig;
996
+ extractMeta: {
997
+ confidence: "low" | "medium" | "high";
998
+ needsUserInput: boolean;
999
+ warnings: string[];
1000
+ cellConfidence?: {
1001
+ rowIndex: number;
1002
+ columnKey: string;
1003
+ confidence: "low" | "medium" | "high";
1004
+ quote?: string | undefined;
1005
+ }[] | undefined;
1006
+ } | null;
1007
+ lastAccuracyEvaluation?: {
1008
+ score: number;
1009
+ issues: string[];
1010
+ sufficient: boolean;
1011
+ summary: string;
1012
+ } | undefined;
1013
+ }>;
1014
+ /**
1015
+ * Streams extract-agent events via SSE.
1016
+ *
1017
+ * @param data - Parameters including `sourceText` and optional request metadata.
1018
+ * @param signal - Optional `AbortSignal` to cancel the request.
1019
+ * @returns An async iterator yielding {@link SSEEvent} objects.
1020
+ * @throws {GraphyApiError} When the API returns an error or the network request fails.
1021
+ */
1022
+ extractFromProseStream(data: ExtractFromProseParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
1023
+ response: {
1024
+ message: string;
1025
+ };
1026
+ config: _graphysdk_core_node.GraphConfig;
1027
+ extractMeta: {
1028
+ confidence: "low" | "medium" | "high";
1029
+ needsUserInput: boolean;
1030
+ warnings: string[];
1031
+ cellConfidence?: {
1032
+ rowIndex: number;
1033
+ columnKey: string;
1034
+ confidence: "low" | "medium" | "high";
1035
+ quote?: string | undefined;
1036
+ }[] | undefined;
1037
+ } | null;
1038
+ lastAccuracyEvaluation?: {
1039
+ score: number;
1040
+ issues: string[];
1041
+ sufficient: boolean;
1042
+ summary: string;
1043
+ } | undefined;
1044
+ }>>>;
712
1045
  private stripStorytelling;
713
1046
  private wrapStreamWithStorytellingStripping;
714
1047
  }
715
1048
 
716
- export { AiChartTypeEnum, ExploreFindingSchema, ExploreStorySchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, isCompleteEvent, isErrorEvent, isGraphyApiError, isProgressEvent };
717
- export type { AiChartType, ClientConfig, CompleteEvent, ErrorEvent, ExploreFinding, ExploreStory, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, Logger, Metadata, ProgressEvent, ProgressHandler, RetryConfig, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
1049
+ export { AiChartTypeEnum, ChartFamilySchema, ExecutionModeSchema, ExploreFindingSchema, ExploreStorySchema, ExtractAccuracyEvaluationSchema, ExtractConfidenceSchema, ExtractFromProseParamsSchema, ExtractFromProseResponseSchema, ExtractMetaSchema, GenerateAnnotationsResponseSchema, GenerateExplorationResponseSchema, GenerateGraphResponseSchema, GenerateGraphSuggestionsResponseSchema, GenerateMutationResponseSchema, GenerateNarrativeResponseSchema, GenerateSuggestionsParamsSchema, GenerateSuggestionsResponseSchema, GraphGenerationRequestSchema, GraphyAiSdk, GraphyApiError, InvocationBudgetSchema, InvocationEffortSchema, MAX_SOURCE_TEXT_LENGTH, MAX_USER_PROMPT_LENGTH, MetadataSchema, StorytellingEffortSchema, SuggestionSchema, isCompleteEvent, isErrorEvent, isGraphyApiError, isPreviewEvent, isProgressEvent, isReasoningEvent };
1050
+ export type { AiChartType, ChartFamily, ClientConfig, CompleteEvent, ErrorEvent, ExecutionMode, ExploreFinding, ExploreStory, ExtractAccuracyEvaluation, ExtractConfidence, ExtractFromProseParams, ExtractFromProseResponse, ExtractMeta, GenerateAnnotationsParams, GenerateAnnotationsResponse, GenerateExplorationParams, GenerateExplorationResponse, GenerateGraphParams, GenerateGraphResponse, GenerateGraphSuggestionsParams, GenerateGraphSuggestionsResponse, GenerateMutationParams, GenerateMutationResponse, GenerateNarrativeParams, GenerateNarrativeResponse, GenerateSuggestionsParams, GenerateSuggestionsResponse, GraphGenerationRequest, GraphyApiErrorOptions, InvocationBudget, InvocationEffort, Logger, Metadata, PreviewEvent, ProgressEvent, ProgressHandler, ReasoningEvent, RetryConfig, SSEEvent, StorytellingEffort, StorytellingOptions, Suggestion };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as i,__rest as n}from"tslib";import{z as o}from"zod";class s extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const a=t=>t instanceof s,c=t=>"progress"===t.type,l=t=>"complete"===t.type,g=t=>"error"===t.type;class d{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return c(t)}static isCompleteEvent(t){return l(t)}static isErrorEvent(t){return g(t)}stream(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,i);return this.parseSSE(t)})}fetch(r,i,n,o){return t(this,void 0,void 0,function*(){var t,a,d,u,h;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${r}`);try{const b=yield this.makeRequest(r,i,o),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var m,f=!0,y=e(this.parseSSE(b));!(t=(m=yield y.next()).done);f=!0){u=m.value,f=!1;const t=u;if(c(t)&&n&&n(t),l(t))return t.data;if(g(t)){const e=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${r} ${e}ms`,t.error),new s(t.error,{code:t.code,retryable:null!==(h=t.retryable)&&void 0!==h&&h})}}}catch(t){a={error:t}}finally{try{f||t||!(d=y.return)||(yield d.call(y))}finally{if(a)throw a.error}}const i=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${i}ms`),new s("Stream ended without completion")}return yield b.json()}catch(t){const e=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${r} ${e}ms`,t),t instanceof s)throw t;throw t}finally{const t=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${r} ${t}ms`)}})}ping(){return t(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(t){return r(this,arguments,function*(){if(!t.body)throw new s("Response body is null");const e=t.body.getReader(),r=new TextDecoder;let n="",o="",a="";try{for(;;){const{done:t,value:s}=yield i(e.read());if(t)break;n+=r.decode(s,{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: "))a+=(a?"\n":"")+t.slice(6);else if(""===t.trim()&&a){try{const t=JSON.parse(a);let e;if("progress"===o){const r=t;e=Object.assign({type:"progress"},r)}else if("complete"===o)e={type:"complete",data:t};else{if("error"!==o){o="",a="";continue}{const r=t;e=Object.assign({type:"error"},r)}}if(yield yield i(e),"complete"===o||"error"===o)return yield i(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}o="",a=""}}}finally{e.releaseLock()}})}makeRequest(e,r,i){return t(this,arguments,void 0,function*(t,e,r,i=1,n="POST"){if(!t.startsWith("/"))throw new s("Invalid endpoint: must start with /");const o=new URL(t,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new s("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${o}`);const a=new AbortController,c=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();r&&r.addEventListener("abort",l);try{const c=yield fetch(o,Object.assign({method:n,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:a.signal},"POST"===n&&{body:JSON.stringify(e)}));if(!c.ok){const o=c.status>=500||429===c.status;let a,l=`HTTP ${c.status}`;try{const t=yield c.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?l=e.message:"string"==typeof e.error&&(l=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new s(l,{status:c.status,code:a,retryable:o});if(o&&i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${o}ms (attempt ${i+1})`),yield this.sleep(o),this.makeRequest(t,e,r,i+1,n)}throw this.logger.error(`${this.tag} Request failed: ${t} (${c.status}) - ${l}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),c}catch(o){if(o instanceof s)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),o;if(i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${o}ms`),yield this.sleep(o),this.makeRequest(t,e,r,i+1,n)}throw this.logger.error(`${this.tag} Network error: ${t}`,o),new s("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",l)}})}}const u=o.enum(["EN_GB","EN_US"]),h=o.custom(t=>null!=t&&"object"==typeof t),p=o.enum(["none","low","medium","high"]),m=o.object({maxWallClockMs:o.number().positive().optional(),maxTotalTokens:o.number().int().positive().optional(),maxCostUsd:o.number().positive().optional()}),f=o.object({callId:o.string().max(256),locale:u.optional(),storytellingEffort:p.optional().default("low"),budget:m.optional()}),y=1e4,b=o.object({config:h,userPrompt:o.string().max(1e4).optional().default(""),metadata:f.optional()}),v=b.extend({maxSuggestionCount:o.number().int().min(1).max(4).optional()}),w=o.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),$=o.object({dataPrepPrompt:o.string(),chartType:w,summary:o.string()}),S=o.object({response:o.object({message:o.string()}),config:h}),j=o.object({suggestions:o.array($)}),x=o.object({finding:o.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:o.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:o.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:o.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:o.string().min(1).max(240).describe("Natural-language prescriptive recipe for a downstream mutate+chart agent: filter → group → aggregate → sort → render → highlight, naming real dataset columns."),evidenceSummary:o.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),k=o.object({topic:o.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:o.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:o.number().int().min(1).describe("Number of findings in this story."),findings:o.array(x).describe("Child findings, sorted by quadrant score desc.")}),C=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),stories:o.array(k)}),E=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),config:h}),O=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),config:h}),R=o.object({config:h,response:o.object({message:o.string(),steps:o.array(o.string())})}),T="/api/v0";class q{constructor(t){this.client=new d(t)}generateGraph(e,r,i){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,o=n(e,["storytellingOptions"]),s=yield this.client.fetch(`${T}/generate`,o,r,i),a=R.parse(s);return this.stripStorytelling(a,t)})}generateGraphStream(e,r){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,i=n(e,["storytellingOptions"]),o=yield this.client.stream(`${T}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(o,t)})}generateNarrative(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${T}/narrate`,e,r,i);return S.parse(t)})}generateNarrativeStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${T}/narrate`,e,r)})}generateSuggestions(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${T}/suggestions`,e,r,i);return j.parse(t)})}generateSuggestionsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${T}/suggestions`,e,r)})}generateExploration(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${T}/explore`,e,r,i);return C.parse(t)})}generateExplorationStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${T}/explore`,e,r)})}generateAnnotations(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${T}/annotate`,e,r,i);return E.parse(t)})}generateAnnotationsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${T}/annotate`,e,r)})}generateMutation(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${T}/mutate`,e,r,i);return O.parse(t)})}generateMutationStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${T}/mutate`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(t,n){return r(this,arguments,function*(){var r,o,s,a;try{for(var c,g=!0,d=e(t);!(r=(c=yield i(d.next())).done);g=!0){a=c.value,g=!1;const t=a;if(l(t)){const e=this.stripStorytelling(t.data,n);yield yield i(Object.assign(Object.assign({},t),{data:e}))}else yield yield i(t)}}catch(t){o={error:t}}finally{try{g||r||!(s=d.return)||(yield i(s.call(d)))}finally{if(o)throw o.error}}})}}export{w as AiChartTypeEnum,x as ExploreFindingSchema,k as ExploreStorySchema,E as GenerateAnnotationsResponseSchema,C as GenerateExplorationResponseSchema,R as GenerateGraphResponseSchema,O as GenerateMutationResponseSchema,S as GenerateNarrativeResponseSchema,v as GenerateSuggestionsParamsSchema,j as GenerateSuggestionsResponseSchema,b as GraphGenerationRequestSchema,q as GraphyAiSdk,s as GraphyApiError,m as InvocationBudgetSchema,y as MAX_USER_PROMPT_LENGTH,f as MetadataSchema,p as StorytellingEffortSchema,$ as SuggestionSchema,l as isCompleteEvent,g as isErrorEvent,a as isGraphyApiError,c as isProgressEvent};
1
+ import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as i,__rest as n}from"tslib";import{z as o}from"zod";class s extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const a=t=>t instanceof s,c=t=>"progress"===t.type,l=t=>"complete"===t.type,g=t=>"error"===t.type,d=t=>"preview"===t.type,u=t=>"reasoning"===t.type;class h{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return c(t)}static isCompleteEvent(t){return l(t)}static isErrorEvent(t){return g(t)}stream(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,i);return this.parseSSE(t)})}fetch(r,i,n,o){return t(this,void 0,void 0,function*(){var t,a,d,u,h;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${r}`);try{const b=yield this.makeRequest(r,i,o),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var m,f=!0,y=e(this.parseSSE(b));!(t=(m=yield y.next()).done);f=!0){u=m.value,f=!1;const t=u;if(c(t)&&n&&n(t),l(t))return t.data;if(g(t)){const e=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${r} ${e}ms`,t.error),new s(t.error,{code:t.code,retryable:null!==(h=t.retryable)&&void 0!==h&&h})}}}catch(t){a={error:t}}finally{try{f||t||!(d=y.return)||(yield d.call(y))}finally{if(a)throw a.error}}const i=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${i}ms`),new s("Stream ended without completion")}return yield b.json()}catch(t){const e=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${r} ${e}ms`,t),t instanceof s)throw t;throw t}finally{const t=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${r} ${t}ms`)}})}ping(){return t(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(t){return r(this,arguments,function*(){if(!t.body)throw new s("Response body is null");const e=t.body.getReader(),r=new TextDecoder;let n="",o="",a="";try{for(;;){const{done:t,value:s}=yield i(e.read());if(t)break;n+=r.decode(s,{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: "))a+=(a?"\n":"")+t.slice(6);else if(""===t.trim()&&a){try{const t=JSON.parse(a);let e;if("progress"===o){const r=t;e=Object.assign({type:"progress"},r)}else if("complete"===o)e={type:"complete",data:t};else if("error"===o){const r=t;e=Object.assign({type:"error"},r)}else if("preview"===o){const r=t;e=Object.assign(Object.assign({},r),{type:"preview"})}else{if("reasoning"!==o){o="",a="";continue}{const r=t;e=Object.assign(Object.assign({},r),{type:"reasoning"})}}if(yield yield i(e),"complete"===o||"error"===o)return yield i(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}o="",a=""}}}finally{e.releaseLock()}})}makeRequest(e,r,i){return t(this,arguments,void 0,function*(t,e,r,i=1,n="POST"){if(!t.startsWith("/"))throw new s("Invalid endpoint: must start with /");const o=new URL(t,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new s("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${o}`);const a=new AbortController,c=setTimeout(()=>a.abort(),this.timeout),l=()=>a.abort();r&&r.addEventListener("abort",l);try{const c=yield fetch(o,Object.assign({method:n,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:a.signal},"POST"===n&&{body:JSON.stringify(e)}));if(!c.ok){const o=c.status>=500||429===c.status;let a,l=`HTTP ${c.status}`;try{const t=yield c.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?l=e.message:"string"==typeof e.error&&(l=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new s(l,{status:c.status,code:a,retryable:o});if(o&&i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${o}ms (attempt ${i+1})`),yield this.sleep(o),this.makeRequest(t,e,r,i+1,n)}throw this.logger.error(`${this.tag} Request failed: ${t} (${c.status}) - ${l}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),c}catch(o){if(o instanceof s)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),o;if(i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${o}ms`),yield this.sleep(o),this.makeRequest(t,e,r,i+1,n)}throw this.logger.error(`${this.tag} Network error: ${t}`,o),new s("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",l)}})}}const p=o.enum(["EN_GB","EN_US"]),m=o.custom(t=>null!=t&&"object"==typeof t),f=o.enum(["low","medium","high"]),y=o.enum(["none","low","medium","high"]),b=o.enum(["agentic","fast"]),v=o.object({maxWallClockMs:o.number().positive().optional(),maxTotalTokens:o.number().int().positive().optional(),maxCostUsd:o.number().positive().optional()}),w=o.object({callId:o.string().max(256),locale:p.optional(),effort:f.optional(),storytellingEffort:y.optional().default("low"),budget:v.optional(),executionMode:b.optional()}),$=1e4,j=o.object({config:m,userPrompt:o.string().max(1e4).optional().default(""),metadata:w.optional()}),S=j.extend({maxSuggestionCount:o.number().int().min(1).max(4).optional()}),x=o.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table"]),O=o.object({dataPrepPrompt:o.string(),chartType:x,summary:o.string()}),k=o.object({response:o.object({message:o.string()}),config:m}),C=o.object({suggestions:o.array(O)}),E=o.enum(["comparison","relationship","distribution","composition"]),R=o.object({finding:o.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:o.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:o.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:o.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:o.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:o.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),T=o.object({topic:o.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:o.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:o.number().int().min(1).describe("Number of findings in this story."),findings:o.array(R).describe("Child findings, sorted by quadrant score desc.")}),P=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),stories:o.array(T)}),q=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),config:m}),A=o.object({response:o.object({message:o.string(),steps:o.array(o.string())}),config:m}),N=o.enum(["high","medium","low"]),U=o.object({confidence:N,needsUserInput:o.boolean(),warnings:o.array(o.string()),cellConfidence:o.array(o.object({rowIndex:o.number().int().nonnegative(),columnKey:o.string(),confidence:N,quote:o.string().optional()})).optional()}),D=o.object({score:o.number().min(0).max(1),issues:o.array(o.string()),sufficient:o.boolean(),summary:o.string()}),K=5e5,I=o.object({sourceText:o.string().min(1).max(K),metadata:w.optional()}),M=o.object({response:o.object({message:o.string()}),config:m,extractMeta:U.nullable(),lastAccuracyEvaluation:D.optional()}),F=o.object({config:m,response:o.object({message:o.string(),steps:o.array(o.string())})}),G=C,L="/api/v0";class W{constructor(t){this.client=new h(t)}generateGraph(e,r,i){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,o=n(e,["storytellingOptions"]),s=yield this.client.fetch(`${L}/generate`,o,r,i),a=F.parse(s);return this.stripStorytelling(a,t)})}generateGraphStream(e,r){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,i=n(e,["storytellingOptions"]),o=yield this.client.stream(`${L}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(o,t)})}generateNarrative(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${L}/narrate`,e,r,i);return k.parse(t)})}generateNarrativeStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${L}/narrate`,e,r)})}generateSuggestions(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${L}/suggestions`,e,r,i);return C.parse(t)})}generateSuggestionsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${L}/suggestions`,e,r)})}generateExploration(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${L}/explore`,e,r,i);return P.parse(t)})}generateExplorationStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${L}/explore`,e,r)})}generateAnnotations(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${L}/annotate`,e,r,i);return q.parse(t)})}generateAnnotationsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${L}/annotate`,e,r)})}generateMutation(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${L}/mutate`,e,r,i);return A.parse(t)})}generateMutationStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${L}/mutate`,e,r)})}extractFromProse(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${L}/extract`,e,r,i);return M.parse(t)})}extractFromProseStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${L}/extract`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(t,n){return r(this,arguments,function*(){var r,o,s,a;try{for(var c,g=!0,d=e(t);!(r=(c=yield i(d.next())).done);g=!0){a=c.value,g=!1;const t=a;if(l(t)){const e=this.stripStorytelling(t.data,n);yield yield i(Object.assign(Object.assign({},t),{data:e}))}else yield yield i(t)}}catch(t){o={error:t}}finally{try{g||r||!(s=d.return)||(yield i(s.call(d)))}finally{if(o)throw o.error}}})}}export{x as AiChartTypeEnum,E as ChartFamilySchema,b as ExecutionModeSchema,R as ExploreFindingSchema,T as ExploreStorySchema,D as ExtractAccuracyEvaluationSchema,N as ExtractConfidenceSchema,I as ExtractFromProseParamsSchema,M as ExtractFromProseResponseSchema,U as ExtractMetaSchema,q as GenerateAnnotationsResponseSchema,P as GenerateExplorationResponseSchema,F as GenerateGraphResponseSchema,G as GenerateGraphSuggestionsResponseSchema,A as GenerateMutationResponseSchema,k as GenerateNarrativeResponseSchema,S as GenerateSuggestionsParamsSchema,C as GenerateSuggestionsResponseSchema,j as GraphGenerationRequestSchema,W as GraphyAiSdk,s as GraphyApiError,v as InvocationBudgetSchema,f as InvocationEffortSchema,K as MAX_SOURCE_TEXT_LENGTH,$ as MAX_USER_PROMPT_LENGTH,w as MetadataSchema,y as StorytellingEffortSchema,O as SuggestionSchema,l as isCompleteEvent,g as isErrorEvent,a 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.3.0-beta.1776260762546",
4
+ "version": "1.3.0-beta.1776929171854",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "files": [
@@ -18,12 +18,12 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "zod": "^4.3.6",
21
- "@graphysdk/core": "1.3.0-beta.1776260762546"
21
+ "@graphysdk/core": "1.3.0-beta.1776929171854"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@rollup/plugin-commonjs": "^28.0.6",
25
25
  "@rollup/plugin-node-resolve": "^16.0.1",
26
- "@rollup/plugin-terser": "^0.4.4",
26
+ "@rollup/plugin-terser": "^1.0.0",
27
27
  "@rollup/plugin-typescript": "^12.1.4",
28
28
  "lodash-es": "^4.18.1",
29
29
  "rollup": "^4.59.0",