@graphysdk/agents-sdk 1.8.0 → 1.8.1-beta.1786025839240
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/LICENSE.md +17 -0
- package/README.md +20 -6
- package/dist/index.cjs +2 -1
- package/dist/index.d.ts +3893 -3667
- package/dist/index.mjs +1068 -1
- package/package.json +21 -17
- package/dist/README.md +0 -26
package/LICENSE.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# License
|
|
2
|
+
|
|
3
|
+
This software is available under any of the following licenses, at your option,
|
|
4
|
+
depending on which one's conditions you meet:
|
|
5
|
+
|
|
6
|
+
- **PolyForm Noncommercial 1.0.0** — for noncommercial use (personal,
|
|
7
|
+
charitable, educational, research, government).
|
|
8
|
+
See [licenses/PolyForm-NonCommercial-1.0.0.md](licenses/PolyForm-NonCommercial-1.0.0.md)
|
|
9
|
+
|
|
10
|
+
- **PolyForm Small Business 1.0.0** — free commercial use for organizations
|
|
11
|
+
under the size thresholds defined in the license.
|
|
12
|
+
See [licenses/PolyForm-Small-Business-1.0.0.md](licenses/PolyForm-Small-Business-1.0.0.md)
|
|
13
|
+
|
|
14
|
+
- **PolyForm Free Trial 1.0.0** — a 32-day evaluation for anyone else.
|
|
15
|
+
See [licenses/PolyForm-Free-Trial-1.0.0.md](licenses/PolyForm-Free-Trial-1.0.0.md)
|
|
16
|
+
|
|
17
|
+
For commercial use beyond these terms, contact [hello@graphy.dev](mailto:hello@graphy.dev) or visit [https://graphy.dev](https://graphy.dev).
|
package/README.md
CHANGED
|
@@ -1,17 +1,31 @@
|
|
|
1
1
|
# @graphysdk/agents-sdk
|
|
2
2
|
|
|
3
|
-
TypeScript client
|
|
3
|
+
TypeScript client for the Graphy Agents API.
|
|
4
|
+
|
|
5
|
+
## Docs
|
|
6
|
+
|
|
7
|
+
- [Installation](https://docs.graphy.dev/agents/sdk/installation)
|
|
8
|
+
- [Agents quickstart](https://docs.graphy.dev/agents/quickstart)
|
|
9
|
+
- [Configuration](https://docs.graphy.dev/agents/sdk/configuration)
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pnpm add @graphysdk/agents-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
No npm org token and no `@graphysdk/core` dependency required. An Agents API key is still required for HTTP calls.
|
|
4
18
|
|
|
5
19
|
## Initial datasets (`datasetRef`)
|
|
6
20
|
|
|
7
21
|
Chart agent requests accept either inline **`config.data`** or a staged **`datasetRef`** (`graphy://attachments/{uuid}`).
|
|
8
22
|
Use **`uploadDataset(file)`** to stage CSV, TSV, or XLSX (presigned flow), then pass `datasetRef` on
|
|
9
|
-
`generateGraph`, `generateGraphStream`, and other
|
|
10
|
-
`datasetRef` are mutually exclusive. See
|
|
23
|
+
`generateGraph`, `generateGraphStream`, and other graph-generation methods. Inline non-empty data and
|
|
24
|
+
`datasetRef` are mutually exclusive. See the [Agents docs](https://docs.graphy.dev/agents/sdk/installation) for size limits and auth.
|
|
11
25
|
|
|
12
26
|
## Extract (`POST /api/v0/extract`)
|
|
13
27
|
|
|
14
|
-
|
|
28
|
+
Prefer **`attachments[]`** over deprecated **`images[]`** (do not send both).
|
|
15
29
|
|
|
16
30
|
Each attachment uses **`kind`**:
|
|
17
31
|
|
|
@@ -21,6 +35,6 @@ Each attachment uses **`kind`**:
|
|
|
21
35
|
| `"document"` | PDF (`application/pdf`) | `buildPdfAttachment` |
|
|
22
36
|
| `"spreadsheet"` | Excel `.xlsx` (OOXML ZIP on the wire) | `buildSpreadsheetAttachment` |
|
|
23
37
|
|
|
24
|
-
Spreadsheet rows must use MIME **`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`**, RFC 4648 **base64** payload (no `data:` prefix), and optional **`filename`**.
|
|
38
|
+
Spreadsheet rows must use MIME **`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`**, RFC 4648 **base64** payload (no `data:` prefix), and optional **`filename`**.
|
|
25
39
|
|
|
26
|
-
See
|
|
40
|
+
See the [Agents API docs](https://docs.graphy.dev/agents/overview) for route limits and runtime behaviour.
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("zod");class n extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const a=e=>"progress"===e.type,r=e=>"complete"===e.type,i=e=>"error"===e.type;function o(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class s{constructor(e){this.tag="[GRAPHY]";if(!("include"===e.credentials||e.apiKey&&0!==e.apiKey.trim().length))throw new Error('apiKey is required and must not be empty (unless credentials: "include" is set for cookie auth)');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.credentials=e.credentials,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 r(e)}static isErrorEvent(e){return i(e)}stream(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,a);return this.parseSSE(e)})}fetch(t,o,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,d,u;const h=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const y=yield this.makeRequest(t,o,c),z=y.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var g,f=!0,b=e.__asyncValues(this.parseSSE(y));!(l=(g=yield b.next()).done);f=!0){d=g.value,f=!1;const e=d;if(a(e)&&s&&s(e),r(e))return e.data;if(i(e)){const a=Date.now()-h;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new n(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){m={error:e}}finally{try{f||l||!(p=b.return)||(yield p.call(b))}finally{if(m)throw m.error}}const o=Date.now()-h;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${o}ms`),new n("Stream ended without completion")}return yield y.json()}catch(e){const a=Date.now()-h;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof n)throw e;throw e}finally{const e=Date.now()-h;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,a);return yield e.json()})}get(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,void 0,n,1,"GET");return yield e.json()})}postJson(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,a,1,"POST");return yield e.json()})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new n("Response body is null");const a=t.body.getReader(),r=new TextDecoder;let i="",s="",c="";try{for(;;){const{done:t,value:n}=yield e.__await(a.read());if(t)break;i+=r.decode(n,{stream:!0});const l=i.split(/\r?\n/);i=l.pop()||"";for(const t of l)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))c+=(c?"\n":"")+t.slice(6);else if(""===t.trim()&&c){try{const t=o(s,JSON.parse(c));if(null===t){s="",c="";continue}if(yield yield e.__await(t),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",c)}s="",c=""}}}finally{a.releaseLock()}})}makeRequest(t,a,r){return e.__awaiter(this,arguments,void 0,function*(e,t,a,r=1,i="POST"){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${r}/${this.retryConfig.attempts}: ${o}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();a&&a.addEventListener("abort",l);try{const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache","User-Agent":"Graphy-SDK/1.0"};this.apiKey&&(c.Authorization=`Bearer ${this.apiKey}`);const l=yield fetch(o,Object.assign(Object.assign({method:i,headers:c,signal:s.signal},this.credentials?{credentials:this.credentials}:{}),"POST"===i&&{body:JSON.stringify(t)}));if(!l.ok){let o,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===o)&&(l.status>=500||429===l.status),m=new n(s,{status:l.status,code:o,retryable:c});if(c&&r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${n}ms (attempt ${r+1})`),yield this.sleep(n),this.makeRequest(e,t,a,r+1,i)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(o){if(o instanceof n)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),o;if(r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${n}ms`),yield this.sleep(n),this.makeRequest(e,t,a,r+1,i)}throw this.logger.error(`${this.tag} Network error: ${e}`,o),new n("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",l)}})}makeMultipartRequest(t,a,r){return e.__awaiter(this,arguments,void 0,function*(e,t,a,r=1){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const i=new URL(e,this.baseUrl);if(i.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");const o=new AbortController,s=setTimeout(()=>o.abort(),this.timeout),c=()=>o.abort();a&&a.addEventListener("abort",c);try{const s={Accept:"application/json","User-Agent":"Graphy-SDK/1.0"};this.apiKey&&(s.Authorization=`Bearer ${this.apiKey}`);const c=yield fetch(i,Object.assign({method:"POST",headers:s,body:t,signal:o.signal},this.credentials?{credentials:this.credentials}:{}));if(!c.ok){let i,o=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error),"string"==typeof t.code&&(i=t.code)}}catch(e){}const s=c.status>=500||429===c.status,l=new n(o,{status:c.status,code:i,retryable:s});if(s&&r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,a,r+1)}throw l}return c}catch(i){if(i instanceof n)throw i;if(i instanceof Error&&"AbortError"===i.name)throw i;if(r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,a,r+1)}throw new n("Network error",{retryable:!0})}finally{clearTimeout(s),a&&a.removeEventListener("abort",c)}})}}const c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".csv":"text/csv",".tsv":"text/tab-separated-values",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function l(e,t){var n;const a=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return a||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function m(e,t){var n;const a=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(a)return a;const r=e.type.trim();if(r.length>0)return r;const i=l(e,t);if(i){const e=function(e){const t=e.lastIndexOf(".");if(t<0)return;const n=e.slice(t).toLowerCase();return c[n]}(i);if(e)return e}throw new Error("uploadAttachment requires a MIME type: set `file.type`, pass `options.mimeType`, or use a filename with a supported extension (.png, .jpg, .pdf, .csv, .tsv, .xlsx, …)")}const p=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);function d(e,t){const n=m(e,t);if(a=n,!p.has(a.trim()))throw new Error("uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)");var a;return n}const u=t.z.object({inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional(),wallClockMs:t.z.number()}),h=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()}),g=t.z.object({limits:t.z.object({maxWallClockMs:t.z.number().optional(),maxTotalTokens:t.z.number().optional(),maxCostUsd:t.z.number().optional(),trackUsage:t.z.boolean().optional()}),consumed:h,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});t.z.object({inputTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),modelName:t.z.string(),inputCachedTokens:t.z.number().optional(),inputUncachedTokens:t.z.number().optional(),cost:t.z.number().optional(),latencyMs:t.z.number().optional(),effort:t.z.string().optional(),providerReasoning:t.z.string().optional()});const f={usage:u.optional(),budget:g.optional()};function b(e,t){const n=void 0!==e.config.data,a=function(e){const{data:t}=e;return void 0!==t&&(t.columns.length>0||t.rows.length>0)}(e.config),r=void 0!==e.datasetRef&&e.datasetRef.trim().length>0;a&&r&&t.addIssue({code:"custom",message:"Provide either config.data or datasetRef, not both",path:["datasetRef"]}),n||r||t.addIssue({code:"custom",message:"Provide config.data or datasetRef",path:["datasetRef"]})}const y=t.z.enum(["EN_GB","EN_US"]),z=t.z.custom(e=>null!=e&&"object"==typeof e),x=t.z.enum(["low","medium","high"]),v=t.z.enum(["none","low","medium","high"]),_=t.z.enum(["agentic","fast"]),w=3e5,S=5e5,T=t.z.object({maxWallClockMs:t.z.number().positive().max(w).optional(),maxTotalTokens:t.z.number().int().positive().max(S).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),E=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()});t.z.object({limits:T,consumed:E,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});const C=t.z.object({callId:t.z.string().max(256).optional(),locale:y.optional(),effort:x.optional(),storytellingEffort:v.optional().default("low"),budget:T.optional(),executionMode:_.optional(),enforceTableRowCap:t.z.boolean().optional()}),j=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()}),A=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),k=1e4,R=t.z.enum(["comparison","relationship","distribution","composition"]),$=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,M=t.z.string().regex($,"datasetRef must be graphy://attachments/{uuid}"),O=t.z.object({config:z,userPrompt:t.z.string().max(k).optional().default(""),metadata:C.optional(),chartFamily:R.optional(),datasetRef:M.optional()}),P=O.superRefine(b),D=O.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}).superRefine(b),U=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),I=t.z.object({dataPrepPrompt:t.z.string(),chartType:U,summary:t.z.string()}),B=O.extend({userPrompt:t.z.string().max(k),mutationReceipt:j.optional(),exploreFindingSummary:t.z.string().max(500).optional()}).superRefine(b),G=t.z.object({response:t.z.object({message:t.z.string()}),config:z,run:A.optional()}).extend(f),X=t.z.object({suggestions:t.z.array(I),run:A.optional()}).extend(f),q=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:R.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.")}),F=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(q).describe("Child findings, sorted by quadrant score desc.")}),N=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(F),run:A.optional()}).extend(f);O.extend({mutationReceipt:j.optional()}).superRefine(b);const L=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:z,run:A.optional()}).extend(f),K=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:z,mutationReceipt:j.optional(),warnings:t.z.array(t.z.string()).optional(),run:A.optional()}).extend(f),H=t.z.enum(["explore","mutate","narrate","annotate"]),W=t.z.object({agent:H,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),Y=O.extend({userPrompt:t.z.string().max(k),stages:t.z.array(H).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}).superRefine(b),J=K.extend({reasoning:t.z.array(W),stories:t.z.array(F).optional()}),V=t.z.enum(["high","medium","low"]),Q=t.z.object({confidence:V,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:V,quote:t.z.string().optional()})).optional()}),Z=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()}),ee=5e5,te=2097152,ne=7340032,ae=6291456,re=8388608,ie=ae,oe=re,se=12582912,ce=12,le=52428800;function me(e){return 4*Math.ceil(e/3)}const pe=me(te),de=me(ne),ue=me(ae),he=me(re),ge=me(ie),fe=me(oe),be=me(se);function ye(e){return e.replace(/\s+/g,"")}function ze(e){const t=ye(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const xe=/^image\/(png|jpeg|jpg|webp|gif)$/i,ve=t.z.object({mimeType:t.z.string().min(1).refine(e=>xe.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(pe).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),_e=t.z.enum(["image","document","spreadsheet","tabular"]),we=ve.extend({kind:t.z.literal("image")}),Se=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(ue).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Te=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(ge).refine(ze,{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"]}),Ee=t.z.discriminatedUnion("kind",[we,Se,Te]),Ce=t.z.string().regex($,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),je=t.z.enum(["pending","ready","failed"]),Ae=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),status:je,kind:_e.optional(),mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().nonnegative(),uploadExpiresAt:t.z.string().datetime().optional(),completedAt:t.z.string().datetime().optional(),expiresAt:t.z.string().datetime()}),ke=Ae.extend({status:t.z.literal("ready"),kind:_e,sizeBytes:t.z.number().int().positive()}),Re=t.z.object({mimeType:t.z.string().min(1),filename:t.z.string().max(512).optional(),sizeBytes:t.z.number().int().positive().max(le).optional()}),$e=t.z.object({files:t.z.array(Re).min(1).max(ce)}),Me=Ae.extend({status:t.z.literal("pending"),uploadUrl:t.z.string().url()}),Oe=t.z.object({uploads:t.z.array(Me)}),Pe=t.z.object({sourceText:t.z.string().max(ee).default(""),images:t.z.array(ve).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(Ee).max(ce).optional(),attachmentRefs:t.z.array(Ce).max(ce).optional(),metadata:C.optional()}).superRefine((e,t)=>{var n,a,r;const i=e.sourceText.trim(),o=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(a=e.attachments)&&void 0!==a?a:[],c=null!==(r=e.attachmentRefs)&&void 0!==r?r:[];if(o.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===i.length&&0===o.length&&0===s.length&&0===c.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(o.length+s.length+c.length>ce)return void t.addIssue({code:"custom",message:"Too many attachments (max 12 across inline payloads and attachmentRefs)",path:["attachmentRefs"]});if(c.length>0&&0===s.length&&0===o.length)return;if(o.length>0){o.reduce((e,t)=>e+ye(t.dataBase64).length,0)>de&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let l=0,m=0,p=0,d=0,u=0,h=0,g=0;for(const e of s){const t=ye(e.dataBase64).length;switch(g+=t,e.kind){case"image":l+=1,d+=t;break;case"document":m+=1,u+=t;break;case"spreadsheet":p+=1,h+=t}}l>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),p>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&p<=2;s.length>0&&f&&(d>de&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>he&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>fe&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>be&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const De=t.z.object({response:t.z.object({message:t.z.string()}),config:z,extractMeta:Q.nullable(),lastAccuracyEvaluation:Z.optional(),run:A.optional()}).extend(f),Ue=t.z.object({config:z,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:A.optional()}).extend(f),Ie=X,Be=t.z.enum(["deal-breaker","pro","con","family","continuity"]),Ge=t.z.object({kind:Be,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),Xe=t.z.enum(["ok","disqualified"]),qe=t.z.object({rank:t.z.number().int().positive(),type:U,score:t.z.number(),verdict:Xe,factors:t.z.array(Ge)}),Fe=P,Ne=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"]),Le=t.z.object({kind:Ne,message:t.z.string()}),Ke=t.z.enum(["sum","avg","count","min","max"]),He=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:Ke,chartType:U,score:t.z.number(),message:t.z.string()}),We=t.z.object({ranking:t.z.array(qe),observations:t.z.array(Le).optional().default([]),suggestions:t.z.array(He).optional().default([]),run:A.optional()}),Ye=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()}),Je=t.z.object({config:z.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:Ye.optional(),userPrompt:t.z.string().optional(),metadata:C.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ve=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Qe=t.z.enum(["info","low","medium","high"]),Ze=t.z.object({category:Ve,severity:Qe,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),et=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Ze)}),tt=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()}),nt=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),at=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:et.nullable(),chartVisionAudit:nt.nullable().optional().default(null),rubricScores:tt.nullable().optional().default(null),run:A.optional()}).extend(f),rt="/api/v0";exports.AggregationFunctionSchema=Ke,exports.AggregationSuggestionSchema=He,exports.AiChartTypeEnum=U,exports.AttachmentResponseSchema=Ae,exports.AttachmentUploadResponseSchema=ke,exports.AttachmentUploadSlotResponseSchema=Me,exports.ChartCritiqueIssueCategorySchema=Ve,exports.ChartCritiqueIssueSchema=Ze,exports.ChartCritiqueIssueSeveritySchema=Qe,exports.ChartCritiqueReportSchema=et,exports.ChartFamilySchema=R,exports.ChartFitEntrySchema=qe,exports.ChartFitFactorKindSchema=Be,exports.ChartFitFactorSchema=Ge,exports.ChartFitVerdictSchema=Xe,exports.ChartJudgeRubricSchema=Ye,exports.CreateAttachmentUploadsParamsSchema=$e,exports.CreateAttachmentUploadsResponseSchema=Oe,exports.DataObservationKindSchema=Ne,exports.DataObservationSchema=Le,exports.EvaluateParamsSchema=Fe,exports.EvaluateResponseSchema=We,exports.ExecutionModeSchema=_,exports.ExploreFindingSchema=q,exports.ExploreStorySchema=F,exports.ExtractAccuracyEvaluationSchema=Z,exports.ExtractAttachmentInputSchema=Ee,exports.ExtractAttachmentKindSchema=_e,exports.ExtractConfidenceSchema=V,exports.ExtractFromProseParamsSchema=Pe,exports.ExtractFromProseResponseSchema=De,exports.ExtractMetaSchema=Q,exports.GenerateAnnotationsResponseSchema=L,exports.GenerateExplorationResponseSchema=N,exports.GenerateGraphResponseSchema=Ue,exports.GenerateGraphSuggestionsResponseSchema=Ie,exports.GenerateMutationResponseSchema=K,exports.GenerateNarrativeParamsSchema=B,exports.GenerateNarrativeResponseSchema=G,exports.GeneratePipelineParamsSchema=Y,exports.GeneratePipelineResponseSchema=J,exports.GenerateSuggestionsParamsSchema=D,exports.GenerateSuggestionsResponseSchema=X,exports.GraphGenerationRequestSchema=P,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:r}=t,i=e.__rest(t,["storytellingOptions"]),o=yield this.client.fetch(`${rt}/generate`,i,n,a),s=Ue.parse(o);return this.stripStorytelling(s,r)})}generateGraphStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,r=e.__rest(t,["storytellingOptions"]),i=yield this.client.stream(`${rt}/generate`,r,n);return this.wrapStreamWithStorytellingStripping(i,a)})}generateNarrative(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/narrate`,t,n,a);return G.parse(e)})}generateNarrativeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/narrate`,t,n)})}generateSuggestions(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/suggestions`,t,n,a);return X.parse(e)})}generateSuggestionsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/suggestions`,t,n)})}generateExploration(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/explore`,t,n,a);return N.parse(e)})}generateExplorationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/explore`,t,n)})}generateAnnotations(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/annotate`,t,n,a);return L.parse(e)})}generateAnnotationsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/annotate`,t,n)})}generateMutation(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/mutate`,t,n,a);return K.parse(e)})}generateMutationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/mutate`,t,n)})}generatePipeline(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/pipeline`,t,n,a);return J.parse(e)})}generatePipelineStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/pipeline`,t,n)})}evaluate(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/evaluate`,t,void 0,n);return We.parse(e)})}judge(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/judge`,t,void 0,n);return at.parse(e)})}judgeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/judge`,t,n)})}extractFromProse(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/extract`,t,n,a);return De.parse(e)})}extractFromProseStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/extract`,t,n)})}uploadAttachment(t,a,r){return e.__awaiter(this,void 0,void 0,function*(){const e=m(t,a),i=l(t,a),{uploads:o}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},i?{filename:i}:{}),t.size>0?{sizeBytes:t.size}:{})]},r),s=o[0];if(!s)throw new n("Attachment upload slot was not returned");const c=yield fetch(s.uploadUrl,{method:"PUT",headers:{"Content-Type":e},body:t,signal:r});if(!c.ok)throw new n(`Attachment upload failed (HTTP ${c.status})`,{status:c.status,retryable:c.status>=500});const p=yield this.completeAttachmentUpload(s.id,r);return ke.parse(p)})}uploadDataset(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=d(t,n);return this.uploadAttachment(t,Object.assign(Object.assign({},n),{mimeType:e}),a)})}createAttachmentUploads(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${rt}/attachment-uploads`,t,n);return Oe.parse(e)})}completeAttachmentUpload(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${rt}/attachments/${t}/complete`,{},n);return Ae.parse(e)})}getAttachment(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.get(`${rt}/attachments/${t}`,n);return Ae.parse(e)})}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,n){return e.__asyncGenerator(this,arguments,function*(){var a,i,o,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(a=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(r(t)){const a=this.stripStorytelling(t.data,n);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){i={error:e}}finally{try{l||a||!(o=m.return)||(yield e.__await(o.call(m)))}finally{if(i)throw i.error}}})}},exports.GraphyApiError=n,exports.InvocationBudgetSchema=T,exports.InvocationEffortSchema=x,exports.JudgeParamsSchema=Je,exports.JudgeResponseSchema=at,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=S,exports.MAX_BUDGET_WALL_CLOCK_MS=w,exports.MAX_EXTRACT_ATTACHMENTS=ce,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=se,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=re,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=ae,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=ne,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=te,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=oe,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=ie,exports.MAX_SOURCE_TEXT_LENGTH=ee,exports.MAX_STAGED_FILE_BYTES=le,exports.MAX_USER_PROMPT_LENGTH=k,exports.MetadataSchema=C,exports.MutateNarrationReceiptSchema=j,exports.PipelineAgentNameSchema=H,exports.PipelineStageReasoningSchema=W,exports.RubricScoresSchema=tt,exports.RunContextSchema=A,exports.StorytellingEffortSchema=v,exports.SuggestionSchema=I,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ye(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ye(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ye(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isAgentCompleteEvent=e=>"agent_complete"===e.type,exports.isCompleteEvent=r,exports.isErrorEvent=i,exports.isGraphyApiError=e=>e instanceof n,exports.isLlmStepEvent=e=>"llm_step"===e.type,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,exports.isReasoningEvent=e=>"reasoning"===e.type,exports.isSessionBudgetEvent=e=>"session_budget"===e.type,exports.isToolCallEvent=e=>"tool_call"===e.type,exports.isToolCompleteEvent=e=>"tool_complete"===e.type,exports.isToolErrorEvent=e=>"tool_error"===e.type;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let e=require("zod");var d=class extends Error{constructor(t,a){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=a?.status,this.code=a?.code,this.retryable=a?.retryable??!1}},Ne=t=>t instanceof d,P=t=>t.type==="progress",w=t=>t.type==="complete",j=t=>t.type==="error",Fe=t=>t.type==="preview",Le=t=>t.type==="reasoning",qe=t=>t.type==="llm_step",He=t=>t.type==="session_budget",Ke=t=>t.type==="agent_complete",Ye=t=>t.type==="tool_call",We=t=>t.type==="tool_complete",Je=t=>t.type==="tool_error";function Ve(t,a){return t==="progress"?{type:"progress",...a}:t==="complete"?{type:"complete",data:a}:t==="error"?{type:"error",...a}:t==="preview"?{...a,type:"preview"}:t==="reasoning"?{...a,type:"reasoning"}:t==="llm_step"||t==="session_budget"||t==="agent_complete"||t==="tool_call"||t==="tool_complete"||t==="tool_error"?a:null}var Ze="[GRAPHY]",Qe=class{constructor(t){if(this.tag=Ze,t.credentials!=="include"&&(!t.apiKey||t.apiKey.trim().length===0))throw new Error('apiKey is required and must not be empty (unless credentials: "include" is set for cookie auth)');const a=new URL(t.baseUrl);if(!["http:","https:"].includes(a.protocol))throw new Error(`Invalid baseUrl protocol: ${a.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.credentials=t.credentials,this.baseUrl=a.origin+a.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 P(t)}static isCompleteEvent(t){return w(t)}static isErrorEvent(t){return j(t)}async stream(t,a,r){const n=await this.makeRequest(t,a,r);return this.parseSSE(n)}async fetch(t,a,r,n){const s=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const o=await this.makeRequest(t,a,n);if(o.headers.get("content-type")?.includes("text/event-stream")){for await(const c of this.parseSSE(o)){if(P(c)&&r&&r(c),w(c))return c.data;if(j(c)){const m=Date.now()-s;throw this.logger.error(`${this.tag} Server error: ${t} ${m}ms`,c.error),new d(c.error,{code:c.code,retryable:c.retryable??!1})}}const u=Date.now()-s;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${u}ms`),new d("Stream ended without completion")}else return await o.json()}catch(o){const u=Date.now()-s;throw this.logger.error(`${this.tag} Fetch failed: ${t} ${u}ms`,o),o instanceof d,o}finally{const o=Date.now()-s;this.logger.debug(`${this.tag} Fetch completed: ${t} ${o}ms`)}}async ping(){const t=Date.now();try{return await this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch{return{ok:!1,latency:Date.now()-t}}}async uploadMultipart(t,a,r){return await(await this.makeMultipartRequest(t,a,r)).json()}async get(t,a){return await(await this.makeRequest(t,void 0,a,1,"GET")).json()}async postJson(t,a,r){return await(await this.makeRequest(t,a,r,1,"POST")).json()}async sleep(t){return new Promise(a=>setTimeout(a,t))}async*parseSSE(t){if(!t.body)throw new d("Response body is null");const a=t.body.getReader(),r=new TextDecoder;let n="",s="",o="";try{for(;;){const{done:u,value:c}=await a.read();if(u)break;n+=r.decode(c,{stream:!0});const m=n.split(/\r?\n/);n=m.pop()||"";for(const i of m)if(i.startsWith("event: "))s=i.slice(7).trim();else if(i.startsWith("data: "))o+=(o?`
|
|
2
|
+
`:"")+i.slice(6);else if(i.trim()===""&&o){try{const h=JSON.parse(o),g=Ve(s,h);if(g===null){s="",o="";continue}if(yield g,s==="complete"||s==="error")return}catch{this.logger.warn("Invalid SSE data format",o)}s="",o=""}}}finally{a.releaseLock()}}async makeRequest(t,a,r,n=1,s="POST"){if(!t.startsWith("/"))throw new d("Invalid endpoint: must start with /");const o=new URL(t,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new d("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${o}`);const u=new AbortController,c=setTimeout(()=>u.abort(),this.timeout),m=()=>u.abort();r&&r.addEventListener("abort",m);try{const i={"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);const h=await fetch(o,{method:s,headers:i,signal:u.signal,...this.credentials?{credentials:this.credentials}:{},...s==="POST"&&{body:JSON.stringify(a)}});if(!h.ok){let g=`HTTP ${h.status}`,y;try{const p=await h.json();if(typeof p=="object"&&p!==null){const v=p;typeof v.message=="string"?g=v.message:typeof v.error=="string"&&(g=v.error),typeof v.code=="string"&&(y=v.code)}}catch{}const z=y!=="QUOTA_EXCEEDED"&&(h.status>=500||h.status===429),f=new d(g,{status:h.status,code:y,retryable:z});if(z&&n<this.retryConfig.attempts&&!r?.aborted){const p=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${p}ms (attempt ${n+1})`),await this.sleep(p),this.makeRequest(t,a,r,n+1,s)}throw this.logger.error(`${this.tag} Request failed: ${t} (${h.status}) - ${g}`),f}return this.logger.debug(`${this.tag} Connected: ${t}`),h}catch(i){if(i instanceof d)throw i;if(i instanceof Error&&i.name==="AbortError")throw this.logger.debug(`${this.tag} Aborted: ${t}`),i;if(n<this.retryConfig.attempts&&!r?.aborted){const h=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${h}ms`),await this.sleep(h),this.makeRequest(t,a,r,n+1,s)}throw this.logger.error(`${this.tag} Network error: ${t}`,i),new d("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",m)}}async makeMultipartRequest(t,a,r,n=1){if(!t.startsWith("/"))throw new d("Invalid endpoint: must start with /");const s=new URL(t,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new d("Endpoint resolved to unexpected origin");const o=new AbortController,u=setTimeout(()=>o.abort(),this.timeout),c=()=>o.abort();r&&r.addEventListener("abort",c);try{const m={Accept:"application/json"};this.apiKey&&(m.Authorization=`Bearer ${this.apiKey}`);const i=await fetch(s,{method:"POST",headers:m,body:a,signal:o.signal,...this.credentials?{credentials:this.credentials}:{}});if(!i.ok){let h=`HTTP ${i.status}`,g;try{const f=await i.json();if(typeof f=="object"&&f!==null){const p=f;typeof p.message=="string"?h=p.message:typeof p.error=="string"&&(h=p.error),typeof p.code=="string"&&(g=p.code)}}catch{}const y=g!=="QUOTA_EXCEEDED"&&(i.status>=500||i.status===429),z=new d(h,{status:i.status,code:g,retryable:y});if(y&&n<this.retryConfig.attempts&&!r?.aborted){const f=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return await this.sleep(f),this.makeMultipartRequest(t,a,r,n+1)}throw z}return i}catch(m){if(m instanceof d||m instanceof Error&&m.name==="AbortError")throw m;if(n<this.retryConfig.attempts&&!r?.aborted){const i=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return await this.sleep(i),this.makeMultipartRequest(t,a,r,n+1)}throw new d("Network error",{retryable:!0})}finally{clearTimeout(u),r&&r.removeEventListener("abort",c)}}},et={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".csv":"text/csv",".tsv":"text/tab-separated-values",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function K(t,a){const r=a?.filename?.trim();if(r)return r;if(typeof File<"u"&&t instanceof File&&t.name.trim().length>0)return t.name.trim()}function Y(t,a){const r=a?.mimeType?.trim();if(r)return r;const n=t.type.trim();if(n.length>0)return n;const s=K(t,a);if(s){const o=tt(s);if(o)return o}throw new Error("uploadAttachment requires a MIME type: set `file.type`, pass `options.mimeType`, or use a filename with a supported extension (.png, .jpg, .pdf, .csv, .tsv, .xlsx, …)")}function tt(t){const a=t.lastIndexOf(".");if(a<0)return;const r=t.slice(a).toLowerCase();return et[r]}var at=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]),rt="uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)";function nt(t){return at.has(t.trim())}function st(t,a){const r=Y(t,a);if(!nt(r))throw new Error(rt);return r}var ot=e.z.object({inputTokens:e.z.number(),inputCachedTokens:e.z.number(),inputUncachedTokens:e.z.number(),outputTokens:e.z.number(),totalTokens:e.z.number(),costUsd:e.z.number().nullable(),costEnforcementSkipped:e.z.boolean().optional(),wallClockMs:e.z.number()}),it=e.z.object({wallClockMs:e.z.number(),inputTokens:e.z.number(),inputCachedTokens:e.z.number(),inputUncachedTokens:e.z.number(),outputTokens:e.z.number(),totalTokens:e.z.number(),costUsd:e.z.number().nullable(),costEnforcementSkipped:e.z.boolean().optional()}),ct=e.z.object({limits:e.z.object({maxWallClockMs:e.z.number().optional(),maxTotalTokens:e.z.number().optional(),maxCostUsd:e.z.number().optional(),trackUsage:e.z.boolean().optional()}),consumed:it,exceeded:e.z.boolean(),exceededDimensions:e.z.array(e.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:e.z.string().optional()}),Ht=e.z.object({inputTokens:e.z.number(),outputTokens:e.z.number(),totalTokens:e.z.number(),modelName:e.z.string(),inputCachedTokens:e.z.number().optional(),inputUncachedTokens:e.z.number().optional(),cost:e.z.number().optional(),latencyMs:e.z.number().optional(),effort:e.z.string().optional(),providerReasoning:e.z.string().optional()}),b={usage:ot.optional(),budget:ct.optional()};function mt(t){const{data:a}=t;return a===void 0?!1:a.columns.length>0||a.rows.length>0}function _(t,a){const r=t.config.data!==void 0,n=mt(t.config),s=t.datasetRef!==void 0&&t.datasetRef.trim().length>0;n&&s&&a.addIssue({code:"custom",message:"Provide either config.data or datasetRef, not both",path:["datasetRef"]}),!r&&!s&&a.addIssue({code:"custom",message:"Provide config.data or datasetRef",path:["datasetRef"]})}var W=["EN_GB","EN_US","AR","PT_PT"],J=e.z.enum(["low","medium","high"]),V=e.z.enum(["none","low","medium","high"]),Z=e.z.enum(["agentic","fast"]),Q=3e5,ee=5e5,lt=10,U=e.z.object({maxWallClockMs:e.z.number().positive().max(Q).optional(),maxTotalTokens:e.z.number().int().positive().max(ee).optional(),maxCostUsd:e.z.number().positive().max(10).optional(),trackUsage:e.z.boolean().optional()}),ut=e.z.object({wallClockMs:e.z.number(),inputTokens:e.z.number(),inputCachedTokens:e.z.number(),inputUncachedTokens:e.z.number(),outputTokens:e.z.number(),totalTokens:e.z.number(),costUsd:e.z.number().nullable(),costEnforcementSkipped:e.z.boolean().optional()}),Kt=e.z.object({limits:U,consumed:ut,exceeded:e.z.boolean(),exceededDimensions:e.z.array(e.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:e.z.string().optional()}),x=e.z.object({steps:e.z.array(e.z.string()),postProcess:e.z.object({measureRelevance:e.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:e.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:e.z.string().optional(),comparison:e.z.string().optional()}).optional(),droppedMeasures:e.z.array(e.z.string()).optional(),rowCount:e.z.number().int().nonnegative(),totalRowCountBeforeSlice:e.z.number().int().positive().optional(),displayedRowCount:e.z.number().int().nonnegative().optional(),columnKeys:e.z.array(e.z.string()),activeFilters:e.z.array(e.z.string()).optional(),grainSummary:e.z.string().optional()}),S=e.z.object({runId:e.z.string(),trackingId:e.z.string(),callId:e.z.string().optional()}),M=1e4,B=e.z.enum(["comparison","relationship","distribution","composition"]),k=e.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),te=e.z.object({dataPrepPrompt:e.z.string(),chartType:k,summary:e.z.string()}),X=e.z.object({suggestions:e.z.array(te),run:S.optional()}).extend(b),ae=e.z.object({finding:e.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:e.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:e.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:e.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:e.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:e.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),$=e.z.object({topic:e.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:e.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:e.z.number().int().min(1).describe("Number of findings in this story."),findings:e.z.array(ae).describe("Child findings, sorted by quadrant score desc.")}),re=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),stories:e.z.array($),run:S.optional()}).extend(b),G=e.z.enum(["explore","mutate","narrate","annotate"]),ne=e.z.object({agent:G,summary:e.z.string(),steps:e.z.array(e.z.string()).optional()}),I=e.z.enum(["high","medium","low"]),se=e.z.object({confidence:I,needsUserInput:e.z.boolean(),warnings:e.z.array(e.z.string()),cellConfidence:e.z.array(e.z.object({rowIndex:e.z.number().int().nonnegative(),columnKey:e.z.string(),confidence:I,quote:e.z.string().optional()})).optional()}),oe=e.z.object({score:e.z.number().min(0).max(1),issues:e.z.array(e.z.string()),sufficient:e.z.boolean(),summary:e.z.string()}),ie=5e5,ht=8,ce=2*1024*1024,me=7*1024*1024,pt=2,O=6*1024*1024,N=8*1024*1024,dt=2,le=O,ue=N,he=12*1024*1024,gt=12,ft=50*1024*1024,pe=ft,F=e.z.enum(["image","document","spreadsheet","tabular"]),St=e.z.enum(["pending","ready","failed"]),C=e.z.object({id:e.z.string().uuid(),uri:e.z.string(),status:St,kind:F.optional(),mimeType:e.z.string(),filename:e.z.string().optional(),sizeBytes:e.z.number().int().nonnegative(),uploadExpiresAt:e.z.string().datetime().optional(),completedAt:e.z.string().datetime().optional(),expiresAt:e.z.string().datetime()}),de=C.extend({status:e.z.literal("ready"),kind:F,sizeBytes:e.z.number().int().positive()}),yt=e.z.object({mimeType:e.z.string().min(1),filename:e.z.string().max(512).optional(),sizeBytes:e.z.number().int().positive().max(pe).optional()}),bt=e.z.object({files:e.z.array(yt).min(1).max(12)}),ge=C.extend({status:e.z.literal("pending"),uploadUrl:e.z.string().url()}),fe=e.z.object({uploads:e.z.array(ge)}),Et=X,Se=e.z.enum(["deal-breaker","pro","con","family","continuity"]),ye=e.z.object({kind:Se,label:e.z.string(),weight:e.z.number(),reason:e.z.string()}),be=e.z.enum(["ok","disqualified"]),Ee=e.z.object({rank:e.z.number().int().positive(),type:k,score:e.z.number(),verdict:be,factors:e.z.array(ye)}),ze=e.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),ve=e.z.object({kind:ze,message:e.z.string()}),Te=e.z.enum(["sum","avg","count","min","max"]),Ae=e.z.object({dimensionName:e.z.string(),dimensionLabel:e.z.string(),measureName:e.z.string().nullable(),measureLabel:e.z.string().nullable(),fn:Te,chartType:k,score:e.z.number(),message:e.z.string()}),Ce=e.z.object({ranking:e.z.array(Ee),observations:e.z.array(ve).optional().default([]),suggestions:e.z.array(Ae).optional().default([]),run:S.optional()}),_e=e.z.object({prompt:e.z.string(),datasetSummary:e.z.string().optional(),mustShow:e.z.array(e.z.string()).optional(),unacceptable:e.z.array(e.z.string()).optional(),acceptableChartFamilies:e.z.array(e.z.string()).optional()}),Re=e.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),we=e.z.enum(["info","low","medium","high"]),xe=e.z.object({category:Re,severity:we,observation:e.z.string(),rationale:e.z.string().optional(),suggestedChange:e.z.string().optional(),configPaths:e.z.array(e.z.string()).optional()}),Me=e.z.object({overallSummary:e.z.string(),overallSeverity:e.z.enum(["none","low","medium","high"]).optional(),issues:e.z.array(xe)}),ke=e.z.object({dataFidelity:e.z.number().min(0).max(1),promptRelevance:e.z.number().min(0).max(1),chartTypeAppropriateness:e.z.number().min(0).max(1),readability:e.z.number().min(0).max(1),honesty:e.z.number().min(0).max(1),composite:e.z.number().min(0).max(1),rationale:e.z.string().optional()}),zt=e.z.enum(W),D=e.z.object({callId:e.z.string().max(256).optional(),locale:zt.optional(),effort:J.optional(),storytellingEffort:V.optional().default("low"),budget:U.optional(),executionMode:Z.optional(),enforceTableRowCap:e.z.boolean().optional()}),De=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,vt=e.z.string().regex(De,"datasetRef must be graphy://attachments/{uuid}"),Tt=E(ce),H=E(me),At=E(O),Ct=E(N),_t=E(le),Rt=E(ue),wt=E(he),xt=/^image\/(png|jpeg|jpg|webp|gif)$/i,Pe=e.z.object({mimeType:e.z.string().min(1).refine(t=>xt.test(t.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:e.z.string().min(1).max(Tt).refine(q,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Mt=Pe.extend({kind:e.z.literal("image")}),kt=e.z.object({kind:e.z.literal("document"),mimeType:e.z.string().min(1).refine(t=>/^application\/pdf$/i.test(t.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:e.z.string().min(1).max(At).refine(q,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Dt=e.z.object({kind:e.z.literal("spreadsheet"),mimeType:e.z.string().min(1).refine(t=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(t.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:e.z.string().min(1).max(_t).refine(q,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:e.z.string().max(512).optional()}).refine(t=>t.filename===void 0||t.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),je=e.z.discriminatedUnion("kind",[Mt,kt,Dt]),Pt=e.z.string().regex(De,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),jt=e.z.object({sourceText:e.z.string().max(ie).default(""),images:e.z.array(Pe).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:e.z.array(je).max(12).optional(),attachmentRefs:e.z.array(Pt).max(12).optional(),metadata:D.optional()}).superRefine((t,a)=>{const r=t.sourceText.trim(),n=t.images??[],s=t.attachments??[],o=t.attachmentRefs??[];if(n.length>0&&s.length>0){a.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});return}if(r.length===0&&n.length===0&&s.length===0&&o.length===0){a.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});return}if(n.length+s.length+o.length>12){a.addIssue({code:"custom",message:"Too many attachments (max 12 across inline payloads and attachmentRefs)",path:["attachmentRefs"]});return}if(o.length>0&&s.length===0&&n.length===0)return;n.length>0&&n.reduce((f,p)=>f+T(p.dataBase64).length,0)>H&&a.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]});let u=0,c=0,m=0,i=0,h=0,g=0,y=0;for(const f of s){const p=T(f.dataBase64).length;switch(y+=p,f.kind){case"image":u+=1,i+=p;break;case"document":c+=1,h+=p;break;case"spreadsheet":m+=1,g+=p;break}}u>8&&a.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&a.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),m>2&&a.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const z=u<=8&&c<=2&&m<=2;s.length>0&&z&&(i>H&&a.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>Ct&&a.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>Rt&&a.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),y>wt&&a.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))}),It=e.z.object({capturedAt:e.z.string(),chartId:e.z.string()}),Ie=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string()),critiqueCommitted:e.z.boolean()}),critiqueReport:Me.nullable(),chartVisionAudit:It.nullable().optional().default(null),rubricScores:ke.nullable().optional().default(null),run:S.optional()}).extend(b),A=e.z.custom(t=>t!==null&&typeof t=="object"),Ue=e.z.object({response:e.z.object({message:e.z.string()}),config:A,run:S.optional()}).extend(b),Be=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),config:A,run:S.optional()}).extend(b),L=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),config:A,mutationReceipt:x.optional(),warnings:e.z.array(e.z.string()).optional(),run:S.optional()}).extend(b),Xe=L.extend({reasoning:e.z.array(ne),stories:e.z.array($).optional()}),$e=e.z.object({response:e.z.object({message:e.z.string()}),config:A,extractMeta:se.nullable(),lastAccuracyEvaluation:oe.optional(),run:S.optional()}).extend(b),Ge=e.z.object({config:A,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),run:S.optional()}).extend(b),Ut=e.z.object({config:A.optional(),chartImage:e.z.string().optional(),data:e.z.unknown().optional(),rubric:_e.optional(),userPrompt:e.z.string().optional(),metadata:D.optional()}).refine(t=>t.config!==void 0||t.chartImage!==void 0,{message:"Provide a chart config or a chart image to judge."}),Bt=e.z.custom(t=>t!==null&&typeof t=="object"),R=e.z.object({config:Bt,userPrompt:e.z.string().max(M).optional().default(""),metadata:D.optional(),chartFamily:B.optional(),datasetRef:vt.optional()}),Oe=R.superRefine(_),Xt=R.extend({maxSuggestionCount:e.z.number().int().min(1).max(4).optional()}).superRefine(_),$t=R.extend({userPrompt:e.z.string().max(M),mutationReceipt:x.optional(),exploreFindingSummary:e.z.string().max(500).optional()}).superRefine(_),Yt=R.extend({mutationReceipt:x.optional()}).superRefine(_),Gt=R.extend({userPrompt:e.z.string().max(M),stages:e.z.array(G).min(1).refine(t=>new Set(t).size===t.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:e.z.string().max(500).optional()}).superRefine(_),Ot=Oe;function Nt(t){return{kind:"image",mimeType:t.mimeType.trim(),dataBase64:T(t.dataBase64)}}function Ft(t){return{kind:"document",mimeType:"application/pdf",dataBase64:T(t.dataBase64)}}function Lt(t){return{kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:T(t.dataBase64),...t.filename!==void 0?{filename:t.filename.trim()}:{}}}function E(t){return Math.ceil(t/3)*4}function T(t){return t.replace(/\s+/g,"")}function q(t){const a=T(t);return a.length===0||a.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(a)}var l="/api/v0",qt=class{constructor(t){this.client=new Qe(t)}async generateGraph(t,a,r){const{storytellingOptions:n,...s}=t,o=await this.client.fetch(`${l}/generate`,s,a,r),u=Ge.parse(o);return this.stripStorytelling(u,n)}async generateGraphStream(t,a){const{storytellingOptions:r,...n}=t,s=await this.client.stream(`${l}/generate`,n,a);return this.wrapStreamWithStorytellingStripping(s,r)}async generateNarrative(t,a,r){const n=await this.client.fetch(`${l}/narrate`,t,a,r);return Ue.parse(n)}async generateNarrativeStream(t,a){return this.client.stream(`${l}/narrate`,t,a)}async generateSuggestions(t,a,r){const n=await this.client.fetch(`${l}/suggestions`,t,a,r);return X.parse(n)}async generateSuggestionsStream(t,a){return this.client.stream(`${l}/suggestions`,t,a)}async generateExploration(t,a,r){const n=await this.client.fetch(`${l}/explore`,t,a,r);return re.parse(n)}async generateExplorationStream(t,a){return this.client.stream(`${l}/explore`,t,a)}async generateAnnotations(t,a,r){const n=await this.client.fetch(`${l}/annotate`,t,a,r);return Be.parse(n)}async generateAnnotationsStream(t,a){return this.client.stream(`${l}/annotate`,t,a)}async generateMutation(t,a,r){const n=await this.client.fetch(`${l}/mutate`,t,a,r);return L.parse(n)}async generateMutationStream(t,a){return this.client.stream(`${l}/mutate`,t,a)}async generatePipeline(t,a,r){const n=await this.client.fetch(`${l}/pipeline`,t,a,r);return Xe.parse(n)}async generatePipelineStream(t,a){return this.client.stream(`${l}/pipeline`,t,a)}async evaluate(t,a){const r=await this.client.fetch(`${l}/evaluate`,t,void 0,a);return Ce.parse(r)}async judge(t,a){const r=await this.client.fetch(`${l}/judge`,t,void 0,a);return Ie.parse(r)}async judgeStream(t,a){return this.client.stream(`${l}/judge`,t,a)}async extractFromProse(t,a,r){const n=await this.client.fetch(`${l}/extract`,t,a,r);return $e.parse(n)}async extractFromProseStream(t,a){return this.client.stream(`${l}/extract`,t,a)}async uploadAttachment(t,a,r){const n=Y(t,a),s=K(t,a),{uploads:o}=await this.createAttachmentUploads({files:[{mimeType:n,...s?{filename:s}:{},...t.size>0?{sizeBytes:t.size}:{}}]},r),u=o[0];if(!u)throw new d("Attachment upload slot was not returned");const c=await fetch(u.uploadUrl,{method:"PUT",headers:{"Content-Type":n},body:t,signal:r});if(!c.ok)throw new d(`Attachment upload failed (HTTP ${c.status})`,{status:c.status,retryable:c.status>=500});const m=await this.completeAttachmentUpload(u.id,r);return de.parse(m)}async uploadDataset(t,a,r){const n=st(t,a);return this.uploadAttachment(t,{...a,mimeType:n},r)}async createAttachmentUploads(t,a){const r=await this.client.postJson(`${l}/attachment-uploads`,t,a);return fe.parse(r)}async completeAttachmentUpload(t,a){const r=await this.client.postJson(`${l}/attachments/${t}/complete`,{},a);return C.parse(r)}async getAttachment(t,a){const r=await this.client.get(`${l}/attachments/${t}`,a);return C.parse(r)}stripStorytelling(t,a){return!a||!t.config.content?t:{...t,config:{...t.config,content:{...t.config.content,...a.excludeTitle&&{title:void 0},...a.excludeSubtitle&&{subtitle:void 0},...a.excludeCaption&&{caption:void 0}}}}}async*wrapStreamWithStorytellingStripping(t,a){for await(const r of t)if(w(r)){const n=this.stripStorytelling(r.data,a);yield{...r,data:n}}else yield r}};exports.AggregationFunctionSchema=Te;exports.AggregationSuggestionSchema=Ae;exports.AiChartTypeEnum=k;exports.AttachmentResponseSchema=C;exports.AttachmentUploadResponseSchema=de;exports.AttachmentUploadSlotResponseSchema=ge;exports.ChartCritiqueIssueCategorySchema=Re;exports.ChartCritiqueIssueSchema=xe;exports.ChartCritiqueIssueSeveritySchema=we;exports.ChartCritiqueReportSchema=Me;exports.ChartFamilySchema=B;exports.ChartFitEntrySchema=Ee;exports.ChartFitFactorKindSchema=Se;exports.ChartFitFactorSchema=ye;exports.ChartFitVerdictSchema=be;exports.ChartJudgeRubricSchema=_e;exports.CreateAttachmentUploadsParamsSchema=bt;exports.CreateAttachmentUploadsResponseSchema=fe;exports.DataObservationKindSchema=ze;exports.DataObservationSchema=ve;exports.EvaluateParamsSchema=Ot;exports.EvaluateResponseSchema=Ce;exports.ExecutionModeSchema=Z;exports.ExploreFindingSchema=ae;exports.ExploreStorySchema=$;exports.ExtractAccuracyEvaluationSchema=oe;exports.ExtractAttachmentInputSchema=je;exports.ExtractAttachmentKindSchema=F;exports.ExtractConfidenceSchema=I;exports.ExtractFromProseParamsSchema=jt;exports.ExtractFromProseResponseSchema=$e;exports.ExtractMetaSchema=se;exports.GenerateAnnotationsResponseSchema=Be;exports.GenerateExplorationResponseSchema=re;exports.GenerateGraphResponseSchema=Ge;exports.GenerateGraphSuggestionsResponseSchema=Et;exports.GenerateMutationResponseSchema=L;exports.GenerateNarrativeParamsSchema=$t;exports.GenerateNarrativeResponseSchema=Ue;exports.GeneratePipelineParamsSchema=Gt;exports.GeneratePipelineResponseSchema=Xe;exports.GenerateSuggestionsParamsSchema=Xt;exports.GenerateSuggestionsResponseSchema=X;exports.GraphGenerationRequestSchema=Oe;exports.GraphyAiSdk=qt;exports.GraphyApiError=d;exports.InvocationBudgetSchema=U;exports.InvocationEffortSchema=J;exports.JudgeParamsSchema=Ut;exports.JudgeResponseSchema=Ie;exports.MAX_BUDGET_COST_USD=lt;exports.MAX_BUDGET_TOTAL_TOKENS=ee;exports.MAX_BUDGET_WALL_CLOCK_MS=Q;exports.MAX_EXTRACT_ATTACHMENTS=gt;exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=he;exports.MAX_EXTRACT_DOCUMENTS=pt;exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=N;exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=O;exports.MAX_EXTRACT_IMAGES=ht;exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=me;exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=ce;exports.MAX_EXTRACT_SPREADSHEETS=dt;exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=ue;exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=le;exports.MAX_SOURCE_TEXT_LENGTH=ie;exports.MAX_STAGED_FILE_BYTES=pe;exports.MAX_USER_PROMPT_LENGTH=M;exports.MetadataSchema=D;exports.MutateNarrationReceiptSchema=x;exports.PipelineAgentNameSchema=G;exports.PipelineStageReasoningSchema=ne;exports.RubricScoresSchema=ke;exports.RunContextSchema=S;exports.StorytellingEffortSchema=V;exports.SuggestionSchema=te;exports.VIZ_LOCALES=W;exports.buildImageAttachment=Nt;exports.buildPdfAttachment=Ft;exports.buildSpreadsheetAttachment=Lt;exports.isAgentCompleteEvent=Ke;exports.isCompleteEvent=w;exports.isErrorEvent=j;exports.isGraphyApiError=Ne;exports.isLlmStepEvent=qe;exports.isPreviewEvent=Fe;exports.isProgressEvent=P;exports.isReasoningEvent=Le;exports.isSessionBudgetEvent=He;exports.isToolCallEvent=Ye;exports.isToolCompleteEvent=We;exports.isToolErrorEvent=Je;
|