@graphysdk/agents-sdk 2.0.0-beta.1786389736654 → 2.0.0-beta.1787130761469

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/README.md CHANGED
@@ -2,39 +2,36 @@
2
2
 
3
3
  TypeScript client for the Graphy Agents API.
4
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
5
  ## Install
12
6
 
13
7
  ```bash
14
- pnpm add @graphysdk/agents-sdk
8
+ npm install @graphysdk/agents-sdk
15
9
  ```
16
10
 
17
- No npm org token and no `@graphysdk/core` dependency required. An Agents API key is still required for HTTP calls.
11
+ You need an [Agents API key](https://docs.graphy.dev/agents/api-keys) for HTTP calls.
12
+
13
+ ## Docs
14
+
15
+ - [Installation](https://docs.graphy.dev/agents/sdk/installation)
16
+ - [Quickstart](https://docs.graphy.dev/agents/quickstart)
17
+ - [Configuration](https://docs.graphy.dev/agents/sdk/configuration)
18
18
 
19
- ## Initial datasets (`datasetRef`)
19
+ ## Datasets
20
20
 
21
- Chart agent requests accept either inline **`config.data`** or a staged **`datasetRef`** (`graphy://attachments/{uuid}`).
22
- Use **`uploadDataset(file)`** to stage CSV, TSV, or XLSX (presigned flow), then pass `datasetRef` on
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.
21
+ Chart requests accept either inline `config.data` or a staged `datasetRef` (`graphy://attachments/{uuid}`).
25
22
 
26
- ## Extract (`POST /api/v0/extract`)
23
+ Upload a CSV, TSV, or XLSX file with `uploadDataset(file)`, then pass the returned `datasetRef` to `generateGraph`, `generateGraphStream`, and the other graph-generation methods. Do not send both inline data and a `datasetRef`.
27
24
 
28
- Prefer **`attachments[]`** over deprecated **`images[]`** (do not send both).
25
+ See the [Agents docs](https://docs.graphy.dev/agents/sdk/installation) for size limits.
29
26
 
30
- Each attachment uses **`kind`**:
27
+ ## Extract
31
28
 
32
- | `kind` | Purpose | Helper |
33
- | --------------- | ------------------------------------- | ---------------------------- |
34
- | `"image"` | PNG / JPEG / WebP / GIF | `buildImageAttachment` |
35
- | `"document"` | PDF (`application/pdf`) | `buildPdfAttachment` |
36
- | `"spreadsheet"` | Excel `.xlsx` (OOXML ZIP on the wire) | `buildSpreadsheetAttachment` |
29
+ Prefer `attachments[]` over `images[]`. Do not send both.
37
30
 
38
- Spreadsheet rows must use MIME **`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`**, RFC 4648 **base64** payload (no `data:` prefix), and optional **`filename`**.
31
+ | `kind` | Purpose | Helper |
32
+ | --------------- | -------------------- | ---------------------------- |
33
+ | `"image"` | PNG, JPEG, WebP, GIF | `buildImageAttachment` |
34
+ | `"document"` | PDF | `buildPdfAttachment` |
35
+ | `"spreadsheet"` | Excel `.xlsx` | `buildSpreadsheetAttachment` |
39
36
 
40
- See the [Agents API docs](https://docs.graphy.dev/agents/overview) for route limits and runtime behaviour.
37
+ Spreadsheet payloads must be RFC 4648 base64 (no `data:` prefix) with MIME type `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
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;
1
+ var Ke=Object.create;var Y=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var Ze=(t,a,r,n)=>{if(a&&typeof a=="object"||typeof a=="function")for(let s of We(a))!Ve.call(t,s)&&s!==r&&Y(t,s,{get:()=>a[s],enumerable:!(n=Ye(a,s))||n.enumerable});return t};var _=(t,a,r)=>(r=t!=null?Ke(Je(t)):{},Ze(a||!t||!t.__esModule?Y(r,"default",{value:t,enumerable:!0}):r,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let e=require("zod");var p=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}},Qe=t=>t instanceof p,I=t=>t.type==="progress",k=t=>t.type==="complete",U=t=>t.type==="error",et=t=>t.type==="preview",tt=t=>t.type==="reasoning",at=t=>t.type==="llm_step",rt=t=>t.type==="session_budget",nt=t=>t.type==="agent_complete",st=t=>t.type==="tool_call",ot=t=>t.type==="tool_complete",it=t=>t.type==="tool_error",ct="graphy:keyless-token:";function mt(t){const a=r=>`${ct}${r}`;return{read:r=>Promise.resolve(t.getItem(a(r))??void 0),write:(r,n)=>Promise.resolve(t.setItem(a(r),n)),clear:r=>Promise.resolve(t.removeItem(a(r)))}}function lt(t){async function a(){try{const{readFile:n}=await import("node:fs/promises"),s=JSON.parse(await n(t,"utf8"));if(typeof s=="object"&&s!==null&&"tokens"in s){const{tokens:o}=s;if(typeof o=="object")return{tokens:o}}}catch{}return{tokens:{}}}async function r(n){const{mkdir:s,writeFile:o}=await import("node:fs/promises"),{default:c}=await import("node:path");await s(c.dirname(t),{recursive:!0,mode:448}),await o(t,JSON.stringify(n,null,2),{mode:384})}return{read:async n=>(await a()).tokens[n],write:async(n,s)=>{await r({tokens:{...(await a()).tokens,[n]:s}})},clear:async n=>{const{[n]:s,...o}=(await a()).tokens;await r({tokens:o})}}}async function ut(t={}){const a="storage"in t?t.storage:globalThis.localStorage;if(a)return mt(a);const r="homeDir"in t?t.homeDir:await pt();if(!r)return ht();const{default:n}=await import("node:path");return lt(n.join(r,".graphy","config.json"))}function ht(){const t=new Map;return{read:a=>Promise.resolve(t.get(a)),write:(a,r)=>Promise.resolve(void t.set(a,r)),clear:a=>Promise.resolve(void t.delete(a))}}async function pt(){try{const{homedir:t}=await import("node:os");return t()||void 0}catch{return}}function dt(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 gt="[GRAPHY]",ft="X-Graphy-Anonymous-Token";function W(){return typeof process>"u"?void 0:process.env.GRAPHY_TOKEN?.trim()||void 0}var St=class{constructor(t){this.tag=gt;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?.trim()||void 0,this.credentials=t.credentials,this.configuredTokenStore=t.tokenStore,this.keyless=!this.apiKey&&t.credentials!=="include",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 I(t)}static isCompleteEvent(t){return k(t)}static isErrorEvent(t){return U(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 i of this.parseSSE(o)){if(I(i)&&r&&r(i),k(i))return i.data;if(U(i)){const l=Date.now()-s;throw this.logger.error(`${this.tag} Server error: ${t} ${l}ms`,i.error),new p(i.error,{code:i.code,retryable:i.retryable??!1})}}const c=Date.now()-s;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${c}ms`),new p("Stream ended without completion")}else return await o.json()}catch(o){const c=Date.now()-s;throw this.logger.error(`${this.tag} Fetch failed: ${t} ${c}ms`,o),o instanceof p,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 resolveTokenStore(){return this.tokenStorePromise??=this.configuredTokenStore?Promise.resolve(this.configuredTokenStore):ut(),this.tokenStorePromise}async resolveAuthToken(){if(this.apiKey)return this.apiKey;if(this.keyless)return this.keylessToken??=W()??await(await this.resolveTokenStore()).read(this.baseUrl),this.keylessToken}async discardKeylessToken(){this.keylessToken=void 0,await(await this.resolveTokenStore()).clear(this.baseUrl)}async keepMintedToken(t){if(!this.keyless)return;const a=t.headers.get(ft);!a||a===this.keylessToken||(this.keylessToken=a,await(await this.resolveTokenStore()).write(this.baseUrl,a))}async*parseSSE(t){if(!t.body)throw new p("Response body is null");const a=t.body.getReader(),r=new TextDecoder;let n="",s="",o="";try{for(;;){const{done:c,value:i}=await a.read();if(c)break;n+=r.decode(i,{stream:!0});const l=n.split(/\r?\n/);n=l.pop()||"";for(const u of l)if(u.startsWith("event: "))s=u.slice(7).trim();else if(u.startsWith("data: "))o+=(o?`
2
+ `:"")+u.slice(6);else if(u.trim()===""&&o){try{const h=JSON.parse(o),d=dt(s,h);if(d===null){s="",o="";continue}if(yield d,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",o=!1){if(!t.startsWith("/"))throw new p("Invalid endpoint: must start with /");const c=new URL(t,this.baseUrl);if(c.origin!==new URL(this.baseUrl).origin)throw new p("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${c}`);const i=new AbortController,l=setTimeout(()=>i.abort(),this.timeout),u=()=>i.abort();r&&r.addEventListener("abort",u);try{const h={"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache"},d=await this.resolveAuthToken();d&&(h.Authorization=`Bearer ${d}`);const g=await fetch(c,{method:s,headers:h,signal:i.signal,...this.credentials?{credentials:this.credentials}:{},...s==="POST"&&{body:JSON.stringify(a)}});if(await this.keepMintedToken(g),g.status===401&&d&&this.keyless&&!o&&!W())return await this.discardKeylessToken(),this.makeRequest(t,a,r,n,s,!0);if(!g.ok){let b=`HTTP ${g.status}`,S;try{const z=await g.json();if(typeof z=="object"&&z!==null){const T=z;typeof T.message=="string"?b=T.message:typeof T.error=="string"&&(b=T.error),typeof T.code=="string"&&(S=T.code)}}catch{}const f=S!=="QUOTA_EXCEEDED"&&(g.status>=500||g.status===429),He=new p(b,{status:g.status,code:S,retryable:f});if(f&&n<this.retryConfig.attempts&&!r?.aborted){const z=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${z}ms (attempt ${n+1})`),await this.sleep(z),this.makeRequest(t,a,r,n+1,s)}throw this.logger.error(`${this.tag} Request failed: ${t} (${g.status}) - ${b}`),He}return this.logger.debug(`${this.tag} Connected: ${t}`),g}catch(h){if(h instanceof p)throw h;if(h instanceof Error&&h.name==="AbortError")throw this.logger.debug(`${this.tag} Aborted: ${t}`),h;if(n<this.retryConfig.attempts&&!r?.aborted){const d=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${d}ms`),await this.sleep(d),this.makeRequest(t,a,r,n+1,s)}throw this.logger.error(`${this.tag} Network error: ${t}`,h),new p("Network error",{retryable:!0})}finally{clearTimeout(l),r&&r.removeEventListener("abort",u)}}async makeMultipartRequest(t,a,r,n=1){if(!t.startsWith("/"))throw new p("Invalid endpoint: must start with /");const s=new URL(t,this.baseUrl);if(s.origin!==new URL(this.baseUrl).origin)throw new p("Endpoint resolved to unexpected origin");const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout),i=()=>o.abort();r&&r.addEventListener("abort",i);try{const l={Accept:"application/json"};this.apiKey&&(l.Authorization=`Bearer ${this.apiKey}`);const u=await fetch(s,{method:"POST",headers:l,body:a,signal:o.signal,...this.credentials?{credentials:this.credentials}:{}});if(!u.ok){let h=`HTTP ${u.status}`,d;try{const S=await u.json();if(typeof S=="object"&&S!==null){const f=S;typeof f.message=="string"?h=f.message:typeof f.error=="string"&&(h=f.error),typeof f.code=="string"&&(d=f.code)}}catch{}const g=d!=="QUOTA_EXCEEDED"&&(u.status>=500||u.status===429),b=new p(h,{status:u.status,code:d,retryable:g});if(g&&n<this.retryConfig.attempts&&!r?.aborted){const S=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return await this.sleep(S),this.makeMultipartRequest(t,a,r,n+1)}throw b}return u}catch(l){if(l instanceof p||l instanceof Error&&l.name==="AbortError")throw l;if(n<this.retryConfig.attempts&&!r?.aborted){const u=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return await this.sleep(u),this.makeMultipartRequest(t,a,r,n+1)}throw new p("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",i)}}},yt={".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 V(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 Z(t,a){const r=a?.mimeType?.trim();if(r)return r;const n=t.type.trim();if(n.length>0)return n;const s=V(t,a);if(s){const o=bt(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 bt(t){const a=t.lastIndexOf(".");if(a<0)return;const r=t.slice(a).toLowerCase();return yt[r]}var Et=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]),vt="uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)";function zt(t){return Et.has(t.trim())}function Tt(t,a){const r=Z(t,a);if(!zt(r))throw new Error(vt);return r}var At=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()}),Ct=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()}),_t=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:Ct,exceeded:e.z.boolean(),exceededDimensions:e.z.array(e.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:e.z.string().optional()}),ua=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()}),E={usage:At.optional(),budget:_t.optional()};function wt(t){const{data:a}=t;return a===void 0?!1:a.columns.length>0||a.rows.length>0}function R(t,a){const r=t.config.data!==void 0,n=wt(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 Q=["EN_GB","EN_US","AR","PT_PT"],ee=e.z.enum(["low","medium","high"]),te=e.z.enum(["none","low","medium","high"]),ae=e.z.enum(["agentic","fast"]),re=3e5,ne=5e5,Rt=10,B=e.z.object({maxWallClockMs:e.z.number().positive().max(re).optional(),maxTotalTokens:e.z.number().int().positive().max(ne).optional(),maxCostUsd:e.z.number().positive().max(10).optional(),trackUsage:e.z.boolean().optional()}),xt=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()}),ha=e.z.object({limits:B,consumed:xt,exceeded:e.z.boolean(),exceededDimensions:e.z.array(e.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:e.z.string().optional()}),M=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()}),y=e.z.object({runId:e.z.string(),trackingId:e.z.string(),callId:e.z.string().optional()}),D=1e4,O=e.z.enum(["comparison","relationship","distribution","composition"]),P=e.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),se=e.z.object({dataPrepPrompt:e.z.string(),chartType:P,summary:e.z.string()}),$=e.z.object({suggestions:e.z.array(se),run:y.optional()}).extend(E),oe=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:O.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.")}),G=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(oe).describe("Child findings, sorted by quadrant score desc.")}),ie=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),stories:e.z.array(G),run:y.optional()}).extend(E),N=e.z.enum(["explore","mutate","narrate","annotate"]),ce=e.z.object({agent:N,summary:e.z.string(),steps:e.z.array(e.z.string()).optional()}),X=e.z.enum(["high","medium","low"]),me=e.z.object({confidence:X,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:X,quote:e.z.string().optional()})).optional()}),le=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()}),ue=5e5,kt=8,he=2*1024*1024,pe=7*1024*1024,Mt=2,F=6*1024*1024,L=8*1024*1024,Dt=2,de=F,ge=L,fe=12*1024*1024,Pt=12,jt=50*1024*1024,Se=jt,q=e.z.enum(["image","document","spreadsheet","tabular"]),It=e.z.enum(["pending","ready","failed"]),w=e.z.object({id:e.z.string().uuid(),uri:e.z.string(),status:It,kind:q.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()}),ye=w.extend({status:e.z.literal("ready"),kind:q,sizeBytes:e.z.number().int().positive()}),Ut=e.z.object({mimeType:e.z.string().min(1),filename:e.z.string().max(512).optional(),sizeBytes:e.z.number().int().positive().max(Se).optional()}),Xt=e.z.object({files:e.z.array(Ut).min(1).max(12)}),be=w.extend({status:e.z.literal("pending"),uploadUrl:e.z.string().url()}),Ee=e.z.object({uploads:e.z.array(be)}),Bt=$,ve=e.z.enum(["deal-breaker","pro","con","family","continuity"]),ze=e.z.object({kind:ve,label:e.z.string(),weight:e.z.number(),reason:e.z.string()}),Te=e.z.enum(["ok","disqualified"]),Ae=e.z.object({rank:e.z.number().int().positive(),type:P,score:e.z.number(),verdict:Te,factors:e.z.array(ze)}),Ce=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"]),_e=e.z.object({kind:Ce,message:e.z.string()}),we=e.z.enum(["sum","avg","count","min","max"]),Re=e.z.object({dimensionName:e.z.string(),dimensionLabel:e.z.string(),measureName:e.z.string().nullable(),measureLabel:e.z.string().nullable(),fn:we,chartType:P,score:e.z.number(),message:e.z.string()}),xe=e.z.object({ranking:e.z.array(Ae),observations:e.z.array(_e).optional().default([]),suggestions:e.z.array(Re).optional().default([]),run:y.optional()}),ke=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()}),Me=e.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),De=e.z.enum(["info","low","medium","high"]),Pe=e.z.object({category:Me,severity:De,observation:e.z.string(),rationale:e.z.string().optional(),suggestedChange:e.z.string().optional(),configPaths:e.z.array(e.z.string()).optional()}),je=e.z.object({overallSummary:e.z.string(),overallSeverity:e.z.enum(["none","low","medium","high"]).optional(),issues:e.z.array(Pe)}),Ie=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()}),Ot=e.z.enum(Q),j=e.z.object({callId:e.z.string().max(256).optional(),locale:Ot.optional(),effort:ee.optional(),storytellingEffort:te.optional().default("low"),budget:B.optional(),executionMode:ae.optional(),enforceTableRowCap:e.z.boolean().optional()}),Ue=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,$t=e.z.string().regex(Ue,"datasetRef must be graphy://attachments/{uuid}"),Gt=v(he),J=v(pe),Nt=v(F),Ft=v(L),Lt=v(de),qt=v(ge),Ht=v(fe),Kt=/^image\/(png|jpeg|jpg|webp|gif)$/i,Xe=e.z.object({mimeType:e.z.string().min(1).refine(t=>Kt.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(Gt).refine(K,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Yt=Xe.extend({kind:e.z.literal("image")}),Wt=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(Nt).refine(K,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Jt=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(Lt).refine(K,{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"]}),Be=e.z.discriminatedUnion("kind",[Yt,Wt,Jt]),Vt=e.z.string().regex(Ue,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),Zt=e.z.object({sourceText:e.z.string().max(ue).default(""),images:e.z.array(Xe).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:e.z.array(Be).max(12).optional(),attachmentRefs:e.z.array(Vt).max(12).optional(),metadata:j.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((S,f)=>S+A(f.dataBase64).length,0)>J&&a.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]});let c=0,i=0,l=0,u=0,h=0,d=0,g=0;for(const S of s){const f=A(S.dataBase64).length;switch(g+=f,S.kind){case"image":c+=1,u+=f;break;case"document":i+=1,h+=f;break;case"spreadsheet":l+=1,d+=f;break}}c>8&&a.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),i>2&&a.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),l>2&&a.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const b=c<=8&&i<=2&&l<=2;s.length>0&&b&&(u>J&&a.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>Ft&&a.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>qt&&a.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>Ht&&a.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))}),Qt=e.z.object({capturedAt:e.z.string(),chartId:e.z.string()}),Oe=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string()),critiqueCommitted:e.z.boolean()}),critiqueReport:je.nullable(),chartVisionAudit:Qt.nullable().optional().default(null),rubricScores:Ie.nullable().optional().default(null),run:y.optional()}).extend(E),C=e.z.custom(t=>t!==null&&typeof t=="object"),$e=e.z.object({response:e.z.object({message:e.z.string()}),config:C,run:y.optional()}).extend(E),Ge=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),config:C,run:y.optional()}).extend(E),H=e.z.object({response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),config:C,mutationReceipt:M.optional(),warnings:e.z.array(e.z.string()).optional(),run:y.optional()}).extend(E),Ne=H.extend({reasoning:e.z.array(ce),stories:e.z.array(G).optional()}),Fe=e.z.object({response:e.z.object({message:e.z.string()}),config:C,extractMeta:me.nullable(),lastAccuracyEvaluation:le.optional(),run:y.optional()}).extend(E),Le=e.z.object({config:C,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string())}),run:y.optional()}).extend(E),ea=e.z.object({config:C.optional(),chartImage:e.z.string().optional(),data:e.z.unknown().optional(),rubric:ke.optional(),userPrompt:e.z.string().optional(),metadata:j.optional()}).refine(t=>t.config!==void 0||t.chartImage!==void 0,{message:"Provide a chart config or a chart image to judge."}),ta=e.z.custom(t=>t!==null&&typeof t=="object"),x=e.z.object({config:ta,userPrompt:e.z.string().max(D).optional().default(""),metadata:j.optional(),chartFamily:O.optional(),datasetRef:$t.optional()}),qe=x.superRefine(R),aa=x.extend({maxSuggestionCount:e.z.number().int().min(1).max(4).optional()}).superRefine(R),ra=x.extend({userPrompt:e.z.string().max(D),mutationReceipt:M.optional(),exploreFindingSummary:e.z.string().max(500).optional()}).superRefine(R),pa=x.extend({mutationReceipt:M.optional()}).superRefine(R),na=x.extend({userPrompt:e.z.string().max(D),stages:e.z.array(N).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(R),sa=qe;function oa(t){return{kind:"image",mimeType:t.mimeType.trim(),dataBase64:A(t.dataBase64)}}function ia(t){return{kind:"document",mimeType:"application/pdf",dataBase64:A(t.dataBase64)}}function ca(t){return{kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:A(t.dataBase64),...t.filename!==void 0?{filename:t.filename.trim()}:{}}}function v(t){return Math.ceil(t/3)*4}function A(t){return t.replace(/\s+/g,"")}function K(t){const a=A(t);return a.length===0||a.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(a)}var m="/api/v0",ma=class{constructor(t){this.client=new St(t)}async generateGraph(t,a,r){const{storytellingOptions:n,...s}=t,o=await this.client.fetch(`${m}/generate`,s,a,r),c=Le.parse(o);return this.stripStorytelling(c,n)}async generateGraphStream(t,a){const{storytellingOptions:r,...n}=t,s=await this.client.stream(`${m}/generate`,n,a);return this.wrapStreamWithStorytellingStripping(s,r)}async generateNarrative(t,a,r){const n=await this.client.fetch(`${m}/narrate`,t,a,r);return $e.parse(n)}async generateNarrativeStream(t,a){return this.client.stream(`${m}/narrate`,t,a)}async generateSuggestions(t,a,r){const n=await this.client.fetch(`${m}/suggestions`,t,a,r);return $.parse(n)}async generateSuggestionsStream(t,a){return this.client.stream(`${m}/suggestions`,t,a)}async generateExploration(t,a,r){const n=await this.client.fetch(`${m}/explore`,t,a,r);return ie.parse(n)}async generateExplorationStream(t,a){return this.client.stream(`${m}/explore`,t,a)}async generateAnnotations(t,a,r){const n=await this.client.fetch(`${m}/annotate`,t,a,r);return Ge.parse(n)}async generateAnnotationsStream(t,a){return this.client.stream(`${m}/annotate`,t,a)}async generateMutation(t,a,r){const n=await this.client.fetch(`${m}/mutate`,t,a,r);return H.parse(n)}async generateMutationStream(t,a){return this.client.stream(`${m}/mutate`,t,a)}async generatePipeline(t,a,r){const n=await this.client.fetch(`${m}/pipeline`,t,a,r);return Ne.parse(n)}async generatePipelineStream(t,a){return this.client.stream(`${m}/pipeline`,t,a)}async evaluate(t,a){const r=await this.client.fetch(`${m}/evaluate`,t,void 0,a);return xe.parse(r)}async judge(t,a){const r=await this.client.fetch(`${m}/judge`,t,void 0,a);return Oe.parse(r)}async judgeStream(t,a){return this.client.stream(`${m}/judge`,t,a)}async extractFromProse(t,a,r){const n=await this.client.fetch(`${m}/extract`,t,a,r);return Fe.parse(n)}async extractFromProseStream(t,a){return this.client.stream(`${m}/extract`,t,a)}async uploadAttachment(t,a,r){const n=Z(t,a),s=V(t,a),{uploads:o}=await this.createAttachmentUploads({files:[{mimeType:n,...s?{filename:s}:{},...t.size>0?{sizeBytes:t.size}:{}}]},r),c=o[0];if(!c)throw new p("Attachment upload slot was not returned");const i=await fetch(c.uploadUrl,{method:"PUT",headers:{"Content-Type":n},body:t,signal:r});if(!i.ok)throw new p(`Attachment upload failed (HTTP ${i.status})`,{status:i.status,retryable:i.status>=500});const l=await this.completeAttachmentUpload(c.id,r);return ye.parse(l)}async uploadDataset(t,a,r){const n=Tt(t,a);return this.uploadAttachment(t,{...a,mimeType:n},r)}async createAttachmentUploads(t,a){const r=await this.client.postJson(`${m}/attachment-uploads`,t,a);return Ee.parse(r)}async completeAttachmentUpload(t,a){const r=await this.client.postJson(`${m}/attachments/${t}/complete`,{},a);return w.parse(r)}async getAttachment(t,a){const r=await this.client.get(`${m}/attachments/${t}`,a);return w.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(k(r)){const n=this.stripStorytelling(r.data,a);yield{...r,data:n}}else yield r}};exports.AggregationFunctionSchema=we;exports.AggregationSuggestionSchema=Re;exports.AiChartTypeEnum=P;exports.AttachmentResponseSchema=w;exports.AttachmentUploadResponseSchema=ye;exports.AttachmentUploadSlotResponseSchema=be;exports.ChartCritiqueIssueCategorySchema=Me;exports.ChartCritiqueIssueSchema=Pe;exports.ChartCritiqueIssueSeveritySchema=De;exports.ChartCritiqueReportSchema=je;exports.ChartFamilySchema=O;exports.ChartFitEntrySchema=Ae;exports.ChartFitFactorKindSchema=ve;exports.ChartFitFactorSchema=ze;exports.ChartFitVerdictSchema=Te;exports.ChartJudgeRubricSchema=ke;exports.CreateAttachmentUploadsParamsSchema=Xt;exports.CreateAttachmentUploadsResponseSchema=Ee;exports.DataObservationKindSchema=Ce;exports.DataObservationSchema=_e;exports.EvaluateParamsSchema=sa;exports.EvaluateResponseSchema=xe;exports.ExecutionModeSchema=ae;exports.ExploreFindingSchema=oe;exports.ExploreStorySchema=G;exports.ExtractAccuracyEvaluationSchema=le;exports.ExtractAttachmentInputSchema=Be;exports.ExtractAttachmentKindSchema=q;exports.ExtractConfidenceSchema=X;exports.ExtractFromProseParamsSchema=Zt;exports.ExtractFromProseResponseSchema=Fe;exports.ExtractMetaSchema=me;exports.GenerateAnnotationsResponseSchema=Ge;exports.GenerateExplorationResponseSchema=ie;exports.GenerateGraphResponseSchema=Le;exports.GenerateGraphSuggestionsResponseSchema=Bt;exports.GenerateMutationResponseSchema=H;exports.GenerateNarrativeParamsSchema=ra;exports.GenerateNarrativeResponseSchema=$e;exports.GeneratePipelineParamsSchema=na;exports.GeneratePipelineResponseSchema=Ne;exports.GenerateSuggestionsParamsSchema=aa;exports.GenerateSuggestionsResponseSchema=$;exports.GraphGenerationRequestSchema=qe;exports.GraphyAiSdk=ma;exports.GraphyApiError=p;exports.InvocationBudgetSchema=B;exports.InvocationEffortSchema=ee;exports.JudgeParamsSchema=ea;exports.JudgeResponseSchema=Oe;exports.MAX_BUDGET_COST_USD=Rt;exports.MAX_BUDGET_TOTAL_TOKENS=ne;exports.MAX_BUDGET_WALL_CLOCK_MS=re;exports.MAX_EXTRACT_ATTACHMENTS=Pt;exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=fe;exports.MAX_EXTRACT_DOCUMENTS=Mt;exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=L;exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=F;exports.MAX_EXTRACT_IMAGES=kt;exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=pe;exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=he;exports.MAX_EXTRACT_SPREADSHEETS=Dt;exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=ge;exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=de;exports.MAX_SOURCE_TEXT_LENGTH=ue;exports.MAX_STAGED_FILE_BYTES=Se;exports.MAX_USER_PROMPT_LENGTH=D;exports.MetadataSchema=j;exports.MutateNarrationReceiptSchema=M;exports.PipelineAgentNameSchema=N;exports.PipelineStageReasoningSchema=ce;exports.RubricScoresSchema=Ie;exports.RunContextSchema=y;exports.StorytellingEffortSchema=te;exports.SuggestionSchema=se;exports.VIZ_LOCALES=Q;exports.buildImageAttachment=oa;exports.buildPdfAttachment=ia;exports.buildSpreadsheetAttachment=ca;exports.isAgentCompleteEvent=nt;exports.isCompleteEvent=k;exports.isErrorEvent=U;exports.isGraphyApiError=Qe;exports.isLlmStepEvent=at;exports.isPreviewEvent=et;exports.isProgressEvent=I;exports.isReasoningEvent=tt;exports.isSessionBudgetEvent=rt;exports.isToolCallEvent=st;exports.isToolCompleteEvent=ot;exports.isToolErrorEvent=it;
package/dist/index.d.ts CHANGED
@@ -432,6 +432,11 @@ export declare interface ClientConfig {
432
432
  apiKey?: string;
433
433
  /** Base URL of the Graphy Agents API (e.g. `"https://agents.graphy.dev"`). */
434
434
  baseUrl: string;
435
+ /**
436
+ * Where a keyless token is kept between calls. Defaults to `localStorage` in a browser and
437
+ * `~/.graphy/config.json` on Node. Only consulted when no `apiKey` and no cookie auth are set.
438
+ */
439
+ tokenStore?: KeylessTokenStore;
435
440
  /**
436
441
  * `fetch` credentials mode. Set to `'include'` for browser callers that authenticate with the
437
442
  * agents-api session cookie (cross-origin requires credentialed CORS on the API). Left unset for
@@ -1922,8 +1927,9 @@ export declare const GraphGenerationRequestSchema: z.ZodObject<{
1922
1927
  export declare class GraphyAiSdk {
1923
1928
  private client;
1924
1929
  /**
1925
- * @param config - SDK configuration including API key and base URL.
1926
- * @throws {Error} If `apiKey` is empty or `baseUrl` is invalid.
1930
+ * @param config - SDK configuration. Omit `apiKey` to run keyless: the server issues a token on
1931
+ * the first call and the SDK keeps it for later ones.
1932
+ * @throws {Error} If `baseUrl` is invalid.
1927
1933
  */
1928
1934
  constructor(config: ClientConfig);
1929
1935
  /**
@@ -3515,6 +3521,13 @@ export declare const JudgeResponseSchema: z.ZodObject<{
3515
3521
  }, z.core.$strip>>;
3516
3522
  }, z.core.$strip>;
3517
3523
 
3524
+ /** Without this, every process start mints a fresh token and hits the server's hourly cap. */
3525
+ declare interface KeylessTokenStore {
3526
+ read: (baseUrl: string) => Promise<string | undefined>;
3527
+ write: (baseUrl: string, token: string) => Promise<void>;
3528
+ clear: (baseUrl: string) => Promise<void>;
3529
+ }
3530
+
3518
3531
  /** Per-step LLM usage during agent execution. */
3519
3532
  export declare interface LlmStepEvent {
3520
3533
  type: 'llm_step';