@vertesia/client 0.72.0 → 0.74.0

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.
Files changed (51) hide show
  1. package/lib/cjs/AccountApi.js +2 -3
  2. package/lib/cjs/AccountApi.js.map +1 -1
  3. package/lib/cjs/AppsApi.js +33 -0
  4. package/lib/cjs/AppsApi.js.map +1 -1
  5. package/lib/esm/AccountApi.js +2 -3
  6. package/lib/esm/AccountApi.js.map +1 -1
  7. package/lib/esm/AppsApi.js +33 -0
  8. package/lib/esm/AppsApi.js.map +1 -1
  9. package/lib/tsconfig.tsbuildinfo +1 -1
  10. package/lib/types/AccountApi.d.ts +1 -3
  11. package/lib/types/AccountApi.d.ts.map +1 -1
  12. package/lib/types/AccountsApi.d.ts +0 -1
  13. package/lib/types/AnalyticsApi.d.ts +0 -1
  14. package/lib/types/ApiKeysApi.d.ts +0 -1
  15. package/lib/types/AppsApi.d.ts +16 -2
  16. package/lib/types/AppsApi.d.ts.map +1 -1
  17. package/lib/types/CommandsApi.d.ts +0 -1
  18. package/lib/types/EnvironmentsApi.d.ts +0 -1
  19. package/lib/types/GroupsApi.d.ts +0 -1
  20. package/lib/types/IamApi.d.ts +0 -1
  21. package/lib/types/InteractionBase.d.ts +0 -1
  22. package/lib/types/InteractionsApi.d.ts +0 -1
  23. package/lib/types/ProjectsApi.d.ts +0 -1
  24. package/lib/types/PromptsApi.d.ts +0 -1
  25. package/lib/types/RefsApi.d.ts +0 -1
  26. package/lib/types/RunsApi.d.ts +0 -1
  27. package/lib/types/StreamSource.d.ts +0 -1
  28. package/lib/types/TrainingApi.d.ts +0 -1
  29. package/lib/types/UsersApi.d.ts +0 -1
  30. package/lib/types/client.d.ts +0 -1
  31. package/lib/types/execute.d.ts +0 -1
  32. package/lib/types/index.d.ts +0 -1
  33. package/lib/types/nodejs/NodeStreamSource.d.ts +0 -1
  34. package/lib/types/nodejs/index.d.ts +0 -1
  35. package/lib/types/store/AgentsApi.d.ts +0 -1
  36. package/lib/types/store/AnalyzeDocApi.d.ts +0 -1
  37. package/lib/types/store/CollectionsApi.d.ts +0 -1
  38. package/lib/types/store/CommandsApi.d.ts +0 -1
  39. package/lib/types/store/EmbeddingsApi.d.ts +0 -1
  40. package/lib/types/store/FilesApi.d.ts +0 -1
  41. package/lib/types/store/ObjectsApi.d.ts +0 -1
  42. package/lib/types/store/TypesApi.d.ts +0 -1
  43. package/lib/types/store/WorkflowsApi.d.ts +0 -1
  44. package/lib/types/store/client.d.ts +0 -1
  45. package/lib/types/store/errors.d.ts +0 -1
  46. package/lib/types/store/index.d.ts +0 -1
  47. package/lib/vertesia-client.js +1 -1
  48. package/lib/vertesia-client.js.map +1 -1
  49. package/package.json +4 -4
  50. package/src/AccountApi.ts +2 -3
  51. package/src/AppsApi.ts +36 -2
@@ -1,5 +1,5 @@
1
1
  import { ApiTopic, ClientBase } from "@vertesia/api-fetch-client";
2
- import type { AppInstallation, AppInstallationKind, AppInstallationWithManifest, AppManifest, AppManifestData } from "@vertesia/common";
2
+ import type { AppInstallation, AppInstallationKind, AppInstallationWithManifest, AppManifest, AppManifestData, ProjectRef, RequireAtLeastOne } from "@vertesia/common";
3
3
  export interface OrphanedAppInstallation extends Omit<AppInstallation, 'manifest'> {
4
4
  manifest: null;
5
5
  }
@@ -23,6 +23,21 @@ export default class AppsApi extends ApiTopic {
23
23
  * @returns
24
24
  */
25
25
  uninstall(installationId: string): Promise<any>;
26
+ /**
27
+ * get an app unstallation given its name or null if the app is not installed
28
+ * @returns
29
+ */
30
+ getAppInstallationByName(appName: string): Promise<AppInstallationWithManifest | null>;
31
+ /**
32
+ * Get the project refs where the application is visible by the current user.
33
+ * The application is specified either by id or by name.
34
+ * @param param0
35
+ * @returns
36
+ */
37
+ getAppInstallationProjects(app: RequireAtLeastOne<{
38
+ id?: string;
39
+ name?: string;
40
+ }, 'id' | 'name'>): Promise<ProjectRef[]>;
26
41
  /**
27
42
  * Get the apps installed for the current authenticated project
28
43
  * @param kind - the kind of app installations to filter by (e.g., 'agent', 'tool', etc.)
@@ -41,4 +56,3 @@ export default class AppsApi extends ApiTopic {
41
56
  */
42
57
  listInstallations(): Promise<AppInstallation[]>;
43
58
  }
44
- //# sourceMappingURL=AppsApi.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AppsApi.d.ts","sourceRoot":"","sources":["../../src/AppsApi.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,KAAK,EAAE,eAAe,EAAE,mBAAmB,EAA0B,2BAA2B,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEhK,MAAM,WAAW,uBAAwB,SAAQ,IAAI,CAAC,eAAe,EAAE,UAAU,CAAC;IAC9E,QAAQ,EAAE,IAAI,CAAC;CAClB;AAED,MAAM,CAAC,OAAO,OAAO,OAAQ,SAAQ,QAAQ;gBAE7B,MAAM,EAAE,UAAU;IAI9B,MAAM,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,WAAW,CAAC;IAIvD,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,WAAW,CAAC;IAInE;;;OAGG;IACH,IAAI,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;IAI9B;;;OAGG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,OAAO,CAAC,eAAe,CAAC;IAShF;;;;OAIG;IACH,SAAS,CAAC,cAAc,EAAE,MAAM;IAIhC;;;OAGG;IACH,gBAAgB,CAAC,IAAI,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,2BAA2B,EAAE,CAAC;IAQpF;;;;;;OAMG;IACH,sBAAsB,IAAI,OAAO,CAAC,CAAC,2BAA2B,GAAG,uBAAuB,CAAC,EAAE,CAAC;IAI5F;;OAEG;IACH,iBAAiB,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;CAKlD"}
1
+ {"version":3,"file":"AppsApi.d.ts","sourceRoot":"","sources":["../../src/AppsApi.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAe,MAAM,4BAA4B,CAAC;AAC/E,OAAO,KAAK,EAAE,eAAe,EAAE,mBAAmB,EAA0B,2BAA2B,EAAE,WAAW,EAAE,eAAe,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE/L,MAAM,WAAW,uBAAwB,SAAQ,IAAI,CAAC,eAAe,EAAE,UAAU,CAAC;IAC9E,QAAQ,EAAE,IAAI,CAAC;CAClB;AAED,MAAM,CAAC,OAAO,OAAO,OAAQ,SAAQ,QAAQ;gBAE7B,MAAM,EAAE,UAAU;IAI9B,MAAM,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,WAAW,CAAC;IAIvD,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,WAAW,CAAC;IAInE;;;OAGG;IACH,IAAI,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;IAI9B;;;OAGG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,OAAO,CAAC,eAAe,CAAC;IAShF;;;;OAIG;IACH,SAAS,CAAC,cAAc,EAAE,MAAM;IAIhC;;;OAGG;IACH,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,2BAA2B,GAAG,IAAI,CAAC;IAUtF;;;;;OAKG;IACH,0BAA0B,CAAC,GAAG,EAAE,iBAAiB,CAAC;QAAE,EAAE,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,IAAI,GAAG,MAAM,CAAC,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAcxH;;;OAGG;IACH,gBAAgB,CAAC,IAAI,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,2BAA2B,EAAE,CAAC;IAQpF;;;;;;OAMG;IACH,sBAAsB,IAAI,OAAO,CAAC,CAAC,2BAA2B,GAAG,uBAAuB,CAAC,EAAE,CAAC;IAI5F;;OAEG;IACH,iBAAiB,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;CAKlD"}
@@ -8,4 +8,3 @@ export default class CommandsApi extends ApiTopic {
8
8
  isNamespaceAvailable(name: string): Promise<boolean>;
9
9
  initSamples(): Promise<GenericCommandResponse>;
10
10
  }
11
- //# sourceMappingURL=CommandsApi.d.ts.map
@@ -28,4 +28,3 @@ export default class EnvironmentsApi extends ApiTopic {
28
28
  listTrainableModels(id: string): Promise<AIModel[]>;
29
29
  embeddings(id: string, payload?: EmbeddingsOptions): Promise<EmbeddingsResult>;
30
30
  }
31
- //# sourceMappingURL=EnvironmentsApi.d.ts.map
@@ -63,4 +63,3 @@ export declare class GroupsApi extends ApiTopic {
63
63
  */
64
64
  removeMember(groupId: string, userId: string): Promise<UserGroup>;
65
65
  }
66
- //# sourceMappingURL=GroupsApi.d.ts.map
@@ -39,4 +39,3 @@ export declare class AcesApi extends ApiTopic {
39
39
  id: string;
40
40
  }>;
41
41
  }
42
- //# sourceMappingURL=IamApi.d.ts.map
@@ -20,4 +20,3 @@ export declare class InteractionBase<P = any, R = any> {
20
20
  */
21
21
  execute(payload?: InteractionExecutionPayload, onChunk?: (chunk: string) => void): Promise<ExecutionRun<P, R>>;
22
22
  }
23
- //# sourceMappingURL=InteractionBase.d.ts.map
@@ -148,4 +148,3 @@ export default class InteractionsApi extends ApiTopic {
148
148
  */
149
149
  listForks(id: string): Promise<InteractionRef[]>;
150
150
  }
151
- //# sourceMappingURL=InteractionsApi.d.ts.map
@@ -15,4 +15,3 @@ declare class IntegrationsConfigurationApi extends ApiTopic {
15
15
  update(projectId: string, integrationId: string, payload: any): Promise<GladiaConfiguration | GithubConfiguration>;
16
16
  }
17
17
  export {};
18
- //# sourceMappingURL=ProjectsApi.d.ts.map
@@ -104,4 +104,3 @@ export interface ListInteractionsResponse {
104
104
  versions: string[];
105
105
  }[];
106
106
  }
