@kivox/client 0.1.0-beta.4 → 0.1.0-beta.41

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
@@ -1,91 +1,15 @@
1
- # KIVOX JavaScript client
1
+ # typescript
2
2
 
3
- `@kivox/client` is the official JavaScript/TypeScript client for interacting with KIVOX. It provides the necessary abstractions and bindings to handle sessions, real-time events, audio, and communication with agents.
4
-
5
- ## Features
6
-
7
- - Unified client for the Kivox API
8
- - Conversation and voice session management
9
- - WebSockets, events, and real-time state
10
- - Audio recording and playback
11
- - Strongly typed contracts and types in TypeScript
12
- - Framework-agnostic (Svelte, React, Angular, Vue, Vanilla, etc.)
13
-
14
- ## Documentation
15
-
16
- <https://kivox.ju4n97.workers.dev/docs/clients/kivox-js>
17
-
18
- ## Installation
3
+ To install dependencies:
19
4
 
20
5
  ```bash
21
- # NPM
22
- npm install @kivox/client
23
-
24
- # PNPM
25
- pnpm add @kivox/client
26
-
27
- # Yarn
28
- yarn add @kivox/client
29
-
30
- # Bun
31
- bun add @kivox/client
32
- ```
33
-
34
- ## Basic example
35
-
36
- ```ts
37
- import { KivoxClient } from '@kivox/client';
38
-
39
- const kivox = new KivoxClient({
40
- baseUrl: 'http://localhost:8787',
41
- });
42
-
43
- // List agents
44
- const agents = await kivox.agents.list();
45
-
46
- // Connect to an agent
47
- const session = await kivox.conversations.connect({
48
- agentId: '019bb51e-e45f-75e3-b828-94fdf231711e',
49
- onEvent: (event) => {
50
- switch (event.type) {
51
- case 'response.delta.text':
52
- console.log('Text:', event.chunk);
53
- break;
54
- case 'response.delta.audio':
55
- audioPlayer.enqueue(event.audio);
56
- break;
57
- case 'response.complete':
58
- console.log('Response complete');
59
- break;
60
- }
61
- }
62
- });
63
-
64
- // Send a message
65
- session.sendText('Hello, how can you help me?');
6
+ bun install
66
7
  ```
67
8
 