107
- //# sourceMappingURL=PromptsApi.d.ts.map
@@ -4,4 +4,3 @@ export declare class RefsApi extends ApiTopic {
4
4
  constructor(parent: ClientBase);
5
5
  resolve(refs: ResolvableRef[]): Promise<ResourceRef[]>;
6
6
  }
7
- //# sourceMappingURL=RefsApi.d.ts.map
@@ -75,4 +75,3 @@ export declare class RunsApi extends ApiTopic {
75
75
  computeFacets(query: ComputeRunFacetPayload): Promise<ComputeRunFacetsResponse>;
76
76
  search(payload: RunSearchPayload): Promise<ExecutionRunRef[]>;
77
77
  }
78
- //# sourceMappingURL=RunsApi.d.ts.map
@@ -5,4 +5,3 @@ export declare class StreamSource {
5
5
  id?: string | undefined;
6
6
  constructor(stream: ReadableStream, name: string, type?: string | undefined, id?: string | undefined);
7
7
  }
8
- //# sourceMappingURL=StreamSource.d.ts.map
@@ -25,4 +25,3 @@ export default class TrainingApi extends ApiTopic {
25
25
  getAndSyncTrainingJob(jobId: string): Promise<TrainingJob>;
26
26
  setDataset(sessionId: string, name?: string): Promise<any>;
27
27
  }
28
- //# sourceMappingURL=TrainingApi.d.ts.map
@@ -4,4 +4,3 @@ export default class UsersApi extends ApiTopic {
4
4
  constructor(parent: ClientBase);
5
5
  retrieve(userId: string): Promise<User>;
6
6
  }
7
- //# sourceMappingURL=UsersApi.d.ts.map
@@ -112,4 +112,3 @@ export declare class VertesiaClient extends AbstractFetchClient<VertesiaClient>
112
112
  }
113
113
  export declare function decodeJWT(jwt: string): AuthTokenPayload;
114
114
  export declare function decodeEndpoints(endpoints: string | Record<string, string> | undefined): Record<string, string>;
115
- //# sourceMappingURL=client.d.ts.map
@@ -34,4 +34,3 @@ export declare function executeInteractionAsync(client: VertesiaClient, payload:
34
34
  runId: string;
35
35
  workflowId: string;
36
36
  }>;
37
- //# sourceMappingURL=execute.d.ts.map
@@ -6,4 +6,3 @@ export type { ComputeRunFacetsResponse, FilterOption } from './RunsApi.js';
6
6
  export type { GroupsQueryOptions } from './GroupsApi.js';
7
7
  export * from "./store/index.js";
8
8
  export * from "./StreamSource.js";
9
- //# sourceMappingURL=index.d.ts.map
@@ -7,4 +7,3 @@ import { StreamSource } from "../StreamSource.js";
7
7
  export declare class NodeStreamSource extends StreamSource {
8
8
  constructor(stream: Readable, name: string, type?: string, id?: string);
9
9
  }
10
- //# sourceMappingURL=NodeStreamSource.d.ts.map
@@ -1,2 +1 @@
1
1
  export * from "./NodeStreamSource.js";
2
- //# sourceMappingURL=index.d.ts.map
@@ -4,4 +4,3 @@ export declare class AgentsApi extends ApiTopic {
4
4
  constructor(parent: ClientBase);
5
5
  deploy(payload: CreateAgentDeploymentRequest): Promise<void>;
6
6
  }
7
- //# sourceMappingURL=AgentsApi.d.ts.map
@@ -15,4 +15,3 @@ export declare class AnalyzeDocApi extends ApiTopic {
15
15
  url: string;
16
16
  }>;
17
17
  }
18
- //# sourceMappingURL=AnalyzeDocApi.d.ts.map
@@ -41,4 +41,3 @@ export declare class CollectionsApi extends ApiTopic {
41
41
  }>;
42
42
  delete(id: string): Promise<any>;
43
43
  }
44
- //# sourceMappingURL=CollectionsApi.d.ts.map
@@ -8,4 +8,3 @@ export declare class CommandsApi extends ApiTopic {
8
8
  constructor(parent: ClientBase);
9
9
  embeddings: EmbeddingsApi;
10
10
  }
11
- //# sourceMappingURL=CommandsApi.d.ts.map
@@ -10,4 +10,3 @@ export declare class EmbeddingsApi extends ApiTopic {
10
10
  disable(type: SupportedEmbeddingTypes): Promise<GenericCommandResponse>;
11
11
  recalculate(type: SupportedEmbeddingTypes): Promise<GenericCommandResponse>;
12
12
  }
13
- //# sourceMappingURL=EmbeddingsApi.d.ts.map
@@ -45,4 +45,3 @@ export declare class FilesApi extends ApiTopic {
45
45
  uploadMemoryPack(source: StreamSource | File): Promise<string>;
46
46
  downloadMemoryPack(name: string, gunzip?: boolean): Promise<ReadableStream<Uint8Array>>;
47
47
  }
48
- //# sourceMappingURL=FilesApi.d.ts.map
@@ -112,4 +112,3 @@ export declare class ObjectsApi extends ApiTopic {
112
112
  exportProperties(payload: ExportPropertiesPayload): Promise<ExportPropertiesResponse>;
113
113
  setEmbedding(id: string, type: SupportedEmbeddingTypes, payload: Embedding): Promise<Record<SupportedEmbeddingTypes, Embedding>>;
114
114
  }
115
- //# sourceMappingURL=ObjectsApi.d.ts.map
@@ -21,4 +21,3 @@ export declare class TypesApi extends ApiTopic {
21
21
  create(payload: CreateContentObjectTypePayload): Promise<ContentObjectType>;
22
22
  delete(id: string): Promise<any>;
23
23
  }
24
- //# sourceMappingURL=TypesApi.d.ts.map
@@ -48,4 +48,3 @@ export declare class WorkflowsDefinitionApi extends ApiTopic {
48
48
  create(payload: DSLWorkflowSpec): Promise<DSLWorkflowDefinition>;
49
49
  delete(id: string): Promise<any>;
50
50
  }
51
- //# sourceMappingURL=WorkflowsApi.d.ts.map
@@ -27,4 +27,3 @@ export declare class ZenoClient extends AbstractFetchClient<ZenoClient> {
27
27
  collections: CollectionsApi;
28
28
  embeddings: EmbeddingsApi;
29
29
  }
30
- //# sourceMappingURL=client.d.ts.map
@@ -2,4 +2,3 @@ import { RequestError } from "@vertesia/api-fetch-client";
2
2
  export declare class ZenoClientNotFoundError extends RequestError {
3
3
  constructor(req: Request, error: RequestError);
4
4
  }
5
- //# sourceMappingURL=errors.d.ts.map
@@ -3,4 +3,3 @@ export * from "./CommandsApi.js";
3
3
  export * from "./ObjectsApi.js";
4
4
  export * from "./TypesApi.js";
5
5
  export * from "./WorkflowsApi.js";
6
- //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,2 @@
1
- import{ExecutionRunStatus as t,AgentMessageType as e}from"@vertesia/common";class s extends Error{constructor(t,e,s,r,n=!0){super(function(t,e,s,r,n){let i=t;if(n){i+="\nRequest: "+e.method+" "+e.url+" => "+s;const t=r?.details||r?.error?.details;if(t){const e=typeof t;"string"===e?i+="\nDetails: "+t:"object"===e&&(i+="\nDetails: "+JSON.stringify(t,void 0,2))}i+="\nStack Trace: "}return i}(t,e,s,r,n)),this.original_message=t,this.request=e,this.status=s,this.payload=r,this.request_info=e.method+" "+e.url+" => "+s,this.displayDetails=n}get details(){return this.payload?.details||this.payload?.error?.details}}class r extends s{constructor(t,e,s,r,n=!0){super(t,e,s,r,n)}updateDetails(t){return t!==this.details?new r(this.original_message,this.request,this.status,{...this.payload,details:t},this.displayDetails):this}}class n extends s{constructor(t,e){super("Failed to connect to server: "+e.message,t,0,e)}}let i;if(globalThis.TextDecoderStream&&"function"==typeof globalThis.TextDecoderStream)i=globalThis.TextDecoderStream;else{class t extends TransformStream{constructor(t="utf-8",{fatal:s=!1,ignoreBOM:r=!1}={}){super(new e(new TextDecoder(t,{fatal:s,ignoreBOM:r}))),this._options={fatal:s,ignoreBOM:r,encoding:t}}get encoding(){return this._options.encoding}get fatal(){return this._options.fatal}get ignoreBOM(){return this._options.ignoreBOM}}class e{constructor(t){this.decoder=t}transform(t,e){if(!(t instanceof ArrayBuffer||ArrayBuffer.isView(t)))throw new TypeError("Input must be a compatible with: ArrayBuffer | Uint8Array");const s=this.decoder.decode(t,{stream:!0});0!==s.length&&e.enqueue(s)}flush(t){const e=this.decoder.decode();0!==e.length&&t.enqueue(e)}}i=t}const a=[239,187,191];class o extends TransformStream{constructor(){let t;super({start(e){t=function(t){let e,s,r,n,i,o,u;return l(),{feed:function(t){s=s?s+t:t,e&&function(t){return a.every(((e,s)=>t.charCodeAt(s)===e))}(s)&&(s=s.slice(a.length)),e=!1;const i=s.length;let o=0,u=!1;for(;o<i;){u&&("\n"===s[o]&&++o,u=!1);let t,e=-1,a=n;for(let n=r;e<0&&n<i;++n)t=s[n],":"===t&&a<0?a=n-o:"\r"===t?(u=!0,e=n-o):"\n"===t&&(e=n-o);if(e<0){r=i-o,n=a;break}r=0,n=-1,c(s,o,a,e),o+=e+1}o===i?s="":o>0&&(s=s.slice(o))},reset:l};function l(){e=!0,s="",r=0,n=-1,i=void 0,o=void 0,u=""}function c(e,s,r,n){if(0===n)return u.length>0&&(t({type:"event",id:i,event:o||void 0,data:u.slice(0,-1)}),u="",i=void 0),void(o=void 0);const a=r<0,l=e.slice(s,s+(a?n:r));let c=0;c=a?n:" "===e[s+r+1]?r+2:r+1;const h=s+c,d=n-c,p=e.slice(h,h+d).toString();if("data"===l)u+=p?"".concat(p,"\n"):"\n";else if("event"===l)o=p;else if("id"!==l||p.includes("\0")){if("retry"===l){const e=parseInt(p,10);Number.isNaN(e)||t({type:"reconnect-interval",value:e})}}else i=p}}((t=>{"event"===t.type&&e.enqueue(t)}))},transform(e){t.feed(e)}})}}function u(t){return"/"===t[t.length-1]?t.slice(0,-1):t}class l{constructor(t,e){this.errorFactory=t=>t,this.verboseErrors=!0,this.baseUrl=u(t),this._fetch=function(t){return t?Promise.resolve(t):"function"==typeof globalThis.fetch?Promise.resolve(globalThis.fetch):Promise.resolve((()=>{throw new Error("No Fetch implementation found")}))}(e)}throwError(t){throw this.errorFactory(t)}getUrl(t){return u((e=this.baseUrl,s=t,e.endsWith("/")?s.startsWith("/")?e+s.substring(1):e+s:s.startsWith("/")?e+s:e+"/"+s));var e,s}get(t,e){return this.request("GET",t,e)}del(t,e){return this.request("DELETE",t,e)}delete(t,e){return this.request("DELETE",t,e)}post(t,e){return this.request("POST",t,e)}put(t,e){return this.request("PUT",t,e)}jsonParse(t){return JSON.parse(t)}createRequest(t,e){return Promise.resolve(new Request(t,e))}createServerError(t,e,s){let n="Server Error: "+e.status;return s&&(s.message?n=String(s.message):s.error&&("string"==typeof s.error?n=String(s.error):"string"==typeof s.error.message&&(n=String(s.error.message)))),new r(n,t,e.status,s,this.verboseErrors)}async readJSONPayload(t){return t.text().then((e=>{if(e)try{return this.jsonParse(e)}catch(s){return{status:t.status,error:"Not a valid JSON payload",message:s.message,text:e}}})).catch((e=>({status:t.status,error:"Unable to load response content",message:e.message})))}handleResponse(t,e,s){return e.url,s&&s.reader?"sse"===s.reader?async function(t){if(!t.ok){const e=await t.text(),s=new Error("SSE error: "+t.status+". Content:\n"+e);throw s.status=t.status,s}if(!t.body)throw new Error("No body in response");return t.body.pipeThrough(new i).pipeThrough(new o)}(e):s.reader.call(this,e):this.readJSONPayload(e).then((s=>{if(e.ok)return s;this.throwError(this.createServerError(t,e,s))}))}async request(t,e,s){let r=this.getUrl(e);s?.query&&(r+="?"+function(t){const e=[];for(const s of Object.keys(t)){const r=t[s];null!=r&&e.push(encodeURIComponent(s)+"="+encodeURIComponent(String(r)))}return e.join("&")}(s.query));const i=this.headers?Object.assign({},this.headers):{},a=s?.headers;if(a)for(const t in a)i[t.toLowerCase()]=a[t];let o;const u=s?.payload;u&&(s&&!1===s.jsonPayload?o=u:(o="string"!=typeof u?JSON.stringify(u):u,"content-type"in i||(i["content-type"]="application/json")));const l={method:t,headers:i,body:o},c=await this.createRequest(r,l);return this._fetch.then((t=>t(c).catch((t=>{console.error(`Failed to connect to ${r}`,t),this.throwError(new n(c,t))})).then((t=>this.handleResponse(c,t,s)))))}fetch(t,e){return this._fetch.then((s=>s(t,e)))}}class c extends l{constructor(t,e){super(t,e),this.baseUrl="/"===t[t.length-1]?t.substring(0,t.length-1):t,this.headers=this.initialHeaders}get initialHeaders(){return{accept:"application/json"}}withAuthCallback(t){return this._auth=t||void 0,this}withErrorFactory(t){return this.errorFactory=t,this}withLang(t){return t?this.headers["accept-language"]=t:delete this.headers["accept-language"],this}withHeaders(t){const e=this.headers;for(const s in t){const r=t[s];null!=r&&(e[s.toLowerCase()]=r)}return this}setHeader(t,e){e?this.headers[t.toLowerCase()]=e:delete this.headers[t.toLowerCase()]}async createRequest(t,e){if(this._auth&&(!(s=e.headers)||!("authorization"in s))){const t=e.headers?e.headers:{};e.headers=t;const s=await this._auth();s&&(e.headers.authorization=s)}var s;this.response=void 0;const r=await super.createRequest(t,e);return this.onRequest&&this.onRequest(r),r}async handleResponse(t,e,s){return this.response=e,this.onResponse&&this.onResponse(e,t),super.handleResponse(t,e,s)}}class h extends l{constructor(t,e){super(t.getUrl(e),t._fetch),this.client=t,this.createServerError=t.createServerError,this.errorFactory=t.errorFactory,this.verboseErrors=t.verboseErrors}createRequest(t,e){return this.client.createRequest(t,e)}handleResponse(t,e,s){return this.client.handleResponse(t,e,s)}get headers(){return this.client.headers}}class d extends h{constructor(t){super(t,"/api/v1/account")}info(){return this.get("/")}update(t){return this.put("/",{payload:t})}projects(){return this.get("/projects").then((t=>t.data))}members(){return this.get("/members")}inviteUser(t){return this.post("/invites",{payload:t})}listInvites(){return this.get("/invites")}listInvitation(t,e="project"){return this.get(`/invites/${e}/${t}`)}acceptInvite(t){return this.put(`/invites/${t}`)}rejectInvite(t){return this.delete(`/invites/${t}`)}onboardingProgress(){return this.get("/onboarding")}getGoogleToken(){return this.get("/google-token")}getStripeBillingStatus(){return this.get("/stripe-billing-status")}}class p extends h{constructor(t){super(t,"/api/v1/accounts")}create(t){return this.post("/",{payload:{name:t}})}list(){return this.get("/")}}class g extends h{constructor(t){super(t,"/api/v1/analytics")}runs(t){return this.post("/runs",{payload:t})}}class y extends h{constructor(t){super(t,"/api/v1/apikeys")}list(){return this.get("/")}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}retrieve(t,e=!1){return e?this.get(`/${t}`,{query:{withValue:!0}}):this.get(`/${t}`)}requestPublicKey(t={}){return this.get("/pk",{query:t})}}class f extends h{constructor(t){super(t,"/api/v1/apps")}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}list(){return this.get("/")}install(t,e){return this.post("/install",{payload:{app_id:t,settings:e}})}uninstall(t){return this.del(`/install/${t}`)}getInstalledApps(t){return this.get("/installations",{query:{kind:t}})}getAllAppInstallations(){return this.get("/installations/all")}listInstallations(){return this.get("/installations/refs")}}let m=class extends h{constructor(t){super(t,"/api/v1/commands")}async isNamespaceAvailable(t){return this.get(`/namespaces/${t}/is_available`).then((t=>t.available))}async initSamples(){return this.post("/onboarding/init-samples")}};class w extends h{constructor(t){super(t,"/api/v1/environments")}list(t=!1){const e=t?{all:!0}:void 0;return this.get("/",{query:e})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get("/"+t)}update(t,e){return this.put("/"+t,{payload:e})}updateConfig(t,e){return this.put("/"+t+"/config",{payload:e})}listModels(t,e){return this.get("/"+t+"/models",{query:e?{...e}:void 0})}listTrainableModels(t){return this.get(`/${t}/trainable-models`)}embeddings(t,e){return this.post("/"+t+"/embeddings",{payload:e})}}class v extends h{constructor(t){super(t,"/groups")}list(t){return this.get("/",{query:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get("/"+t)}update(t,e){return this.put("/"+t,{payload:e})}delete(t){return this.del("/"+t)}listMembers(t){return this.get("/"+t+"/members")}addMember(t,e){return this.post("/"+t+"/members/"+e)}removeMember(t,e){return this.del("/"+t+"/members/"+e)}}class $ extends h{constructor(t){super(t,"/api/v1/iam"),this.aces=new x(this),this.roles=new b(this),this.groups=new v(this)}}class b extends h{constructor(t){super(t,"/roles")}list(){return this.get("/")}}class x extends h{constructor(t){super(t,"/aces")}list(t){return this.get("/",{query:{...t}})}retrieve(t){return this.get("/"+t)}create(t){return this.post("/",{payload:t})}delete(t){return this.del("/"+t)}}async function q(){return"function"==typeof globalThis.EventSource?globalThis.EventSource:(await import("eventsource")).EventSource}async function E(e,s,r={},n){const i=!!n,a=await e.runs.create({...r,interaction:s,stream:i});if(i){if(a.status===t.failed)return a;await T(e,a.id,n)}return a}function T(t,e,s){return new Promise((async(r,n)=>{try{const i=await q(),a=new URL(t.runs.baseUrl+"/"+e+"/stream"),o=t._auth?await t._auth():void 0;if(!o)throw new Error("No auth token available");{const t=o.split(" ")[1];a.searchParams.set("access_token",t)}const u=new i(a.href);u.addEventListener("message",(t=>{try{const e=JSON.parse(t.data);e&&s&&s(e)}catch(t){n(t)}})),u.addEventListener("close",(t=>{try{u.close();const e=JSON.parse(t.data);r(e)}catch(t){n(t)}}))}catch(t){n(t)}}))}class k extends h{constructor(t){super(t,"/api/v1/interactions")}list(t={}){const e=t.query||{};return this.get("/",{query:{...e}})}listEndpoints(t){return this.post("/endpoints",{payload:t})}listVersionsByName(t){return this.get(`/versions/${t}`)}computeFacets(t){return this.post("/facets",{payload:t})}listNames(){return this.get("/names")}export(t){return this.post("/export",{payload:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}execute(t,e={},s){return E(this.client,t,e,s).catch((t=>{throw t instanceof r&&t.payload?.id?t.updateDetails({run_id:t.payload.id}):t}))}executeByName(e,s={},n){return async function(e,s,r={},n){const i=!!n,a=await e.post("/api/v1/execute",{payload:{...r,interaction:s,stream:i}});if(i){if(a.status===t.failed)return a;await T(e,a.id,n)}return a}(this.client,e,s,n).catch((t=>{throw t instanceof r&&t.payload?.id?t.updateDetails({run_id:t.payload.id}):t}))}executeAsync(t){return async function(t,e){return await t.post("/api/v1/execute/async",{payload:e})}(this.client,t)}publish(t,e){return this.post(`/${t}/publish`,{payload:e})}fork(t,e){return this.post(`/${t}/fork`,{payload:e})}generateInteraction(t,e){return this.post(`${t}/generate-interaction`,{payload:e})}generateTestData(t,e){return this.post(`${t}/generate-test-data`,{payload:e})}suggestImprovements(t,e){return this.post(`${t}/suggest-prompt-improvements`,{payload:e})}listVersions(t){return this.get(`/${t}/versions`)}listForks(t){return this.get(`/${t}/forks`)}}class S extends h{constructor(t){super(t,"/api/v1/projects"),this.integrations=new _(this)}list(t){return this.get("/",{query:{account:t}})}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}}class _ extends h{constructor(t){super(t,"/")}list(t){return this.get(`/${t}/integrations`).then((t=>t.integrations))}retrieve(t,e){return this.get(`/${t}/integrations/${e}`).catch((t=>{if(404!==t.status)throw t}))}update(t,e,s){return this.put(`/${t}/integrations/${e}`,{payload:s})}}class R extends h{constructor(t){super(t,"/api/v1/prompts")}list(t={}){const e=t.query||{};return this.get("/",{query:{...e}})}computeFacets(t){return this.post("/facets",{payload:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}fork(t,e){return this.post(`/${t}/fork`,{payload:e})}render(t,e){return this.post(`/${t}/render`,{payload:e})}options(t){return this.get(`/options/${t}`)}listVersions(t){return this.get(`/${t}/versions`)}listInteractions(t){return this.get(`/${t}/interactions`)}listForks(t){return this.get(`/${t}/forks`)}}class U extends h{constructor(t){super(t,"/api/v1/refs")}resolve(t){return this.post("/resolve",{payload:{refs:t}})}}class F extends h{constructor(t){super(t,"/api/v1/runs")}list({limit:t,offset:e,filters:s}){const r={limit:t,offset:e,...s};return this.get("/",{query:r})}find(t){return this.post("/find",{payload:t})}retrieve(t){return this.get("/"+t)}filterOptions(t,e){const s={...e};return this.get(`/filter-options/${t}`,{query:s})}create(t){const e=this.client.sessionTags;if(e){let s=Array.isArray(e)?e:[e];Array.isArray(t.tags)?s=s.concat(t.tags):t.tags&&(s=s.concat([t.tags])),t={...t,tags:s}}return this.post("/",{payload:t})}sendToolResults(t){return this.post("/tool-results",{payload:t})}sendUserMessage(t){return this.post("/user-message",{payload:t})}createCheckpoint(t){return this.post("/checkpoint",{payload:t})}computeFacets(t){return this.post("/facets",{payload:t})}search(t){return this.post("/search",{payload:t})}}class j extends h{constructor(t){super(t,"/api/v1/agents")}async deploy(t){return this.post("/",{payload:t})}}class A extends h{constructor(t,e="/api/v1/embeddings"){super(t,e)}async status(t){return this.get(t+"/status")}async activate(t,e){if(!e.environment)throw new Error("Invalid configuration: select environment");return this.post(t+"/enable",{payload:e})}async disable(t){return this.post(t+"/disable")}async recalculate(t){return this.post(t+"/recalculate")}}class M extends h{constructor(t){super(t,"/api/v1/commands"),this.embeddings=new A(this,"/embeddings")}}class C extends s{constructor(t,e){super("Resource not found: "+e.message,t,404,e.payload)}}class P{constructor(t,e,s,r){this.stream=t,this.name=e,this.type=s,this.id=r}}function D(t){return`memories/${t.endsWith(".tar.gz")?t:t+".tar.gz"}`}class I extends h{constructor(t){super(t,"/api/v1/files")}async deleteFile(t,e){return(await this.delete(`/${t}`,{query:{prefix:e}})).count}getMetadata(t){return this.get("/metadata",{query:{file:t}})}getOrCreateBucket(){return this.post("/bucket")}getUploadUrl(t){return this.post("/upload-url",{payload:t})}getDownloadUrl(t){return this.post("/download-url",{payload:{file:t}})}async uploadFile(t){const e=t instanceof P,{url:s,id:r,path:n}=await this.getUploadUrl(t);return await fetch(s,{method:"PUT",body:e?t.stream:t,duplex:e?"half":void 0,headers:{"Content-Type":t.type||"application/gzip"}}).then((t=>{if(t.ok)return t;throw console.log(t),new Error(`Failed to upload file: ${t.statusText}`)})).catch((t=>{throw console.error("Failed to upload file",{err:t,url:s,id:r,path:n}),t})),r}async downloadFile(t){const e=!t.startsWith("https:"),{url:s}=e?await this.getDownloadUrl(t):{url:t},r=await fetch(s,{method:"GET"}).then((e=>{if(e.ok)return e;throw 404===e.status?new Error(`File ${t} not found`):403===e.status?new Error(`File ${t} is forbidden`):(console.log(e),new Error(`Failed to download file ${t}: ${e.statusText}`))})).catch((e=>{throw console.error(`Failed to download file ${t}.`,e),e}));if(!r.body)throw new Error(`No body in response while downloading file ${t}`);return r.body}async uploadMemoryPack(t){const e=D(t.name),s=t.name.endsWith(".tar.gz")?t.name:t.name+".tar.gz";if(t instanceof File){let r=t;return this.uploadFile(new P(r.stream(),s,r.type,e))}return this.uploadFile(new P(t.stream,s,t.type,e))}async downloadMemoryPack(t,e=!1){let s=await this.downloadFile(D(t));if(e){const t=new DecompressionStream("gzip");s=s.pipeThrough(t)}return s}}class N extends h{constructor(t,e){super(t,`/${e}/analyze`),this.objectId=e}async start(t){return this.post("/",{payload:t})}async getStatus(){return this.get("/status")}async getResults(){return this.get("/results")}async adaptTables(t){return this.post("/adapt_tables",{payload:t})}async getAdaptedTables(t,e){const s=t?`/adapt_tables/${t}`:"/adapt_tables",r={};e?.format&&(r.format=e.format),void 0!==e?.raw&&(r.raw=e.raw);const n={query:r};return"csv"===e?.format&&(n.responseType="text"),this.get(s,n)}async getXml(){return this.get("/xml")}async getTables(t){const e={};return t&&(e.query={format:t}),this.get("/tables",e)}async getImages(){return this.get("/images")}async getAnnotated(){return this.get("/annotated")}}class O extends h{constructor(t){super(t,"/api/v1/objects")}analyze(t){return new N(this,t)}getUploadUrl(t){return this.post("/upload-url",{payload:t})}getDownloadUrl(t){return this.post("/download-url",{payload:{file:t}})}getContentSource(t){return this.get(`/${t}/content-source`)}list(t={}){const e=t.limit||100,s=t.offset||0,r=t.query||{},n=!0===t.all_revisions,i=t.from_root;return this.get("/",{query:{limit:e,offset:s,...r,all_revisions:n?"true":void 0,from_root:i}})}computeFacets(t){return this.post("/facets",{payload:t})}listFolders(t="/"){}find(t){return this.post("/find",{payload:t})}count(t){return this.post("/count",{payload:t})}search(t){return this.post("/search",{payload:t})}retrieve(t,e){return this.get(`/${t}`,{query:{select:e}})}getObjectText(t){return this.get(`/${t}/text`)}async upload(t){const e=t instanceof P,{url:s,id:r,mime_type:n}=await this.getUploadUrl({id:e?t.id:void 0,name:t.name,mime_type:t.type}),i=await fetch(s,{method:"PUT",body:e?t.stream:t,duplex:e?"half":void 0,headers:{"Content-Type":n||"application/octet-stream"}}).then((t=>{if(t.ok)return t;throw console.log(t),new Error(`Failed to upload file: ${t.statusText}`)})).catch((t=>{throw console.error("Failed to upload file",t),t})),a=i.headers.get("etag")?.replace(/^"(.*)"$/,"$1");return{source:r,name:t.name,type:n,etag:a}}async create(t,e){const s={...t};return(t.content instanceof P||t.content instanceof File)&&(s.content=await this.upload(t.content)),await this.post("/",{payload:s,query:e||{}})}async createFromExternalSource(t,e={}){const s=await this.client.files.getMetadata(t),r={...e,content:{source:t,name:s.name,type:s.contentType,etag:s.etag}};return await this.post("/",{payload:r})}async update(t,e,s){const r={...e};return(e.content instanceof P||e.content instanceof File)&&(r.content=await this.upload(e.content)),s?.createRevision?this.put(`/${t}`,{payload:r,headers:{"x-create-revision":"true","x-revision-label":s.revisionLabel||""}}):this.put(`/${t}`,{payload:r})}getRevisions(t){return this.get(`/${t}/revisions`)}getCollections(t){return this.get(`/${t}/collections`)}delete(t){return this.del(`/${t}`)}listWorkflowRuns(t){return this.get(`/${t}/workflow-runs`)}listRenditions(t){return this.get(`/${t}/renditions`)}getRendition(t,e){const s={max_hw:e.max_hw,generate_if_missing:e.generate_if_missing,sign_url:e.sign_url};return this.get(`/${t}/renditions/${e.format}`,{query:s})}exportProperties(t){return this.post("/export",{payload:t})}setEmbedding(t,e,s){return this.put(`/${t}/embeddings/${e}`,{payload:s})}}class B extends h{constructor(t){super(t,"/api/v1/types")}list(t={},e){const s=t.limit||100,r=t.offset||0,n=t.query||{};return this.get("/",{query:{limit:s,offset:r,layout:!!e?.layout,schema:!!e?.schema,...n}})}find(t){return this.post("/find",{payload:t})}retrieve(t){return this.get(`/${t}`)}getTypeByName(t){return this.get(`/name/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}}class J extends h{constructor(t){super(t,"/api/v1/workflows"),this.rules=new L(this),this.definitions=new W(this)}getActivityCatalog(){return this.get("/activity-catalog")}listRuns(t,e,s){return this.post("/runs",{payload:{documentId:t,eventName:e,ruleId:s}})}listConversations(){return this.get("/conversations")}searchRuns(t){return this.post("/runs",{payload:t})}sendSignal(t,e,s,r){return this.post(`/runs/${t}/${e}/signal/${s}`,{payload:r})}getRunDetails(t,e,s=!1){const r={include_history:s};return this.get(`/runs/${e}/${t}`,{query:r})}getRunInteraction(t,e){return this.get(`/runs/${t}/${e}/interaction`)}terminate(t,e,s){return this.post(`/runs/${t}/${e}/actions/terminate`,{payload:{reason:s}})}cancel(t,e,s){return this.post(`/runs/${t}/${e}/actions/cancel`,{payload:{reason:s}})}execute(t,e={}){return this.post(`/execute/${t}`,{payload:e})}postMessage(t,e){if(!t)throw new Error("runId is required");return this.post(`/runs/${t}/updates`,{payload:e})}retrieveMessages(t,e,s){const r={since:s};return this.get(`/runs/${t}/${e}/updates`,{query:r})}async streamMessages(t,s,r,n){return new Promise(((i,a)=>{let o=0,u=n||0,l=!1,c=null,h=null;const d=10,p=t=>{const e=Math.min(1e3*Math.pow(2,t),3e4);return e+.1*Math.random()*e},g=()=>{h&&(clearInterval(h),h=null),c&&(c.close(),c=null)},y=t=>{l||(l=!0,g(),i(t))},f=async(n=!1)=>{if(!l)try{const m=await q(),w=this.client,v=new URL(w.workflows.baseUrl+`/runs/${t}/${s}/stream`);u>0&&v.searchParams.set("since",u.toString());const $=w._auth?await w._auth():void 0;if(!$)return void a(new Error("No auth token available"));const b=$.split(" ")[1];v.searchParams.set("access_token",b),n&&console.log(`Reconnecting to SSE stream for run ${s} (attempt ${o+1}/10)`);const x=new m(v.href);c=x,h=setInterval((()=>{}),1e3),x.onopen=()=>{n&&console.log(`Successfully reconnected to SSE stream for run ${s}`),o=0},x.onmessage=t=>{if(t.data&&!t.data.startsWith(":"))try{const s=JSON.parse(t.data);s.timestamp&&(u=Math.max(u,s.timestamp)),r&&r(s,y);s.type===e.TERMINATED||s.type===e.COMPLETE&&(!s.workstream_id||"main"===s.workstream_id)?(console.log("Closing stream due to COMPLETE message from main workstream"),l||(l=!0,g(),i(null))):s.type===e.COMPLETE&&console.log(`Received COMPLETE message from non-main workstream: ${s.workstream_id||"unknown"}, keeping stream open`)}catch(e){console.error("Failed to parse SSE message:",e,t.data)}else console.log("Received comment or heartbeat; ignoring it.: ",t.data)},x.onerror=t=>{if(!l)if(console.warn(`SSE stream error for run ${s}:`,t),g(),o<d){const t=p(o);console.log(`Attempting to reconnect in ${t}ms (attempt ${o+1}/10)`),o++,setTimeout((()=>{l||f(!0)}),t)}else console.error(`Failed to reconnect to SSE stream for run ${s} after 10 attempts`),l=!0,a(new Error("SSE connection failed after 10 reconnection attempts"))}}catch(t){if(console.error("Error setting up SSE stream:",t),o<d){const t=p(o);o++,setTimeout((()=>{l||f(!0)}),t)}else a(t)}};return f(!1),()=>{l=!0,g()}}))}}class L extends h{constructor(t){super(t,"/rules")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}execute(t,e,s){const r={objectIds:e,vars:s};return this.post(`/${t}/execute`,{payload:r})}}class W extends h{constructor(t){super(t,"/definitions")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}}class z extends h{constructor(t){super(t,"/api/v1/collections")}search(t){return this.post("/search",{payload:t})}computeListFacets(t){return this.post("/facets",{payload:t})}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}addMembers(t,e){return this.post(`/${t}/members`,{payload:{action:"add",members:e}})}listMembers(t,e){return this.get(`/${t}/members`,{query:{...e}})}computeFacets(t,e){return this.post(`/${t}/facets`,{payload:e})}searchMembers(t,e){return this.post(`/${t}/search`,{payload:e})}deleteMembers(t,e){return this.post(`/${t}/members`,{payload:{action:"delete",members:e}})}delete(t){return this.del(`/${t}`)}}class V extends c{constructor(t={}){super(function(t){if(!t)throw new Error("zeno client serverUrl is required");return t}(t.serverUrl)),this.objects=new O(this),this.types=new B(this),this.workflows=new J(this),this.files=new I(this),this.commands=new M(this),this.agents=new j(this),this.collections=new z(this),this.embeddings=new A(this),t.apikey&&this.withApiKey(t.apikey),this.onRequest=t.onRequest,this.onResponse=t.onResponse,this.errorFactory=t=>404===t.status?new C(t.request,t):t}withApiKey(t){return this.withAuthCallback(t?()=>Promise.resolve(`Bearer ${t}`):void 0)}runOperation(t){return this.post("/api/v1/operations",{payload:t})}}class K extends h{constructor(t){super(t,"/api/v1/training")}listSessions(t={}){return this.get("/",{query:t})}listSessionNames(t={}){return this.get("/names",{query:t})}createSession(t){return this.post("/",{payload:t})}getSession(t){return this.get("/"+t)}addToSession(t,e){return this.post("/"+t+"/add",{payload:{runs:e}})}listSessionRuns(t,e=100,s=0){return this.get("/"+t+"/runs",{query:{limit:e,offset:s}})}buildSession(t){return this.post("/"+t+"/build")}getDataUrl(t){return this.get("/"+t+"/url")}getDataUploadUrl(t,e=!1){return this.get("/"+t+"/upload-url",e?{query:{resumable:"true"}}:{})}startTraining(t){return this.post("/"+t+"/start")}cancelTraining(t){return this.post("/"+t+"/cancel")}getTrainingJob(t){return this.get(`/job/${t}`)}getAndSyncTrainingJob(t){return this.get(`/job/${t}`,{query:{sync:"true"}})}setDataset(t,e="default"){return this.post("/"+t+"/dataset",{payload:{dataset:e}})}}class H extends h{constructor(t){super(t,"/api/v1/users")}retrieve(t){return this.get("/"+t)}}class G extends c{static async fromAuthToken(t,e){e||(e=X(t));const s=Q(e.endpoints);return await new G({serverUrl:s.studio,storeUrl:s.store}).withApiKey(t)}static decodeEndpoints(){}constructor(t={site:"api.vertesia.io"}){let e,s;if(t.serverUrl)e=t.serverUrl;else{if(!t.site)throw new Error("Parameter 'site' or 'serverUrl' is required for VertesiaClient");e=`https://${t.site}`}if(t.storeUrl)s=t.storeUrl;else{if(!t.site)throw new Error("Parameter 'site' or 'storeUrl' is required for VertesiaClient");s=`https://${t.site}`}super(e),this._jwt=null,this.projects=new S(this),this.environments=new w(this),this.interactions=new k(this),this.prompts=new R(this),this.runs=new F(this),this.account=new d(this),this.accounts=new p(this),this.apikeys=new y(this),this.analytics=new g(this),this.training=new K(this),this.users=new H(this),this.iam=new $(this),this.refs=new U(this),this.commands=new m(this),this.apps=new f(this),this.store=new V({serverUrl:s,apikey:t.apikey,onRequest:t.onRequest,onResponse:t.onResponse}),t.apikey&&this.withApiKey(t.apikey),t.projectId&&(this.headers["x-project-id"]=t.projectId),this.onRequest=t.onRequest,this.onResponse=t.onResponse,this.sessionTags=t.sessionTags}withAuthCallback(t){return this.store.withAuthCallback(t),super.withAuthCallback(t)}async withApiKey(t){return this.withAuthCallback(t?async()=>{if(!function(t){return t.startsWith("pk-")||t.startsWith("sk-")}(t))return`Bearer ${t}`;if(function(t){if(!t)return!0;const e=X(t).exp;return Date.now()<=1e3*e-6e4}(this._jwt)){const e=await this.getAuthToken(t);this._jwt=e.token}return`Bearer ${this._jwt}`}:void 0)}async getRawJWT(){if(!this._jwt&&this._auth){const t=await this._auth();this._jwt||(this._jwt=t.trim().split(" ")[1])}return this._jwt||null}async getDecodedJWT(){const t=await this.getRawJWT();return t?X(t):null}async getProject(){const t=await this.getDecodedJWT();return t?.project||null}async getAccount(){const t=await this.getDecodedJWT();return t?.account||null}get workflows(){return this.store.workflows}get objects(){return this.store.objects}get files(){return this.store.files}get types(){return this.store.types}get storeUrl(){return this.store.baseUrl}async getAuthToken(t,e){const s={accountId:e,token:t};return this.get("/auth/token",{query:s,headers:{authorization:void 0}})}}function X(t){const e=function(t){const e=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(4*Math.ceil(t.length/4),"=");if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");if("undefined"!=typeof atob&&"undefined"!=typeof TextDecoder){const t=atob(e),s=Uint8Array.from(t,(t=>t.charCodeAt(0)));return(new TextDecoder).decode(s)}throw new Error("No base64 decoder available")}(t.split(".")[1]);return JSON.parse(e)}function Q(t){return t?"string"==typeof t?Y(t):t:Y("api.vertesia.io")}function Y(t){if("local"===t)return{studio:"http://localhost:8091",store:"http://localhost:8092"};{const e=`https://${t}`;return{studio:e,store:e}}}class Z{constructor(t,e){this.id=t,this.client=e instanceof G?e:new G(e)}retrieve(){return this.client.interactions.retrieve(this.id)}update(t){return this.client.interactions.update(this.id,t)}render(t){}async execute(t={},e){return E(this.client,this.id,t,e)}}export{M as CommandsApi,Z as InteractionBase,O as ObjectsApi,P as StreamSource,B as TypesApi,G as VertesiaClient,J as WorkflowsApi,W as WorkflowsDefinitionApi,L as WorkflowsRulesApi,V as ZenoClient,Q as decodeEndpoints,X as decodeJWT};
1
+ import{ExecutionRunStatus as t,AgentMessageType as e}from"@vertesia/common";class s extends Error{constructor(t,e,s,r,n=!0){super(function(t,e,s,r,n){let i=t;if(n){i+="\nRequest: "+e.method+" "+e.url+" => "+s;const t=r?.details||r?.error?.details;if(t){const e=typeof t;"string"===e?i+="\nDetails: "+t:"object"===e&&(i+="\nDetails: "+JSON.stringify(t,void 0,2))}i+="\nStack Trace: "}return i}(t,e,s,r,n)),this.original_message=t,this.request=e,this.status=s,this.payload=r,this.request_info=e.method+" "+e.url+" => "+s,this.displayDetails=n}get details(){return this.payload?.details||this.payload?.error?.details}}class r extends s{constructor(t,e,s,r,n=!0){super(t,e,s,r,n)}updateDetails(t){return t!==this.details?new r(this.original_message,this.request,this.status,{...this.payload,details:t},this.displayDetails):this}}class n extends s{constructor(t,e){super("Failed to connect to server: "+e.message,t,0,e)}}let i;if(globalThis.TextDecoderStream&&"function"==typeof globalThis.TextDecoderStream)i=globalThis.TextDecoderStream;else{class t extends TransformStream{constructor(t="utf-8",{fatal:s=!1,ignoreBOM:r=!1}={}){super(new e(new TextDecoder(t,{fatal:s,ignoreBOM:r}))),this._options={fatal:s,ignoreBOM:r,encoding:t}}get encoding(){return this._options.encoding}get fatal(){return this._options.fatal}get ignoreBOM(){return this._options.ignoreBOM}}class e{constructor(t){this.decoder=t}transform(t,e){if(!(t instanceof ArrayBuffer||ArrayBuffer.isView(t)))throw new TypeError("Input must be a compatible with: ArrayBuffer | Uint8Array");const s=this.decoder.decode(t,{stream:!0});0!==s.length&&e.enqueue(s)}flush(t){const e=this.decoder.decode();0!==e.length&&t.enqueue(e)}}i=t}const a=[239,187,191];class o extends TransformStream{constructor(){let t;super({start(e){t=function(t){let e,s,r,n,i,o,u;return l(),{feed:function(t){s=s?s+t:t,e&&function(t){return a.every(((e,s)=>t.charCodeAt(s)===e))}(s)&&(s=s.slice(a.length)),e=!1;const i=s.length;let o=0,u=!1;for(;o<i;){u&&("\n"===s[o]&&++o,u=!1);let t,e=-1,a=n;for(let n=r;e<0&&n<i;++n)t=s[n],":"===t&&a<0?a=n-o:"\r"===t?(u=!0,e=n-o):"\n"===t&&(e=n-o);if(e<0){r=i-o,n=a;break}r=0,n=-1,c(s,o,a,e),o+=e+1}o===i?s="":o>0&&(s=s.slice(o))},reset:l};function l(){e=!0,s="",r=0,n=-1,i=void 0,o=void 0,u=""}function c(e,s,r,n){if(0===n)return u.length>0&&(t({type:"event",id:i,event:o||void 0,data:u.slice(0,-1)}),u="",i=void 0),void(o=void 0);const a=r<0,l=e.slice(s,s+(a?n:r));let c=0;c=a?n:" "===e[s+r+1]?r+2:r+1;const h=s+c,d=n-c,p=e.slice(h,h+d).toString();if("data"===l)u+=p?"".concat(p,"\n"):"\n";else if("event"===l)o=p;else if("id"!==l||p.includes("\0")){if("retry"===l){const e=parseInt(p,10);Number.isNaN(e)||t({type:"reconnect-interval",value:e})}}else i=p}}((t=>{"event"===t.type&&e.enqueue(t)}))},transform(e){t.feed(e)}})}}function u(t){return"/"===t[t.length-1]?t.slice(0,-1):t}class l{constructor(t,e){this.errorFactory=t=>t,this.verboseErrors=!0,this.baseUrl=u(t),this._fetch=function(t){return t?Promise.resolve(t):"function"==typeof globalThis.fetch?Promise.resolve(globalThis.fetch):Promise.resolve((()=>{throw new Error("No Fetch implementation found")}))}(e)}throwError(t){throw this.errorFactory(t)}getUrl(t){return u((e=this.baseUrl,s=t,e.endsWith("/")?s.startsWith("/")?e+s.substring(1):e+s:s.startsWith("/")?e+s:e+"/"+s));var e,s}get(t,e){return this.request("GET",t,e)}del(t,e){return this.request("DELETE",t,e)}delete(t,e){return this.request("DELETE",t,e)}post(t,e){return this.request("POST",t,e)}put(t,e){return this.request("PUT",t,e)}jsonParse(t){return JSON.parse(t)}createRequest(t,e){return Promise.resolve(new Request(t,e))}createServerError(t,e,s){let n="Server Error: "+e.status;return s&&(s.message?n=String(s.message):s.error&&("string"==typeof s.error?n=String(s.error):"string"==typeof s.error.message&&(n=String(s.error.message)))),new r(n,t,e.status,s,this.verboseErrors)}async readJSONPayload(t){return t.text().then((e=>{if(e)try{return this.jsonParse(e)}catch(s){return{status:t.status,error:"Not a valid JSON payload",message:s.message,text:e}}})).catch((e=>({status:t.status,error:"Unable to load response content",message:e.message})))}handleResponse(t,e,s){return e.url,s&&s.reader?"sse"===s.reader?async function(t){if(!t.ok){const e=await t.text(),s=new Error("SSE error: "+t.status+". Content:\n"+e);throw s.status=t.status,s}if(!t.body)throw new Error("No body in response");return t.body.pipeThrough(new i).pipeThrough(new o)}(e):s.reader.call(this,e):this.readJSONPayload(e).then((s=>{if(e.ok)return s;this.throwError(this.createServerError(t,e,s))}))}async request(t,e,s){let r=this.getUrl(e);s?.query&&(r+="?"+function(t){const e=[];for(const s of Object.keys(t)){const r=t[s];null!=r&&e.push(encodeURIComponent(s)+"="+encodeURIComponent(String(r)))}return e.join("&")}(s.query));const i=this.headers?Object.assign({},this.headers):{},a=s?.headers;if(a)for(const t in a)i[t.toLowerCase()]=a[t];let o;const u=s?.payload;u&&(s&&!1===s.jsonPayload?o=u:(o="string"!=typeof u?JSON.stringify(u):u,"content-type"in i||(i["content-type"]="application/json")));const l={method:t,headers:i,body:o},c=await this.createRequest(r,l);return this._fetch.then((t=>t(c).catch((t=>{console.error(`Failed to connect to ${r}`,t),this.throwError(new n(c,t))})).then((t=>this.handleResponse(c,t,s)))))}fetch(t,e){return this._fetch.then((s=>s(t,e)))}}class c extends l{constructor(t,e){super(t,e),this.baseUrl="/"===t[t.length-1]?t.substring(0,t.length-1):t,this.headers=this.initialHeaders}get initialHeaders(){return{accept:"application/json"}}withAuthCallback(t){return this._auth=t||void 0,this}withErrorFactory(t){return this.errorFactory=t,this}withLang(t){return t?this.headers["accept-language"]=t:delete this.headers["accept-language"],this}withHeaders(t){const e=this.headers;for(const s in t){const r=t[s];null!=r&&(e[s.toLowerCase()]=r)}return this}setHeader(t,e){e?this.headers[t.toLowerCase()]=e:delete this.headers[t.toLowerCase()]}async createRequest(t,e){if(this._auth&&(!(s=e.headers)||!("authorization"in s))){const t=e.headers?e.headers:{};e.headers=t;const s=await this._auth();s&&(e.headers.authorization=s)}var s;this.response=void 0;const r=await super.createRequest(t,e);return this.onRequest&&this.onRequest(r),r}async handleResponse(t,e,s){return this.response=e,this.onResponse&&this.onResponse(e,t),super.handleResponse(t,e,s)}}class h extends l{constructor(t,e){super(t.getUrl(e),t._fetch),this.client=t,this.createServerError=t.createServerError,this.errorFactory=t.errorFactory,this.verboseErrors=t.verboseErrors}createRequest(t,e){return this.client.createRequest(t,e)}handleResponse(t,e,s){return this.client.handleResponse(t,e,s)}get headers(){return this.client.headers}}class d extends h{constructor(t){super(t,"/api/v1/account")}info(){return this.get("/")}update(t){return this.put("/",{payload:t})}projects(){return this.get("/projects").then((t=>t.data))}members(){return this.get("/members")}inviteUser(t){return this.post("/invites",{payload:t})}listInvites(){return this.get("/invites")}listInvitation(t="project"){return this.get(`/invites/${t}`)}acceptInvite(t){return this.put(`/invites/${t}`)}rejectInvite(t){return this.delete(`/invites/${t}`)}onboardingProgress(){return this.get("/onboarding")}getGoogleToken(){return this.get("/google-token")}getStripeBillingStatus(){return this.get("/stripe-billing-status")}}class p extends h{constructor(t){super(t,"/api/v1/accounts")}create(t){return this.post("/",{payload:{name:t}})}list(){return this.get("/")}}class g extends h{constructor(t){super(t,"/api/v1/analytics")}runs(t){return this.post("/runs",{payload:t})}}class y extends h{constructor(t){super(t,"/api/v1/apikeys")}list(){return this.get("/")}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}retrieve(t,e=!1){return e?this.get(`/${t}`,{query:{withValue:!0}}):this.get(`/${t}`)}requestPublicKey(t={}){return this.get("/pk",{query:t})}}class f extends h{constructor(t){super(t,"/api/v1/apps")}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}list(){return this.get("/")}install(t,e){return this.post("/install",{payload:{app_id:t,settings:e}})}uninstall(t){return this.del(`/install/${t}`)}getAppInstallationByName(t){return this.get(`/installations/name/${t}`).catch((t=>{if(404===t.status)return null;throw t}))}getAppInstallationProjects(t){if(!t.id&&!t.name)throw new Error("Invalid arguments: appId or appName must be specified");const e=t.id?{id:t.id}:{name:t.name};return this.get("/installations/projects",{query:e})}getInstalledApps(t){return this.get("/installations",{query:{kind:t}})}getAllAppInstallations(){return this.get("/installations/all")}listInstallations(){return this.get("/installations/refs")}}let m=class extends h{constructor(t){super(t,"/api/v1/commands")}async isNamespaceAvailable(t){return this.get(`/namespaces/${t}/is_available`).then((t=>t.available))}async initSamples(){return this.post("/onboarding/init-samples")}};class w extends h{constructor(t){super(t,"/api/v1/environments")}list(t=!1){const e=t?{all:!0}:void 0;return this.get("/",{query:e})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get("/"+t)}update(t,e){return this.put("/"+t,{payload:e})}updateConfig(t,e){return this.put("/"+t+"/config",{payload:e})}listModels(t,e){return this.get("/"+t+"/models",{query:e?{...e}:void 0})}listTrainableModels(t){return this.get(`/${t}/trainable-models`)}embeddings(t,e){return this.post("/"+t+"/embeddings",{payload:e})}}class v extends h{constructor(t){super(t,"/groups")}list(t){return this.get("/",{query:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get("/"+t)}update(t,e){return this.put("/"+t,{payload:e})}delete(t){return this.del("/"+t)}listMembers(t){return this.get("/"+t+"/members")}addMember(t,e){return this.post("/"+t+"/members/"+e)}removeMember(t,e){return this.del("/"+t+"/members/"+e)}}class $ extends h{constructor(t){super(t,"/api/v1/iam"),this.aces=new x(this),this.roles=new b(this),this.groups=new v(this)}}class b extends h{constructor(t){super(t,"/roles")}list(){return this.get("/")}}class x extends h{constructor(t){super(t,"/aces")}list(t){return this.get("/",{query:{...t}})}retrieve(t){return this.get("/"+t)}create(t){return this.post("/",{payload:t})}delete(t){return this.del("/"+t)}}async function q(){return"function"==typeof globalThis.EventSource?globalThis.EventSource:(await import("eventsource")).EventSource}async function E(e,s,r={},n){const i=!!n,a=await e.runs.create({...r,interaction:s,stream:i});if(i){if(a.status===t.failed)return a;await T(e,a.id,n)}return a}function T(t,e,s){return new Promise((async(r,n)=>{try{const i=await q(),a=new URL(t.runs.baseUrl+"/"+e+"/stream"),o=t._auth?await t._auth():void 0;if(!o)throw new Error("No auth token available");{const t=o.split(" ")[1];a.searchParams.set("access_token",t)}const u=new i(a.href);u.addEventListener("message",(t=>{try{const e=JSON.parse(t.data);e&&s&&s(e)}catch(t){n(t)}})),u.addEventListener("close",(t=>{try{u.close();const e=JSON.parse(t.data);r(e)}catch(t){n(t)}}))}catch(t){n(t)}}))}class k extends h{constructor(t){super(t,"/api/v1/interactions")}list(t={}){const e=t.query||{};return this.get("/",{query:{...e}})}listEndpoints(t){return this.post("/endpoints",{payload:t})}listVersionsByName(t){return this.get(`/versions/${t}`)}computeFacets(t){return this.post("/facets",{payload:t})}listNames(){return this.get("/names")}export(t){return this.post("/export",{payload:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}execute(t,e={},s){return E(this.client,t,e,s).catch((t=>{throw t instanceof r&&t.payload?.id?t.updateDetails({run_id:t.payload.id}):t}))}executeByName(e,s={},n){return async function(e,s,r={},n){const i=!!n,a=await e.post("/api/v1/execute",{payload:{...r,interaction:s,stream:i}});if(i){if(a.status===t.failed)return a;await T(e,a.id,n)}return a}(this.client,e,s,n).catch((t=>{throw t instanceof r&&t.payload?.id?t.updateDetails({run_id:t.payload.id}):t}))}executeAsync(t){return async function(t,e){return await t.post("/api/v1/execute/async",{payload:e})}(this.client,t)}publish(t,e){return this.post(`/${t}/publish`,{payload:e})}fork(t,e){return this.post(`/${t}/fork`,{payload:e})}generateInteraction(t,e){return this.post(`${t}/generate-interaction`,{payload:e})}generateTestData(t,e){return this.post(`${t}/generate-test-data`,{payload:e})}suggestImprovements(t,e){return this.post(`${t}/suggest-prompt-improvements`,{payload:e})}listVersions(t){return this.get(`/${t}/versions`)}listForks(t){return this.get(`/${t}/forks`)}}class S extends h{constructor(t){super(t,"/api/v1/projects"),this.integrations=new _(this)}list(t){return this.get("/",{query:{account:t}})}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}}class _ extends h{constructor(t){super(t,"/")}list(t){return this.get(`/${t}/integrations`).then((t=>t.integrations))}retrieve(t,e){return this.get(`/${t}/integrations/${e}`).catch((t=>{if(404!==t.status)throw t}))}update(t,e,s){return this.put(`/${t}/integrations/${e}`,{payload:s})}}class R extends h{constructor(t){super(t,"/api/v1/prompts")}list(t={}){const e=t.query||{};return this.get("/",{query:{...e}})}computeFacets(t){return this.post("/facets",{payload:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}fork(t,e){return this.post(`/${t}/fork`,{payload:e})}render(t,e){return this.post(`/${t}/render`,{payload:e})}options(t){return this.get(`/options/${t}`)}listVersions(t){return this.get(`/${t}/versions`)}listInteractions(t){return this.get(`/${t}/interactions`)}listForks(t){return this.get(`/${t}/forks`)}}class U extends h{constructor(t){super(t,"/api/v1/refs")}resolve(t){return this.post("/resolve",{payload:{refs:t}})}}class j extends h{constructor(t){super(t,"/api/v1/runs")}list({limit:t,offset:e,filters:s}){const r={limit:t,offset:e,...s};return this.get("/",{query:r})}find(t){return this.post("/find",{payload:t})}retrieve(t){return this.get("/"+t)}filterOptions(t,e){const s={...e};return this.get(`/filter-options/${t}`,{query:s})}create(t){const e=this.client.sessionTags;if(e){let s=Array.isArray(e)?e:[e];Array.isArray(t.tags)?s=s.concat(t.tags):t.tags&&(s=s.concat([t.tags])),t={...t,tags:s}}return this.post("/",{payload:t})}sendToolResults(t){return this.post("/tool-results",{payload:t})}sendUserMessage(t){return this.post("/user-message",{payload:t})}createCheckpoint(t){return this.post("/checkpoint",{payload:t})}computeFacets(t){return this.post("/facets",{payload:t})}search(t){return this.post("/search",{payload:t})}}class A extends h{constructor(t){super(t,"/api/v1/agents")}async deploy(t){return this.post("/",{payload:t})}}class F extends h{constructor(t,e="/api/v1/embeddings"){super(t,e)}async status(t){return this.get(t+"/status")}async activate(t,e){if(!e.environment)throw new Error("Invalid configuration: select environment");return this.post(t+"/enable",{payload:e})}async disable(t){return this.post(t+"/disable")}async recalculate(t){return this.post(t+"/recalculate")}}class I extends h{constructor(t){super(t,"/api/v1/commands"),this.embeddings=new F(this,"/embeddings")}}class M extends s{constructor(t,e){super("Resource not found: "+e.message,t,404,e.payload)}}class P{constructor(t,e,s,r){this.stream=t,this.name=e,this.type=s,this.id=r}}function C(t){return`memories/${t.endsWith(".tar.gz")?t:t+".tar.gz"}`}class N extends h{constructor(t){super(t,"/api/v1/files")}async deleteFile(t,e){return(await this.delete(`/${t}`,{query:{prefix:e}})).count}getMetadata(t){return this.get("/metadata",{query:{file:t}})}getOrCreateBucket(){return this.post("/bucket")}getUploadUrl(t){return this.post("/upload-url",{payload:t})}getDownloadUrl(t){return this.post("/download-url",{payload:{file:t}})}async uploadFile(t){const e=t instanceof P,{url:s,id:r,path:n}=await this.getUploadUrl(t);return await fetch(s,{method:"PUT",body:e?t.stream:t,duplex:e?"half":void 0,headers:{"Content-Type":t.type||"application/gzip"}}).then((t=>{if(t.ok)return t;throw console.log(t),new Error(`Failed to upload file: ${t.statusText}`)})).catch((t=>{throw console.error("Failed to upload file",{err:t,url:s,id:r,path:n}),t})),r}async downloadFile(t){const e=!t.startsWith("https:"),{url:s}=e?await this.getDownloadUrl(t):{url:t},r=await fetch(s,{method:"GET"}).then((e=>{if(e.ok)return e;throw 404===e.status?new Error(`File ${t} not found`):403===e.status?new Error(`File ${t} is forbidden`):(console.log(e),new Error(`Failed to download file ${t}: ${e.statusText}`))})).catch((e=>{throw console.error(`Failed to download file ${t}.`,e),e}));if(!r.body)throw new Error(`No body in response while downloading file ${t}`);return r.body}async uploadMemoryPack(t){const e=C(t.name),s=t.name.endsWith(".tar.gz")?t.name:t.name+".tar.gz";if(t instanceof File){let r=t;return this.uploadFile(new P(r.stream(),s,r.type,e))}return this.uploadFile(new P(t.stream,s,t.type,e))}async downloadMemoryPack(t,e=!1){let s=await this.downloadFile(C(t));if(e){const t=new DecompressionStream("gzip");s=s.pipeThrough(t)}return s}}class D extends h{constructor(t,e){super(t,`/${e}/analyze`),this.objectId=e}async start(t){return this.post("/",{payload:t})}async getStatus(){return this.get("/status")}async getResults(){return this.get("/results")}async adaptTables(t){return this.post("/adapt_tables",{payload:t})}async getAdaptedTables(t,e){const s=t?`/adapt_tables/${t}`:"/adapt_tables",r={};e?.format&&(r.format=e.format),void 0!==e?.raw&&(r.raw=e.raw);const n={query:r};return"csv"===e?.format&&(n.responseType="text"),this.get(s,n)}async getXml(){return this.get("/xml")}async getTables(t){const e={};return t&&(e.query={format:t}),this.get("/tables",e)}async getImages(){return this.get("/images")}async getAnnotated(){return this.get("/annotated")}}class O extends h{constructor(t){super(t,"/api/v1/objects")}analyze(t){return new D(this,t)}getUploadUrl(t){return this.post("/upload-url",{payload:t})}getDownloadUrl(t){return this.post("/download-url",{payload:{file:t}})}getContentSource(t){return this.get(`/${t}/content-source`)}list(t={}){const e=t.limit||100,s=t.offset||0,r=t.query||{},n=!0===t.all_revisions,i=t.from_root;return this.get("/",{query:{limit:e,offset:s,...r,all_revisions:n?"true":void 0,from_root:i}})}computeFacets(t){return this.post("/facets",{payload:t})}listFolders(t="/"){}find(t){return this.post("/find",{payload:t})}count(t){return this.post("/count",{payload:t})}search(t){return this.post("/search",{payload:t})}retrieve(t,e){return this.get(`/${t}`,{query:{select:e}})}getObjectText(t){return this.get(`/${t}/text`)}async upload(t){const e=t instanceof P,{url:s,id:r,mime_type:n}=await this.getUploadUrl({id:e?t.id:void 0,name:t.name,mime_type:t.type}),i=await fetch(s,{method:"PUT",body:e?t.stream:t,duplex:e?"half":void 0,headers:{"Content-Type":n||"application/octet-stream"}}).then((t=>{if(t.ok)return t;throw console.log(t),new Error(`Failed to upload file: ${t.statusText}`)})).catch((t=>{throw console.error("Failed to upload file",t),t})),a=i.headers.get("etag")?.replace(/^"(.*)"$/,"$1");return{source:r,name:t.name,type:n,etag:a}}async create(t,e){const s={...t};return(t.content instanceof P||t.content instanceof File)&&(s.content=await this.upload(t.content)),await this.post("/",{payload:s,query:e||{}})}async createFromExternalSource(t,e={}){const s=await this.client.files.getMetadata(t),r={...e,content:{source:t,name:s.name,type:s.contentType,etag:s.etag}};return await this.post("/",{payload:r})}async update(t,e,s){const r={...e};return(e.content instanceof P||e.content instanceof File)&&(r.content=await this.upload(e.content)),s?.createRevision?this.put(`/${t}`,{payload:r,headers:{"x-create-revision":"true","x-revision-label":s.revisionLabel||""}}):this.put(`/${t}`,{payload:r})}getRevisions(t){return this.get(`/${t}/revisions`)}getCollections(t){return this.get(`/${t}/collections`)}delete(t){return this.del(`/${t}`)}listWorkflowRuns(t){return this.get(`/${t}/workflow-runs`)}listRenditions(t){return this.get(`/${t}/renditions`)}getRendition(t,e){const s={max_hw:e.max_hw,generate_if_missing:e.generate_if_missing,sign_url:e.sign_url};return this.get(`/${t}/renditions/${e.format}`,{query:s})}exportProperties(t){return this.post("/export",{payload:t})}setEmbedding(t,e,s){return this.put(`/${t}/embeddings/${e}`,{payload:s})}}class B extends h{constructor(t){super(t,"/api/v1/types")}list(t={},e){const s=t.limit||100,r=t.offset||0,n=t.query||{};return this.get("/",{query:{limit:s,offset:r,layout:!!e?.layout,schema:!!e?.schema,...n}})}find(t){return this.post("/find",{payload:t})}retrieve(t){return this.get(`/${t}`)}getTypeByName(t){return this.get(`/name/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}}class J extends h{constructor(t){super(t,"/api/v1/workflows"),this.rules=new L(this),this.definitions=new W(this)}getActivityCatalog(){return this.get("/activity-catalog")}listRuns(t,e,s){return this.post("/runs",{payload:{documentId:t,eventName:e,ruleId:s}})}listConversations(){return this.get("/conversations")}searchRuns(t){return this.post("/runs",{payload:t})}sendSignal(t,e,s,r){return this.post(`/runs/${t}/${e}/signal/${s}`,{payload:r})}getRunDetails(t,e,s=!1){const r={include_history:s};return this.get(`/runs/${e}/${t}`,{query:r})}getRunInteraction(t,e){return this.get(`/runs/${t}/${e}/interaction`)}terminate(t,e,s){return this.post(`/runs/${t}/${e}/actions/terminate`,{payload:{reason:s}})}cancel(t,e,s){return this.post(`/runs/${t}/${e}/actions/cancel`,{payload:{reason:s}})}execute(t,e={}){return this.post(`/execute/${t}`,{payload:e})}postMessage(t,e){if(!t)throw new Error("runId is required");return this.post(`/runs/${t}/updates`,{payload:e})}retrieveMessages(t,e,s){const r={since:s};return this.get(`/runs/${t}/${e}/updates`,{query:r})}async streamMessages(t,s,r,n){return new Promise(((i,a)=>{let o=0,u=n||0,l=!1,c=null,h=null;const d=10,p=t=>{const e=Math.min(1e3*Math.pow(2,t),3e4);return e+.1*Math.random()*e},g=()=>{h&&(clearInterval(h),h=null),c&&(c.close(),c=null)},y=t=>{l||(l=!0,g(),i(t))},f=async(n=!1)=>{if(!l)try{const m=await q(),w=this.client,v=new URL(w.workflows.baseUrl+`/runs/${t}/${s}/stream`);u>0&&v.searchParams.set("since",u.toString());const $=w._auth?await w._auth():void 0;if(!$)return void a(new Error("No auth token available"));const b=$.split(" ")[1];v.searchParams.set("access_token",b),n&&console.log(`Reconnecting to SSE stream for run ${s} (attempt ${o+1}/10)`);const x=new m(v.href);c=x,h=setInterval((()=>{}),1e3),x.onopen=()=>{n&&console.log(`Successfully reconnected to SSE stream for run ${s}`),o=0},x.onmessage=t=>{if(t.data&&!t.data.startsWith(":"))try{const s=JSON.parse(t.data);s.timestamp&&(u=Math.max(u,s.timestamp)),r&&r(s,y);s.type===e.TERMINATED||s.type===e.COMPLETE&&(!s.workstream_id||"main"===s.workstream_id)?(console.log("Closing stream due to COMPLETE message from main workstream"),l||(l=!0,g(),i(null))):s.type===e.COMPLETE&&console.log(`Received COMPLETE message from non-main workstream: ${s.workstream_id||"unknown"}, keeping stream open`)}catch(e){console.error("Failed to parse SSE message:",e,t.data)}else console.log("Received comment or heartbeat; ignoring it.: ",t.data)},x.onerror=t=>{if(!l)if(console.warn(`SSE stream error for run ${s}:`,t),g(),o<d){const t=p(o);console.log(`Attempting to reconnect in ${t}ms (attempt ${o+1}/10)`),o++,setTimeout((()=>{l||f(!0)}),t)}else console.error(`Failed to reconnect to SSE stream for run ${s} after 10 attempts`),l=!0,a(new Error("SSE connection failed after 10 reconnection attempts"))}}catch(t){if(console.error("Error setting up SSE stream:",t),o<d){const t=p(o);o++,setTimeout((()=>{l||f(!0)}),t)}else a(t)}};return f(!1),()=>{l=!0,g()}}))}}class L extends h{constructor(t){super(t,"/rules")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}execute(t,e,s){const r={objectIds:e,vars:s};return this.post(`/${t}/execute`,{payload:r})}}class W extends h{constructor(t){super(t,"/definitions")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}}class z extends h{constructor(t){super(t,"/api/v1/collections")}search(t){return this.post("/search",{payload:t})}computeListFacets(t){return this.post("/facets",{payload:t})}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}addMembers(t,e){return this.post(`/${t}/members`,{payload:{action:"add",members:e}})}listMembers(t,e){return this.get(`/${t}/members`,{query:{...e}})}computeFacets(t,e){return this.post(`/${t}/facets`,{payload:e})}searchMembers(t,e){return this.post(`/${t}/search`,{payload:e})}deleteMembers(t,e){return this.post(`/${t}/members`,{payload:{action:"delete",members:e}})}delete(t){return this.del(`/${t}`)}}class V extends c{constructor(t={}){super(function(t){if(!t)throw new Error("zeno client serverUrl is required");return t}(t.serverUrl)),this.objects=new O(this),this.types=new B(this),this.workflows=new J(this),this.files=new N(this),this.commands=new I(this),this.agents=new A(this),this.collections=new z(this),this.embeddings=new F(this),t.apikey&&this.withApiKey(t.apikey),this.onRequest=t.onRequest,this.onResponse=t.onResponse,this.errorFactory=t=>404===t.status?new M(t.request,t):t}withApiKey(t){return this.withAuthCallback(t?()=>Promise.resolve(`Bearer ${t}`):void 0)}runOperation(t){return this.post("/api/v1/operations",{payload:t})}}class K extends h{constructor(t){super(t,"/api/v1/training")}listSessions(t={}){return this.get("/",{query:t})}listSessionNames(t={}){return this.get("/names",{query:t})}createSession(t){return this.post("/",{payload:t})}getSession(t){return this.get("/"+t)}addToSession(t,e){return this.post("/"+t+"/add",{payload:{runs:e}})}listSessionRuns(t,e=100,s=0){return this.get("/"+t+"/runs",{query:{limit:e,offset:s}})}buildSession(t){return this.post("/"+t+"/build")}getDataUrl(t){return this.get("/"+t+"/url")}getDataUploadUrl(t,e=!1){return this.get("/"+t+"/upload-url",e?{query:{resumable:"true"}}:{})}startTraining(t){return this.post("/"+t+"/start")}cancelTraining(t){return this.post("/"+t+"/cancel")}getTrainingJob(t){return this.get(`/job/${t}`)}getAndSyncTrainingJob(t){return this.get(`/job/${t}`,{query:{sync:"true"}})}setDataset(t,e="default"){return this.post("/"+t+"/dataset",{payload:{dataset:e}})}}class H extends h{constructor(t){super(t,"/api/v1/users")}retrieve(t){return this.get("/"+t)}}class G extends c{static async fromAuthToken(t,e){e||(e=X(t));const s=Q(e.endpoints);return await new G({serverUrl:s.studio,storeUrl:s.store}).withApiKey(t)}static decodeEndpoints(){}constructor(t={site:"api.vertesia.io"}){let e,s;if(t.serverUrl)e=t.serverUrl;else{if(!t.site)throw new Error("Parameter 'site' or 'serverUrl' is required for VertesiaClient");e=`https://${t.site}`}if(t.storeUrl)s=t.storeUrl;else{if(!t.site)throw new Error("Parameter 'site' or 'storeUrl' is required for VertesiaClient");s=`https://${t.site}`}super(e),this._jwt=null,this.projects=new S(this),this.environments=new w(this),this.interactions=new k(this),this.prompts=new R(this),this.runs=new j(this),this.account=new d(this),this.accounts=new p(this),this.apikeys=new y(this),this.analytics=new g(this),this.training=new K(this),this.users=new H(this),this.iam=new $(this),this.refs=new U(this),this.commands=new m(this),this.apps=new f(this),this.store=new V({serverUrl:s,apikey:t.apikey,onRequest:t.onRequest,onResponse:t.onResponse}),t.apikey&&this.withApiKey(t.apikey),t.projectId&&(this.headers["x-project-id"]=t.projectId),this.onRequest=t.onRequest,this.onResponse=t.onResponse,this.sessionTags=t.sessionTags}withAuthCallback(t){return this.store.withAuthCallback(t),super.withAuthCallback(t)}async withApiKey(t){return this.withAuthCallback(t?async()=>{if(!function(t){return t.startsWith("pk-")||t.startsWith("sk-")}(t))return`Bearer ${t}`;if(function(t){if(!t)return!0;const e=X(t).exp;return Date.now()<=1e3*e-6e4}(this._jwt)){const e=await this.getAuthToken(t);this._jwt=e.token}return`Bearer ${this._jwt}`}:void 0)}async getRawJWT(){if(!this._jwt&&this._auth){const t=await this._auth();this._jwt||(this._jwt=t.trim().split(" ")[1])}return this._jwt||null}async getDecodedJWT(){const t=await this.getRawJWT();return t?X(t):null}async getProject(){const t=await this.getDecodedJWT();return t?.project||null}async getAccount(){const t=await this.getDecodedJWT();return t?.account||null}get workflows(){return this.store.workflows}get objects(){return this.store.objects}get files(){return this.store.files}get types(){return this.store.types}get storeUrl(){return this.store.baseUrl}async getAuthToken(t,e){const s={accountId:e,token:t};return this.get("/auth/token",{query:s,headers:{authorization:void 0}})}}function X(t){const e=function(t){const e=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(4*Math.ceil(t.length/4),"=");if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");if("undefined"!=typeof atob&&"undefined"!=typeof TextDecoder){const t=atob(e),s=Uint8Array.from(t,(t=>t.charCodeAt(0)));return(new TextDecoder).decode(s)}throw new Error("No base64 decoder available")}(t.split(".")[1]);return JSON.parse(e)}function Q(t){return t?"string"==typeof t?Y(t):t:Y("api.vertesia.io")}function Y(t){if("local"===t)return{studio:"http://localhost:8091",store:"http://localhost:8092"};{const e=`https://${t}`;return{studio:e,store:e}}}class Z{constructor(t,e){this.id=t,this.client=e instanceof G?e:new G(e)}retrieve(){return this.client.interactions.retrieve(this.id)}update(t){return this.client.interactions.update(this.id,t)}render(t){}async execute(t={},e){return E(this.client,this.id,t,e)}}export{I as CommandsApi,Z as InteractionBase,O as ObjectsApi,P as StreamSource,B as TypesApi,G as VertesiaClient,J as WorkflowsApi,W as WorkflowsDefinitionApi,L as WorkflowsRulesApi,V as ZenoClient,Q as decodeEndpoints,X as decodeJWT};
2
2
  //# sourceMappingURL=vertesia-client.js.map