68
- ## Authentication
69
-
70
- ```ts
71
- import { KivoxClient } from '@kivox/client';
9
+ To run:
72
10
 
73
- const kivox = new KivoxClient({
74
- baseUrl: 'http://localhost:8787',
75
- headers: {
76
- Authorization: 'Bearer token',
77
- },
78
- });
11
+ ```bash
12
+ bun run index.ts
79
13
  ```
80
14
 
81
- ## Other examples
82
-
83
- - [alpine-chat-app](https://github.com/ekisa-team/kivox/tree/main/examples/alpine-chat-app)
84
-
85
- ## Contributing
86
-
87
- [https://github.com/ekisa-team/kivox/blob/main/CONTRIBUTING.md](https://github.com/ekisa-team/kivox/blob/main/CONTRIBUTING.md)
88
-
89
- ## License
90
-
91
- [LICENSE](https://github.com/ekisa-team/kivox/blob/main/LICENSE)
15
+ This project was created using `bun init` in bun v1.3.10. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ var{defineProperty:b,getOwnPropertyNames:$G,getOwnPropertyDescriptor:JG}=Object,KG=Object.prototype.hasOwnProperty;function NG(G){return this[G]}var WG=(G)=>{var V=(l??=new WeakMap).get(G),X;if(V)return V;if(V=b({},"__esModule",{value:!0}),G&&typeof G==="object"||typeof G==="function"){for(var Z of $G(G))if(!KG.call(V,Z))b(V,Z,{get:NG.bind(G,Z),enumerable:!(X=JG(G,Z))||X.enumerable})}return l.set(G,V),V},l;var DG=(G)=>G;function _G(G,V){this[G]=DG.bind(null,V)}var IG=(G,V)=>{for(var X in V)b(G,X,{get:V[X],enumerable:!0,configurable:!0,set:_G.bind(V,X)})};var TG={};IG(TG,{createSessionClient:()=>kG,createBearerClient:()=>LG,ConversationTransportError:()=>O,ConversationSession:()=>T});module.exports=WG(TG);var QG=/\{[^{}]+\}/g,OG=()=>{return typeof process==="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici};function BG(){return Math.random().toString(36).slice(2,11)}function s(G){let{baseUrl:V="",Request:X=globalThis.Request,fetch:Z=globalThis.fetch,querySerializer:Y,bodySerializer:$,pathSerializer:J,headers:_,requestInitExt:S=void 0,...GG}={...G};S=OG()?S:void 0,V=n(V);let A=[];async function Q(N,K){let{baseUrl:F,fetch:c=Z,Request:v=X,headers:h,params:k={},parseAs:j="json",querySerializer:x,bodySerializer:d=$??FG,pathSerializer:VG,body:m,middleware:XG=[],...z}=K||{},U=V;if(F)U=n(F)??V;let g=typeof Y==="function"?Y:o(Y);if(x)g=typeof x==="function"?x:o({...typeof Y==="object"?Y:{},...x});let u=VG||J||HG,P=m===void 0?void 0:d(m,i(_,h,k.header)),YG=i(P===void 0||P instanceof FormData?{}:{"Content-Type":"application/json"},_,h,k.header),B=[...A,...XG],ZG={redirect:"follow",...GG,...z,body:P,headers:YG},R,E,H=new v(MG(N,{baseUrl:U,params:k,querySerializer:g,pathSerializer:u}),ZG),W;for(let I in z)if(!(I in H))H[I]=z[I];if(B.length){R=BG(),E=Object.freeze({baseUrl:U,fetch:c,parseAs:j,querySerializer:g,bodySerializer:d,pathSerializer:u});for(let I of B)if(I&&typeof I==="object"&&typeof I.onRequest==="function"){let D=await I.onRequest({request:H,schemaPath:N,params:k,options:E,id:R});if(D)if(D instanceof v)H=D;else if(D instanceof Response){W=D;break}else throw Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!W){try{W=await c(H,S)}catch(I){let D=I;if(B.length)for(let M=B.length-1;M>=0;M--){let w=B[M];if(w&&typeof w==="object"&&typeof w.onError==="function"){let L=await w.onError({request:H,error:D,schemaPath:N,params:k,options:E,id:R});if(L){if(L instanceof Response){D=void 0,W=L;break}if(L instanceof Error){D=L;continue}throw Error("onError: must return new Response() or instance of Error")}}}if(D)throw D}if(B.length)for(let I=B.length-1;I>=0;I--){let D=B[I];if(D&&typeof D==="object"&&typeof D.onResponse==="function"){let M=await D.onResponse({request:H,response:W,schemaPath:N,params:k,options:E,id:R});if(M){if(!(M instanceof Response))throw Error("onResponse: must return new Response() when modifying the response");W=M}}}}let p=W.headers.get("Content-Length");if(W.status===204||H.method==="HEAD"||p==="0"&&!W.headers.get("Transfer-Encoding")?.includes("chunked"))return W.ok?{data:void 0,response:W}:{error:void 0,response:W};if(W.ok)return{data:await(async()=>{if(j==="stream")return W.body;if(j==="json"&&!p){let D=await W.text();return D?JSON.parse(D):void 0}return await W[j]()})(),response:W};let f=await W.text();try{f=JSON.parse(f)}catch{}return{error:f,response:W}}return{request(N,K,F){return Q(K,{...F,method:N.toUpperCase()})},GET(N,K){return Q(N,{...K,method:"GET"})},PUT(N,K){return Q(N,{...K,method:"PUT"})},POST(N,K){return Q(N,{...K,method:"POST"})},DELETE(N,K){return Q(N,{...K,method:"DELETE"})},OPTIONS(N,K){return Q(N,{...K,method:"OPTIONS"})},HEAD(N,K){return Q(N,{...K,method:"HEAD"})},PATCH(N,K){return Q(N,{...K,method:"PATCH"})},TRACE(N,K){return Q(N,{...K,method:"TRACE"})},use(...N){for(let K of N){if(!K)continue;if(typeof K!=="object"||!(("onRequest"in K)||("onResponse"in K)||("onError"in K)))throw Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");A.push(K)}},eject(...N){for(let K of N){let F=A.indexOf(K);if(F!==-1)A.splice(F,1)}}}}function q(G,V,X){if(V===void 0||V===null)return"";if(typeof V==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${G}=${X?.allowReserved===!0?V:encodeURIComponent(V)}`}function t(G,V,X){if(!V||typeof V!=="object")return"";let Z=[],Y={simple:",",label:".",matrix:";"}[X.style]||"&";if(X.style!=="deepObject"&&X.explode===!1){for(let _ in V)Z.push(_,X.allowReserved===!0?V[_]:encodeURIComponent(V[_]));let J=Z.join(",");switch(X.style){case"form":return`${G}=${J}`;case"label":return`.${J}`;case"matrix":return`;${G}=${J}`;default:return J}}for(let J in V){let _=X.style==="deepObject"?`${G}[${J}]`:J;Z.push(q(_,V[J],X))}let $=Z.join(Y);return X.style==="label"||X.style==="matrix"?`${Y}${$}`:$}function a(G,V,X){if(!Array.isArray(V))return"";if(X.explode===!1){let $={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[X.style]||",",J=(X.allowReserved===!0?V:V.map((_)=>encodeURIComponent(_))).join($);switch(X.style){case"simple":return J;case"label":return`.${J}`;case"matrix":return`;${G}=${J}`;default:return`${G}=${J}`}}let Z={simple:",",label:".",matrix:";"}[X.style]||"&",Y=[];for(let $ of V)if(X.style==="simple"||X.style==="label")Y.push(X.allowReserved===!0?$:encodeURIComponent($));else Y.push(q(G,$,X));return X.style==="label"||X.style==="matrix"?`${Z}${Y.join(Z)}`:Y.join(Z)}function o(G){return function(X){let Z=[];if(X&&typeof X==="object")for(let Y in X){let $=X[Y];if($===void 0||$===null)continue;if(Array.isArray($)){if($.length===0)continue;Z.push(a(Y,$,{style:"form",explode:!0,...G?.array,allowReserved:G?.allowReserved||!1}));continue}if(typeof $==="object"){Z.push(t(Y,$,{style:"deepObject",explode:!0,...G?.object,allowReserved:G?.allowReserved||!1}));continue}Z.push(q(Y,$,G))}return Z.join("&")}}function HG(G,V){let X=G;for(let Z of G.match(QG)??[]){let Y=Z.substring(1,Z.length-1),$=!1,J="simple";if(Y.endsWith("*"))$=!0,Y=Y.substring(0,Y.length-1);if(Y.startsWith("."))J="label",Y=Y.substring(1);else if(Y.startsWith(";"))J="matrix",Y=Y.substring(1);if(!V||V[Y]===void 0||V[Y]===null)continue;let _=V[Y];if(Array.isArray(_)){X=X.replace(Z,a(Y,_,{style:J,explode:$}));continue}if(typeof _==="object"){X=X.replace(Z,t(Y,_,{style:J,explode:$}));continue}if(J==="matrix"){X=X.replace(Z,`;${q(Y,_)}`);continue}X=X.replace(Z,J==="label"?`.${encodeURIComponent(_)}`:encodeURIComponent(_))}return X}function FG(G,V){if(G instanceof FormData)return G;if(V){if((V.get instanceof Function?V.get("Content-Type")??V.get("content-type"):V["Content-Type"]??V["content-type"])==="application/x-www-form-urlencoded")return new URLSearchParams(G).toString()}return JSON.stringify(G)}function MG(G,V){let X=`${V.baseUrl}${G}`;if(V.params?.path)X=V.pathSerializer(X,V.params.path);let Z=V.querySerializer(V.params.query??{});if(Z.startsWith("?"))Z=Z.substring(1);if(Z)X+=`?${Z}`;return X}function i(...G){let V=new Headers;for(let X of G){if(!X||typeof X!=="object")continue;let Z=X instanceof Headers?X.entries():Object.entries(X);for(let[Y,$]of Z)if($===null)V.delete(Y);else if(Array.isArray($))for(let J of $)V.append(Y,J);else if($!==void 0)V.set(Y,$)}return V}function n(G){if(G.endsWith("/"))return G.substring(0,G.length-1);return G}class T{_transport;_conversationId;_closed=!1;_onEvent;_pendingAudioMetadata=null;_remainingMs=0;_elapsedMs=0;get conversationId(){return this._conversationId}get remainingMs(){return this._remainingMs}get elapsedMs(){return this._elapsedMs}get closed(){return this._closed}constructor(G,V,X){this._transport=G,this._conversationId=V,this._onEvent=X.onEvent,this.#G()}sendText(G){if(this._closed){console.warn("Cannot send text: session is closed");return}this._transport.send({type:"input_text",text:G})}sendAudio(G){if(this._closed){console.warn("Cannot send audio: session is closed");return}this._transport.send({type:"input_audio"}),this._transport.sendBinary(G)}streamAudio(G){if(this._closed){console.warn("Cannot stream audio: session is closed");return}this._transport.send({type:"input_audio_stream"}),this._transport.sendBinary(G)}cancelRequest(){if(this._closed){console.warn("Cannot cancel request: session is closed");return}this._transport.send({type:"cancel"})}end(){if(this._closed){console.warn("Cannot end session: session is closed");return}this._transport.send({type:"end"})}close(){if(this._closed)return;this._closed=!0,this._transport.close()}#G(){this._transport.onMessage((G)=>{let V=G;if(V.type==="audio_delta"){this._pendingAudioMetadata={size:V.size};return}if(V.type==="tick")this._remainingMs=V.remaining_ms,this._elapsedMs=V.elapsed_ms;if(V.type==="session_closed")this._closed=!0;this._onEvent?.(V)}),this._transport.onBinary((G)=>{if(this._pendingAudioMetadata){let V={type:"audio_delta",size:this._pendingAudioMetadata.size,audio:G};this._pendingAudioMetadata=null,this._onEvent?.(V)}}),this._transport.onClose(()=>{if(this._closed)return;this._closed=!0,this._onEvent?.({type:"connection_lost",reason:"socket_closed"})}),this._transport.onError(()=>{if(this._closed)return;this._closed=!0,this._onEvent?.({type:"connection_lost",reason:"socket_error"})})}}class O extends Error{code;constructor(G,V="TRANSPORT_ERROR"){super(G);this.code=V;this.name="ConversationTransportError"}}class y{_ws;_closed=!1;_onMessage=null;_onBinary=null;_onError=null;_onClose=null;constructor(G){this._ws=G}async connect(){if(this._ws.readyState===WebSocket.OPEN)throw new O("Already connected","ALREADY_CONNECTED");if(this._ws.readyState===WebSocket.CLOSING||this._ws.readyState===WebSocket.CLOSED)throw new O("Socket is closing or closed","SOCKET_CLOSED");return new Promise((G,V)=>{let X,Z;X=()=>{this._ws.removeEventListener("open",X),this._ws.removeEventListener("error",Z),this.#G(),G()},Z=()=>{this._ws.removeEventListener("open",X),this._ws.removeEventListener("error",Z),V(new O("Connection failed","CONNECTION_FAILED"))},this._ws.addEventListener("open",X),this._ws.addEventListener("error",Z)})}send(G){if(this._ws.readyState!==WebSocket.OPEN)throw new O("Not connected","NOT_CONNECTED");this._ws.send(JSON.stringify(G))}async sendBinary(G){if(this._ws.readyState!==WebSocket.OPEN)throw new O("Not connected","NOT_CONNECTED");let V=await G.arrayBuffer();this._ws.send(V)}onMessage(G){this._onMessage=G}onBinary(G){this._onBinary=G}onError(G){this._onError=G}onClose(G){this._onClose=G}close(){if(this._closed)return;if(this._closed=!0,this._ws.readyState===WebSocket.OPEN||this._ws.readyState===WebSocket.CONNECTING)this._ws.close();this._onClose?.()}#G(){this._ws.addEventListener("message",(G)=>{if(G.data instanceof Blob)this._onBinary?.(G.data);else if(G.data instanceof ArrayBuffer)this._onBinary?.(new Blob([G.data]));else if(typeof G.data==="string")try{let V=JSON.parse(G.data);this._onMessage?.(V)}catch(V){console.warn("Failed to parse JSON message:",G.data,V)}}),this._ws.addEventListener("error",()=>{if(this._closed)return;this._onError?.(new O("WebSocket error")),this.close()}),this._ws.addEventListener("close",()=>{if(this._closed)return;this.close()})}}class C{#G;constructor(G){this.#G=G}async connect(G){let V=this.#V("/conversations/ws"),X=new y(new WebSocket(V));return await X.connect(),X.send({type:"handshake",agent_id:G.agent_id,channel:G.channel}),new Promise((Z,Y)=>{let $=!1;X.onMessage((J)=>{switch(J.type){case"handshake_ok":$=!0,G.onConnection?.(J),Z(new T(X,J.conversation_id,G));break;case"handshake_error":$=!0,G.onConnection?.(J),X.close(),Y(Error(`Handshake rejected: ${J.reason}`));break;default:}}),X.onError((J)=>{if(!$)Y(J)}),X.onClose(()=>{if(!$)Y(Error("Connection lost during handshake"))})})}#V(G){return`${this.#G.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://").replace(/\/$/,"")}${G}`}}var r="https://server.kivox.com.co";function e(G){return s(G)}function kG({baseUrl:G=r}={}){return{api:e({baseUrl:G,credentials:"include"}),realtime:new C(G)}}function LG({bearerToken:G,baseUrl:V=r}){return{api:e({baseUrl:V,headers:{Authorization:`Bearer ${G}`}}),realtime:new C(V)}}