codicent-app-sdk 0.3.93 → 0.3.95
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 +5 -0
- package/dist/cjs/config/index.d.ts +4 -0
- package/dist/cjs/config/index.d.ts.map +1 -1
- package/dist/cjs/config/index.js +1 -1
- package/dist/cjs/hooks/useCodicentApp.d.ts.map +1 -1
- package/dist/cjs/hooks/useCodicentApp.js +1 -1
- package/dist/cjs/hooks/useRealtimeVoiceAI.d.ts +20 -3
- package/dist/cjs/hooks/useRealtimeVoiceAI.d.ts.map +1 -1
- package/dist/cjs/hooks/useRealtimeVoiceAI.js +1 -1
- package/dist/cjs/services/codicent.d.ts +4 -0
- package/dist/cjs/services/codicent.d.ts.map +1 -1
- package/dist/cjs/services/codicent.js +1 -1
- package/dist/cjs/utils/withWakeLock.js +1 -1
- package/dist/esm/config/index.d.ts +4 -0
- package/dist/esm/config/index.d.ts.map +1 -1
- package/dist/esm/config/index.js +1 -1
- package/dist/esm/hooks/useCodicentApp.d.ts.map +1 -1
- package/dist/esm/hooks/useCodicentApp.js +1 -1
- package/dist/esm/hooks/useRealtimeVoiceAI.d.ts +20 -3
- package/dist/esm/hooks/useRealtimeVoiceAI.d.ts.map +1 -1
- package/dist/esm/hooks/useRealtimeVoiceAI.js +1 -1
- package/dist/esm/services/codicent.d.ts +4 -0
- package/dist/esm/services/codicent.d.ts.map +1 -1
- package/dist/esm/services/codicent.js +1 -1
- package/dist/esm/utils/withWakeLock.js +1 -1
- package/dist/index.d.ts +28 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -88,9 +88,13 @@ BUTTON_BORDER_RADIUS: string
|
|
|
88
88
|
BUTTON_BACKGROUND_COLOR: string
|
|
89
89
|
DEFAULT_LANGUAGE: string
|
|
90
90
|
SUBSCRIPTION_NEEDED: boolean
|
|
91
|
+
REALTIME_VOICE_MODEL: string // Voice model: "alloy", "shimmer", or "echo" (default: "alloy")
|
|
92
|
+
USE_REALTIME_SESSION_ENDPOINT: boolean // Use secure session endpoint (default: true)
|
|
91
93
|
// ...and more
|
|
92
94
|
```
|
|
93
95
|
|
|
96
|
+
For AI voice configuration and security, see the [Voice Upgrade Guide](VOICE_UPGRADE_GUIDE.md).
|
|
97
|
+
|
|
94
98
|
|
|
95
99
|
### Example: Simple Chat App
|
|
96
100
|
|
|
@@ -128,6 +132,7 @@ const App = () => {
|
|
|
128
132
|
|
|
129
133
|
- **React Components:** Chat UI, Markdown, File Upload, Audio, and more
|
|
130
134
|
- **Hooks:** Chat state, authentication, localization, theme, and more
|
|
135
|
+
- **AI Voice:** Realtime voice AI with secure session endpoint support (see [Voice Upgrade Guide](VOICE_UPGRADE_GUIDE.md))
|
|
131
136
|
- **Utilities:** Helpers for app state, device, logging, and more
|
|
132
137
|
- **TypeScript Support:** Full typings for all exports
|
|
133
138
|
- **Customizable:** Theming and configuration options
|
|
@@ -93,6 +93,10 @@ export interface AppConfigOptions {
|
|
|
93
93
|
MODULE_VOICE: boolean;
|
|
94
94
|
PUBLIC_FLOW_CODICENT: undefined | string;
|
|
95
95
|
REALTIME_VOICE_API_KEY: string;
|
|
96
|
+
REALTIME_VOICE_MODEL: string;
|
|
97
|
+
USE_REALTIME_SESSION_ENDPOINT: boolean;
|
|
98
|
+
REALTIME_SESSION_ENDPOINT: string;
|
|
99
|
+
REALTIME_CONFIG_ENDPOINT: string;
|
|
96
100
|
SEND_BUTTON_ROUND_BACKGROUND: boolean;
|
|
97
101
|
SHOW_CANVAS_BUTTON: boolean;
|
|
98
102
|
SHOW_CHAT_PROMPTS: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/config/index.ts"],"names":[],"mappings":"AAGA,qBAAa,SAAS;;IAKpB,iBAAiB,EAAE,MAAM,CAAM;IAC/B,2BAA2B,EAAE,MAAM,CAAM;IACzC,IAAI,EAAE;QACJ,CAAC,GAAG,EAAE,MAAM,GA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,GAAG,EAAE,MAAM,GAAG;YAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;SAAE,CAAA;KAAE,GAAG,SAAS,CAAC;IAIvE,iBAAiB,EAAE,SAAS,GAAG,MAAM,CAAC;IACtC,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,kBAAkB,EAAE,OAAO,CAAC;IAC5B,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,yBAAyB,EAAE,OAAO,CAAC;IACnC,oBAAoB,EAAE,SAAS,GAAG,MAAM,CAAC;IACzC,2BAA2B,EAAE,OAAO,CAAC;CACtC;AA2HD,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,gBAAgB,EAAE,GAAG,EAAE,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAG5F;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,OAAO,CAAC,gBAAgB,CAAM,QAgBtE"}
|
package/dist/cjs/config/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _=require("../node_modules/mermaid/dist/mermaid.core.js");class T{constructor(){this.CHAT_INSTRUCTIONS="",this.REALTIME_VOICE_INSTRUCTIONS="",this.apps={}}}const O={LOGIN_REDIRECT:!1,ABOUT_TEXT:"Codicent APP SDK",ANONYMOUS_CODICENT:void 0,ANONYMOUS_TOKEN:void 0,API_BASE_URL:"https://codicent.com/",APP_BUTTONS:void 0,APP_CHAT_TEXT_PLACEHOLDER:void 0,APP_CHAT_TITLE:void 0,APP_CONFIG:new T,APP_FOOTER_COLOR:void 0,APP_FOOTER_SELECTED_COLOR:void 0,APP_FOOTER_TEXT_COLOR:void 0,APP_HEADER_COLOR:void 0,APP_HEADER_ICON_URL:void 0,APP_HEADER_TEXT_COLOR:void 0,APP_ICON_URL:void 0,APP_LOG_CODICENT:"",APP_LOG_TOKEN:"",APP_LOGBOOK_TITLE:void 0,APP_MENU_TITLE:void 0,APP_NAME:void 0,APP_PREFIX:void 0,APP_SAVE_TITLE:void 0,APP_SEARCH_TITLE:void 0,APP_SLOGAN:void 0,APP_SPLASH_TEXT:void 0,APP_SPLASH_URL:void 0,APP_TEMPLATE:"",APP_TITLE:void 0,AUTH_REDIRECT_URL:void 0,AUTH0_AUDIENCE:"https://codicent.com/api",AUTH0_CLIENT_ID:"80STzWmmzN3Tgf76HgFRyv54keYmvnaw",AUTH0_DOMAIN:"auth.codicent.com",AUTH0_PROVIDER_SCOPE:"read:current_user update:current_user_metadata openid profile email",AUTH0_SCOPE:"read:current_user",AUTH0_USER_DOMAIN:void 0,BUTTON_ACTIVE_COLOR:void 0,BUTTON_BACKGROUND_COLOR:void 0,BUTTON_BORDER_RADIUS:void 0,BUTTON_HOVER_COLOR:void 0,BUTTON_TAG:"app-button",BUTTON_TEXT_COLOR:void 0,CHAT_BACKGROUND_IMAGE_URL:void 0,CHAT_BOT_BACKGROUND_COLOR:void 0,CHAT_BOT_TEXT_COLOR:void 0,CHAT_INSTRUCTIONS:void 0,CHAT_USER_BACKGROUND_COLOR:void 0,CHAT_USER_TEXT_COLOR:void 0,CHAT_WELCOME:"Welcome",COMPOSE_BACKGROUND_IMAGE_URL:void 0,COMPOSE_HIDE_LOCATION:void 0,COMPOSE_SIMPLE_ATTACH_FILE:void 0,DEFAULT_LANGUAGE:"en",HIDE_CHAT_BUTTON:!1,HIDE_MENU_BUTTON:!1,HIDE_REGISTER_BUTTON:!1,HIDE_SAVE_BUTTON:!1,HOME_BACKGROUND_IMAGE_URL:void 0,INDEX_TITLE:void 0,LOGBOOK_TAG_DEFINITIONS:{},LOGBOOK_TAGS:"[]",MENU_BACKGROUND_IMAGE_URL:void 0,MESSAGE_HIDE_BAR:!1,MODULE_VOICE:!1,PUBLIC_FLOW_CODICENT:void 0,REALTIME_VOICE_API_KEY:"",SEND_BUTTON_ROUND_BACKGROUND:!1,SHOW_CANVAS_BUTTON:!1,SHOW_CHAT_PROMPTS:!1,SHOW_HELP_BUTTON:!1,SHOW_LOGBOOK_BUTTON:!1,SHOW_MICROPHONE_BUTTON:!1,SHOW_SETTINGS_BUTTON:!1,SHOW_SNAP_BUTTON:!1,SHOW_VOICE_BUTTON:!1,STRIP_CUSTOMER_PORTAL:"",STRIPE_PRICE_ID:"",STRIPE_PUBLIC_KEY:"",SUBSCRIPTION_NEEDED:!1,THEME_WELCOME:void 0,USER_PREFIX:void 0,WELCOME_STATUS_PROMPT:"",SHOW_SEND_BUTTON_TEXT:!1,SHOW_SAVE_BUTTON_TEXT:!1,FORM_BACKGROUND_IMAGE_URL:void 0,AUTO_TRANSLATE:!0,FORCE_LANGUAGE:void 0,TRANSLATIONS:void 0,LOGIN_WELCOME_TEXT:void 0,LOGIN_HIDE_WELCOME:!1,LOGIN_LOGO_URL:void 0,HIDE_CHAT_ADD_FILE_BUTTON:!1,FORM_ACCEPT_MARKDOWN:void 0,RESTART_AUDIO_ON_TAKE_PHOTO:!1};const E=function(_){return new Proxy(_,{get:(_,T,O)=>Reflect.get(_,T,O)})}(O);exports.AppConfig=T,exports.getConfigValue=function(_){return E[_]},exports.initCodicentApp=function(T={}){for(const[_,E]of Object.entries(T))void 0!==E&&(O[_]=E);void 0!==T.TRANSLATIONS&&(globalThis.__CODICENT_REINIT_I18N__=!0),_.default.initialize({startOnLoad:!1})};
|
|
1
|
+
"use strict";var _=require("../node_modules/mermaid/dist/mermaid.core.js");class T{constructor(){this.CHAT_INSTRUCTIONS="",this.REALTIME_VOICE_INSTRUCTIONS="",this.apps={}}}const O={LOGIN_REDIRECT:!1,ABOUT_TEXT:"Codicent APP SDK",ANONYMOUS_CODICENT:void 0,ANONYMOUS_TOKEN:void 0,API_BASE_URL:"https://codicent.com/",APP_BUTTONS:void 0,APP_CHAT_TEXT_PLACEHOLDER:void 0,APP_CHAT_TITLE:void 0,APP_CONFIG:new T,APP_FOOTER_COLOR:void 0,APP_FOOTER_SELECTED_COLOR:void 0,APP_FOOTER_TEXT_COLOR:void 0,APP_HEADER_COLOR:void 0,APP_HEADER_ICON_URL:void 0,APP_HEADER_TEXT_COLOR:void 0,APP_ICON_URL:void 0,APP_LOG_CODICENT:"",APP_LOG_TOKEN:"",APP_LOGBOOK_TITLE:void 0,APP_MENU_TITLE:void 0,APP_NAME:void 0,APP_PREFIX:void 0,APP_SAVE_TITLE:void 0,APP_SEARCH_TITLE:void 0,APP_SLOGAN:void 0,APP_SPLASH_TEXT:void 0,APP_SPLASH_URL:void 0,APP_TEMPLATE:"",APP_TITLE:void 0,AUTH_REDIRECT_URL:void 0,AUTH0_AUDIENCE:"https://codicent.com/api",AUTH0_CLIENT_ID:"80STzWmmzN3Tgf76HgFRyv54keYmvnaw",AUTH0_DOMAIN:"auth.codicent.com",AUTH0_PROVIDER_SCOPE:"read:current_user update:current_user_metadata openid profile email",AUTH0_SCOPE:"read:current_user",AUTH0_USER_DOMAIN:void 0,BUTTON_ACTIVE_COLOR:void 0,BUTTON_BACKGROUND_COLOR:void 0,BUTTON_BORDER_RADIUS:void 0,BUTTON_HOVER_COLOR:void 0,BUTTON_TAG:"app-button",BUTTON_TEXT_COLOR:void 0,CHAT_BACKGROUND_IMAGE_URL:void 0,CHAT_BOT_BACKGROUND_COLOR:void 0,CHAT_BOT_TEXT_COLOR:void 0,CHAT_INSTRUCTIONS:void 0,CHAT_USER_BACKGROUND_COLOR:void 0,CHAT_USER_TEXT_COLOR:void 0,CHAT_WELCOME:"Welcome",COMPOSE_BACKGROUND_IMAGE_URL:void 0,COMPOSE_HIDE_LOCATION:void 0,COMPOSE_SIMPLE_ATTACH_FILE:void 0,DEFAULT_LANGUAGE:"en",HIDE_CHAT_BUTTON:!1,HIDE_MENU_BUTTON:!1,HIDE_REGISTER_BUTTON:!1,HIDE_SAVE_BUTTON:!1,HOME_BACKGROUND_IMAGE_URL:void 0,INDEX_TITLE:void 0,LOGBOOK_TAG_DEFINITIONS:{},LOGBOOK_TAGS:"[]",MENU_BACKGROUND_IMAGE_URL:void 0,MESSAGE_HIDE_BAR:!1,MODULE_VOICE:!1,PUBLIC_FLOW_CODICENT:void 0,REALTIME_VOICE_API_KEY:"",REALTIME_VOICE_MODEL:"alloy",USE_REALTIME_SESSION_ENDPOINT:!0,REALTIME_SESSION_ENDPOINT:"/realtime/session",REALTIME_CONFIG_ENDPOINT:"/realtime/config",SEND_BUTTON_ROUND_BACKGROUND:!1,SHOW_CANVAS_BUTTON:!1,SHOW_CHAT_PROMPTS:!1,SHOW_HELP_BUTTON:!1,SHOW_LOGBOOK_BUTTON:!1,SHOW_MICROPHONE_BUTTON:!1,SHOW_SETTINGS_BUTTON:!1,SHOW_SNAP_BUTTON:!1,SHOW_VOICE_BUTTON:!1,STRIP_CUSTOMER_PORTAL:"",STRIPE_PRICE_ID:"",STRIPE_PUBLIC_KEY:"",SUBSCRIPTION_NEEDED:!1,THEME_WELCOME:void 0,USER_PREFIX:void 0,WELCOME_STATUS_PROMPT:"",SHOW_SEND_BUTTON_TEXT:!1,SHOW_SAVE_BUTTON_TEXT:!1,FORM_BACKGROUND_IMAGE_URL:void 0,AUTO_TRANSLATE:!0,FORCE_LANGUAGE:void 0,TRANSLATIONS:void 0,LOGIN_WELCOME_TEXT:void 0,LOGIN_HIDE_WELCOME:!1,LOGIN_LOGO_URL:void 0,HIDE_CHAT_ADD_FILE_BUTTON:!1,FORM_ACCEPT_MARKDOWN:void 0,RESTART_AUDIO_ON_TAKE_PHOTO:!1};const E=function(_){return new Proxy(_,{get:(_,T,O)=>Reflect.get(_,T,O)})}(O);exports.AppConfig=T,exports.getConfigValue=function(_){return E[_]},exports.initCodicentApp=function(T={}){for(const[_,E]of Object.entries(T))void 0!==E&&(O[_]=E);void 0!==T.TRANSLATIONS&&(globalThis.__CODICENT_REINIT_I18N__=!0),_.default.initialize({startOnLoad:!1})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCodicentApp.d.ts","sourceRoot":"","sources":["../../../src/hooks/useCodicentApp.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAA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oBAAoB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,kBAAkB,EAAyB,MAAM,UAAU,CAAC;AACpG,OAAyB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAqB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAA2B,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAIzE,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,kBAAkB,CAAC;IAC1B,IAAI,EAAE,YAAY,CAAC;IACnB,YAAY,EAAE,eAAe,CAAC;IAC9B,OAAO,EAAE,eAAe,CAAC;IACzB,OAAO,EAAE,YAAY,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACvC,SAAS,EAAE,kBAAkB,CAAC;IAC9B,MAAM,EAAE,MAAM,OAAO,CAAC;IACtB,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,eAAO,MAAM,cAAc,cAAe;IAAE,KAAK,EAAE,qBAAqB,CAAA;CAAE,KAmKnE,gBACN,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime");var t=require("../utils/appState.js");require("../_virtual/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");var r=require("./useAudioRecorder.js"),s=require("./useAuthState.js"),n=require("./useRealtimeVoiceAI.js"),a=require("./useTools.js"),c=require("../config/index.js");exports.useCodicentApp=({auth0:u})=>{const i=s.default(u),o=e.useRef(t.createAppStateMachine(i.codicentService,(()=>{}))),[l,d]=e.useState(),{service:m,context:p}=o.current,{nickname:f,name:k,error:v,errorType:g,selectedApp:h}=p,A=e.useCallback(((e,t)=>{const r=e.get("file").name;m.uploadFile(r,e).then((e=>{m.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[m]),C=r.useAudioRecorder(A),[b,S]=e.useState(),[q,w]=e.useState(),[j,y]=e.useState(!1),x=e.useMemo((()=>new Audio("./notification.mp3")),[]),T=e.useCallback((()=>y(!0)),[]),_=a.default(m,S,w,x,b,T),I=e.useMemo((()=>c.getConfigValue("REALTIME_VOICE_API_KEY")||""),[]),E=n.default(I,_);e.useEffect((()=>{j&&(E?.disconnectConversation(),y(!1))}),[j,E]),e.useEffect((()=>{i.isAuthenticated&&i.user&&i.accessToken&&o.current.updateContext({isAuthenticated:i.isAuthenticated,user:{sub:i.user.sub,email:i.user.email},accessToken:i.accessToken})}),[i.isAuthenticated,i.user,i.accessToken]),e.useEffect((()=>o.current.updateContext({nickname:i.nickname})),[i.nickname]),e.useEffect((()=>{o.current.update();let e,t=o.current.getCurrentStateName();d(o.current.getCurrentStateName()),JSON.stringify(o.current.context);let r=!1;const s=n=>setInterval((()=>{const n=o.current.getCurrentStateName();if("hasAccess"===n&&!r)return console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),r=!0,clearInterval(e),void(e=s(1e3));if("hasAccess"!==n&&r)return console.log("🚨 Left stable state - switching to fast polling (200ms)"),r=!1,clearInterval(e),void(e=s(200));const a=JSON.stringify(o.current.context);o.current.update();const c=JSON.stringify(o.current.context),u=o.current.getCurrentStateName();u===t&&a===c||(d(u),t=u)}),n);return e=s(200),()=>clearInterval(e)}),[]);const M=e.useCallback((e=>e.replace("{nickname}",f||"unknown").replace("{token}",encodeURIComponent(i.accessToken||"unknown")).replace("{app}",h||"unknown")),[f,i.accessToken,h]),N=e.useCallback((e=>{o.current.updateContext({isAnonymous:e})}),[]),R=e.useCallback((()=>o.current.isBusy()),[]);return e.useMemo((()=>({audio:C,auth:i,currentStateName:l,stateMachine:o.current,service:m,context:p,state:l,nickname:f,name:k,error:v,errorType:g,fixAppUrl:M,setAnonymous:N,allStates:o.current.allStates,isBusy:R,voice:E,html:b,setHtml:S,script:q})),[l,f,k,v,g,b,q,i.isAuthenticated,i.isLoading,C.isRecording,E?.isConnected,M,N,R])};
|
|
1
|
+
"use strict";var e=require("react");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime");var t=require("../utils/appState.js");require("../_virtual/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");var r=require("./useAudioRecorder.js"),s=require("./useAuthState.js"),n=require("./useRealtimeVoiceAI.js"),a=require("./useTools.js"),c=require("../config/index.js");exports.useCodicentApp=({auth0:u})=>{const i=s.default(u),o=e.useRef(t.createAppStateMachine(i.codicentService,(()=>{}))),[l,d]=e.useState(),{service:m,context:p}=o.current,{nickname:f,name:k,error:v,errorType:g,selectedApp:h}=p,A=e.useCallback(((e,t)=>{const r=e.get("file").name;m.uploadFile(r,e).then((e=>{m.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[m]),C=r.useAudioRecorder(A),[b,S]=e.useState(),[q,w]=e.useState(),[j,y]=e.useState(!1),x=e.useMemo((()=>new Audio("./notification.mp3")),[]),T=e.useCallback((()=>y(!0)),[]),_=a.default(m,S,w,x,b,T),I=e.useMemo((()=>c.getConfigValue("REALTIME_VOICE_API_KEY")||""),[]),E=n.default(m,I,_);e.useEffect((()=>{j&&(E?.disconnectConversation(),y(!1))}),[j,E]),e.useEffect((()=>{i.isAuthenticated&&i.user&&i.accessToken&&o.current.updateContext({isAuthenticated:i.isAuthenticated,user:{sub:i.user.sub,email:i.user.email},accessToken:i.accessToken})}),[i.isAuthenticated,i.user,i.accessToken]),e.useEffect((()=>o.current.updateContext({nickname:i.nickname})),[i.nickname]),e.useEffect((()=>{o.current.update();let e,t=o.current.getCurrentStateName();d(o.current.getCurrentStateName()),JSON.stringify(o.current.context);let r=!1;const s=n=>setInterval((()=>{const n=o.current.getCurrentStateName();if("hasAccess"===n&&!r)return console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),r=!0,clearInterval(e),void(e=s(1e3));if("hasAccess"!==n&&r)return console.log("🚨 Left stable state - switching to fast polling (200ms)"),r=!1,clearInterval(e),void(e=s(200));const a=JSON.stringify(o.current.context);o.current.update();const c=JSON.stringify(o.current.context),u=o.current.getCurrentStateName();u===t&&a===c||(d(u),t=u)}),n);return e=s(200),()=>clearInterval(e)}),[]);const M=e.useCallback((e=>e.replace("{nickname}",f||"unknown").replace("{token}",encodeURIComponent(i.accessToken||"unknown")).replace("{app}",h||"unknown")),[f,i.accessToken,h]),N=e.useCallback((e=>{o.current.updateContext({isAnonymous:e})}),[]),R=e.useCallback((()=>o.current.isBusy()),[]);return e.useMemo((()=>({audio:C,auth:i,currentStateName:l,stateMachine:o.current,service:m,context:p,state:l,nickname:f,name:k,error:v,errorType:g,fixAppUrl:M,setAnonymous:N,allStates:o.current.allStates,isBusy:R,voice:E,html:b,setHtml:S,script:q})),[l,f,k,v,g,b,q,i.isAuthenticated,i.isLoading,C.isRecording,E?.isConnected,M,N,R])};
|
|
@@ -1,4 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ToolDefinitionType } from "@openai/realtime-api-beta/dist/lib/client";
|
|
2
|
+
import { CodicentService } from "../services";
|
|
3
|
+
/**
|
|
4
|
+
* Type for conversation items
|
|
5
|
+
*/
|
|
6
|
+
export interface ItemType {
|
|
7
|
+
id: string;
|
|
8
|
+
type: string;
|
|
9
|
+
status?: string;
|
|
10
|
+
role?: string;
|
|
11
|
+
content?: any[];
|
|
12
|
+
formatted?: {
|
|
13
|
+
audio?: Int16Array;
|
|
14
|
+
text?: string;
|
|
15
|
+
transcript?: string;
|
|
16
|
+
file?: any;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
2
19
|
/**
|
|
3
20
|
* Type for all event logs
|
|
4
21
|
*/
|
|
@@ -32,9 +49,9 @@ export interface RealtimeVoice {
|
|
|
32
49
|
updateInstructions: (instructions: string) => void;
|
|
33
50
|
setLanguage: (language: string) => void;
|
|
34
51
|
}
|
|
35
|
-
declare const useRealtimeVoiceAI: (apiKey: string, tools: {
|
|
52
|
+
declare const useRealtimeVoiceAI: (codicentService: CodicentService, apiKey: string, tools: {
|
|
36
53
|
definition: ToolDefinitionType;
|
|
37
54
|
handler: Function;
|
|
38
|
-
}[]) => RealtimeVoice | undefined;
|
|
55
|
+
}[], voice?: string) => RealtimeVoice | undefined;
|
|
39
56
|
export default useRealtimeVoiceAI;
|
|
40
57
|
//# sourceMappingURL=useRealtimeVoiceAI.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRealtimeVoiceAI.d.ts","sourceRoot":"","sources":["../../../src/hooks/useRealtimeVoiceAI.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useRealtimeVoiceAI.d.ts","sourceRoot":"","sources":["../../../src/hooks/useRealtimeVoiceAI.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAK/E,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,C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IAAI,CAAC,CAAC;IACtD,cAAc,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACpC,aAAa,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,iBAAiB,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpD,gBAAgB,EAAE,MAAM,MAAM,CAAC;IAC/B,cAAc,EAAE,MAAM,MAAM,CAAC;IAC7B,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IACxC,kBAAkB,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,CAAC;IACnD,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC;AAED,QAAA,MAAM,kBAAkB,oBACL,eAAe,UACxB,MAAM,SACP;IAAE,UAAU,EAAE,kBAAkB,CAAC;IAAC,OAAO,EAAE,QAAQ,CAAA;CAAE,EAAE,UACtD,MAAM,KACb,aAAa,GAAG,SA2iBlB,CAAC;AAEF,eAAe,kBAAkB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("../utils/wav_renderer.js");require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js");var n=require("../lib/wavtools/lib/wav_stream_player.js"),r=require("../lib/wavtools/lib/wav_recorder.js"),a=require("../config/index.js");exports.default=(s,o,i,c)=>{const u=!!a.getConfigValue("APP_CONFIG"),l=!!a.getConfigValue("APP_BUTTONS");u||console.warn("APP_CONFIG is not set. Voice AI will not be available."),l||console.warn("APP_BUTTONS is not set. Voice AI will not be available.");const d=a.getConfigValue("APP_CONFIG"),p=a.getConfigValue("APP_BUTTONS");a.getConfigValue("API_BASE_URL").replace(/\/$/,""),a.getConfigValue("USE_REALTIME_SESSION_ENDPOINT"),a.getConfigValue("REALTIME_SESSION_ENDPOINT");const f=c||a.getConfigValue("REALTIME_VOICE_MODEL")||"alloy",g=["alloy","shimmer","echo"],m=g.includes(f)?f:"alloy";f!==m&&console.warn(`[codicent-app-sdk] Voice "${f}" is not supported in the current SDK version. Supported voices: ${g.join(", ")}. Falling back to "${m}".`);const w=e.useRef(new r.WavRecorder({sampleRate:24e3})),S=e.useRef(new n.WavStreamPlayer({sampleRate:24e3})),v=e.useRef(null),y=e.useRef(null),h=e.useRef(null),_=e.useRef(null),C=e.useRef(!1),R=e.useRef(null),O=e.useRef(null),I=e.useRef(null),T=e.useRef((new Date).toISOString()),[E,b]=e.useState([]),[N,P]=e.useState([]),[k,A]=e.useState(!1),[D,M]=e.useState(!1),[V,x]=e.useState(!1),F=e.useRef(0),L=e.useRef(0),[$,j]=e.useState(""),[q,U]=e.useState("en-US"),[J,B]=e.useState((()=>u&&l&&p&&d&&d.apps&&d.apps[p]?d.apps[p].voiceInstructions||d.REALTIME_VOICE_INSTRUCTIONS||"":d&&d.REALTIME_VOICE_INSTRUCTIONS||"")),W=e.useCallback((e=>{const t=T.current,n=new Date(t).valueOf(),r=new Date(e).valueOf()-n,a=Math.floor(r/10)%100,s=Math.floor(r/1e3)%60,o=e=>{let t=e+"";for(;t.length<2;)t="0"+t;return t};return`${o(Math.floor(r/6e4)%60)}:${o(s)}.${o(a)}`}),[]),G=e.useCallback((async()=>{try{T.current=(new Date).toISOString(),A(!0),P([]),b([]);const e=await s.getRealtimeSessionToken(m);if(!e)throw new Error("No ephemeral key returned from session endpoint");const t=new RTCPeerConnection;v.current=t,h.current||(h.current=new Audio,h.current.autoplay=!0),t.ontrack=e=>{h.current&&e.streams[0]&&(h.current.srcObject=e.streams[0])};const n=await navigator.mediaDevices.getUserMedia({audio:!0});_.current=n;const r=n.getTracks()[0];t.addTrack(r,n);const o=t.createDataChannel("oai-events");y.current=o,o.addEventListener("message",(e=>{try{const t=JSON.parse(e.data);"session.created"===t.type||("conversation.item.created"===t.type?b((e=>[...e,t.item])):"conversation.item.input_audio_transcription.completed"===t.type?b((e=>{const n=[...e],r=n.findIndex((e=>e.id===t.item_id));return-1!==r&&n[r].formatted&&(n[r].formatted.transcript=t.transcript),n})):"response.audio_transcript.delta"===t.type||"response.audio_transcript.done"===t.type||"error"===t.type&&console.error("Server error:",t.error))}catch(t){console.warn("Invalid message:",e.data)}})),o.onopen=()=>{console.log("Data channel opened, configuring session"),o.send(JSON.stringify({type:"session.update",session:{instructions:J.replace("{{name}}",$).replace("{{language}}",q).replace("{{time}}",(new Date).toISOString()),modalities:["text","audio"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:500},voice:m,temperature:.8,max_response_output_tokens:4096,input_audio_format:"pcm16",output_audio_format:"pcm16",tools:i.map((e=>({type:"function",...e.definition})))}}))},o.onclose=()=>{console.log("Data channel closed")};const c=await t.createOffer();await t.setLocalDescription(c);let u="gpt-4o-realtime-preview";try{if(a.getConfigValue("REALTIME_CONFIG_ENDPOINT")){const e=await s.getRealtimeConfig();e&&e.model&&(u=e.model)}}catch(e){console.warn("Failed to fetch realtime config, using default model:",e)}const l="https://api.openai.com/v1/realtime",d=await fetch(`${l}?model=${u}`,{method:"POST",body:c.sdp,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/sdp"}});if(!d.ok)throw new Error(`Failed to get SDP answer: ${d.statusText}`);const p={type:"answer",sdp:await d.text()};await t.setRemoteDescription(p),M(!1);const f=w.current,g=S.current;await f.begin(),await g.connect()}catch(e){throw console.error("[codicent-app-sdk] Failed to establish WebRTC connection:",e),A(!1),e}}),[s,m,J,$,q,i]),H=e.useCallback((async()=>{A(!1),P([]),b([]),y.current&&(y.current.close(),y.current=null),v.current&&(v.current.close(),v.current=null),_.current&&(_.current.getTracks().forEach((e=>e.stop())),_.current=null),h.current&&(h.current.pause(),h.current.srcObject=null);const e=w.current;await e.end();const t=S.current;await t.interrupt()}),[]),z=e.useCallback((async e=>{const t=y.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"conversation.item.delete",item_id:e}))}),[]),K=e.useCallback((async()=>{x(!0);const e=y.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"input_audio_buffer.commit"}))}),[]),Q=e.useCallback((async()=>{x(!1);const e=y.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"response.create"}))}),[]),X=e.useCallback((async e=>{const t=y.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"session.update",session:{turn_detection:"none"===e?null:{type:"server_vad"}}})),M("none"===e)}),[]);e.useEffect((()=>{if($&&k){const e=y.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"session.update",session:{instructions:J.replace("{{name}}",$).replace("{{language}}",q).replace("{{time}}",(new Date).toISOString())}}))}}),[J,$,q,k]),e.useEffect((()=>{let e=!0;const n=w.current,r=R.current;let a=null;const s=S.current,o=O.current;let i=null;const c=()=>{if(e){if(r&&(r.width&&r.height||(r.width=r.offsetWidth,r.height=r.offsetHeight),a=a||r.getContext("2d"),a)){a.clearRect(0,0,r.width,r.height);const e=n.recording?n.getFrequencies("voice"):{values:new Float32Array([0])},s=1-Math.max(...e.values);F.current=s,t.WavRenderer.drawCircularBars(r,a,e.values,"#0099ff",20,0,8)}if(o&&(o.width&&o.height||(o.width=o.offsetWidth,o.height=o.offsetHeight),i=i||o.getContext("2d"),i)){i.clearRect(0,0,o.width,o.height);const e=s.analyser?s.getFrequencies("voice"):{values:new Float32Array([0])},n=1-Math.max(...e.values);L.current=n,t.WavRenderer.drawCircularBars(o,i,e.values,"#009900",20,0,8)}window.requestAnimationFrame(c)}};return c(),()=>{e=!1}}),[]),e.useEffect((()=>{!C.current&&i&&J&&(C.current=!0)}),[i,J]);const Y=e.useCallback((e=>{const t=e.replace("{{name}}",$).replace("{{language}}",q).replace("{{time}}",(new Date).toISOString()),n=y.current;n&&"open"===n.readyState&&n.send(JSON.stringify({type:"session.update",session:{instructions:t}})),B(e)}),[$,q]);return e.useMemo((()=>{if(u&&l)return{items:E,realtimeEvents:N,isConnected:k,canPushToTalk:D,isRecording:V,clientCanvasRef:R,serverCanvasRef:O,eventsScrollRef:I,formatTime:W,connectConversation:G,disconnectConversation:H,deleteConversationItem:z,startRecording:K,stopRecording:Q,changeTurnEndType:X,getRecorderLevel:()=>F.current,getStreamLevel:()=>L.current,setUsername:j,updateInstructions:Y,setLanguage:U}}),[u,l,E,N,k,D,V,R,O,I])};
|
|
@@ -128,5 +128,9 @@ export declare class CodicentService {
|
|
|
128
128
|
private handleUnauthorized;
|
|
129
129
|
getTodoStatus: (messageId: string) => Promise<"done" | "undone" | "unknown">;
|
|
130
130
|
updateTodoStatus: (messageId: string, status: "done" | "undone") => Promise<boolean>;
|
|
131
|
+
getRealtimeSessionToken(voice?: string): Promise<string>;
|
|
132
|
+
getRealtimeConfig(): Promise<{
|
|
133
|
+
model: string;
|
|
134
|
+
} | null>;
|
|
131
135
|
}
|
|
132
136
|
//# sourceMappingURL=codicent.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAmCA,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACvC,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CA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AI,CAAC;CAmB7D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let a="https://codicent.com/",n="-";const s=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let i=s();if(!i){const t=setInterval((()=>{i=s(),i&&clearInterval(t)}),100)}class r{constructor(t){this.createDataMessage=async(t,e)=>await window.Codicent.data.create({codicent:this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e)=>await window.Codicent.data.read({codicent:this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e)=>await window.Codicent.data.update({id:t,data:e,codicent:this.codicent}),this.deleteDataMessage=async t=>await window.Codicent.data.delete({id:t,codicent:this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new o.default(t.content).content.split("\n"),a=e[0],n=e.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e)=>window.Codicent.postMessage({message:`@${this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e)=>window.Codicent.getChatReply3({message:t,codicent:this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0)=>{const s=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:this.codicent,search:e,length:o})});let i=await s.json();if(i.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);i=i.concat(t),i.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return i},this.getMessages=async(t,e)=>{let o=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:10});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{o=o.concat(t)})),e)try{const t=await this.getPublicFlow(e);o=o.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return o=o.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),o.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),o},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({priceId:t,successUrl:window.location.href,cancelUrl:window.location.href})});if(!e.ok)throw new Error("Failed to create checkout session");const{id:o}=await e.json();return o},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(t),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}}t=r,r.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,r.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,r.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const o=window.URL.createObjectURL(t),a=document.createElement("a");a.style.display="none",a.href=o,a.download=e.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},r.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},r.getMiniChatReply=async(t,e="codicent-mini",o,a=3e5,s=2e3)=>{const i={project:e,message:t};let r;o&&(i.messageId=o);try{const t="https://dev.codicent.com/",e=await fetch(`${t}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(i)});if(!e.ok)return e.status,void console.error(`Failed to start AI chat: ${e.status}`);if(r=(await e.json()).promptMessageId,!r)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const c=Date.now();for(;Date.now()-c<a;)try{const t="https://dev.codicent.com/",o=await fetch(`${t}app/GetAi2ChatReplyStatus?promptMessageId=${r}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===o.status){await new Promise((t=>setTimeout(t,s)));continue}if(!o.ok)return void console.error(`Error polling AI chat status: ${o.status}`);const a=await o.json();return a.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},exports.CodicentService=r;
|
|
1
|
+
"use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let a="https://codicent.com/",n="-";const s=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let i=s();if(!i){const t=setInterval((()=>{i=s(),i&&clearInterval(t)}),100)}class r{constructor(t){this.createDataMessage=async(t,e)=>await window.Codicent.data.create({codicent:this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e)=>await window.Codicent.data.read({codicent:this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e)=>await window.Codicent.data.update({id:t,data:e,codicent:this.codicent}),this.deleteDataMessage=async t=>await window.Codicent.data.delete({id:t,codicent:this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new o.default(t.content).content.split("\n"),a=e[0],n=e.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e)=>window.Codicent.postMessage({message:`@${this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e)=>window.Codicent.getChatReply4({message:t,codicent:this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0)=>{const s=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:this.codicent,search:e,length:o})});let i=await s.json();if(i.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);i=i.concat(t),i.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return i},this.getMessages=async(t,e)=>{let o=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:10});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{o=o.concat(t)})),e)try{const t=await this.getPublicFlow(e);o=o.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return o=o.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),o.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),o},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({priceId:t,successUrl:window.location.href,cancelUrl:window.location.href})});if(!e.ok)throw new Error("Failed to create checkout session");const{id:o}=await e.json();return o},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(t),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy"){const e=`${a}realtime/session?voice=${t}`,o=await fetch(e,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!o.ok)throw new Error(`Failed to fetch session token: ${o.statusText}`);const n=await o.json(),s=n.client_secret?.value;if(!s)throw new Error("No ephemeral key returned from session endpoint");return s}async getRealtimeConfig(){try{const t=`${a}realtime/config`,e=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return e.ok?await e.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}t=r,r.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,r.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,r.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const o=window.URL.createObjectURL(t),a=document.createElement("a");a.style.display="none",a.href=o,a.download=e.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},r.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},r.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},exports.CodicentService=r;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),r=require("react"),n=require("../node_modules/nosleep.js/src/index.js");exports.default=function(t){return function(a){const[o,c]=r.useState(null),[s]=r.useState((()=>new n.default));return r.useEffect((()=>{!async function(){if("wakeLock"in navigator)try{const e=await navigator.wakeLock.request("screen");c(e)}catch(e){console.warn(`Error acquiring wake lock API: ${e}`);try{s.enable()}catch(e){console.error(`Error enabling NoSleep.js: ${e}`)}}else try{s.enable()}catch(e){console.warn(`Error enabling NoSleep.js: ${e}`)}}()}),[]),r.useEffect((()=>()=>{o&&o.release().then((()=>{})).catch((e=>{console.warn("Error releasing wake lock:",e)}));try{s.disable()}catch(e){console.warn("Error disabling NoSleep.js:",e)}}),[o,s]),e.jsx(t,{...a})}};
|
|
@@ -93,6 +93,10 @@ export interface AppConfigOptions {
|
|
|
93
93
|
MODULE_VOICE: boolean;
|
|
94
94
|
PUBLIC_FLOW_CODICENT: undefined | string;
|
|
95
95
|
REALTIME_VOICE_API_KEY: string;
|
|
96
|
+
REALTIME_VOICE_MODEL: string;
|
|
97
|
+
USE_REALTIME_SESSION_ENDPOINT: boolean;
|
|
98
|
+
REALTIME_SESSION_ENDPOINT: string;
|
|
99
|
+
REALTIME_CONFIG_ENDPOINT: string;
|
|
96
100
|
SEND_BUTTON_ROUND_BACKGROUND: boolean;
|
|
97
101
|
SHOW_CANVAS_BUTTON: boolean;
|
|
98
102
|
SHOW_CHAT_PROMPTS: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/config/index.ts"],"names":[],"mappings":"AAGA,qBAAa,SAAS;;IAKpB,iBAAiB,EAAE,MAAM,CAAM;IAC/B,2BAA2B,EAAE,MAAM,CAAM;IACzC,IAAI,EAAE;QACJ,CAAC,GAAG,EAAE,MAAM,GAAG;YACb,OAAO,EAAE;gBAAE,KAAK,EAAE,MAAM,CAAC;gBAAC,GAAG,EAAE,MAAM,CAAA;aAAE,EAAE,CAAC;YAC1C,KAAK,EAAE;gBAAE,EAAE,EAAE,MAAM,CAAC;gBAAC,KAAK,EAAE,MAAM,CAAC;gBAAC,OAAO,EAAE,MAAM,CAAA;aAAE,EAAE,CAAC;YACxD,iBAAiB,EAAE,MAAM,CAAC;YAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;YACvB,gBAAgB,EAAE,MAAM,CAAC;YACzB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;SACtB,CAAC;KACH,CAAC;CAyBH;AAED,MAAM,WAAW,gBAAgB;IAC/B,cAAc,EAAE,OAAO,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,kBAAkB,EA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AED;;GAEG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,OAAO,CAAC,gBAAgB,CAAM,QAgBtE"}
|
package/dist/esm/config/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import _ from"../node_modules/mermaid/dist/mermaid.core.js";class T{constructor(){this.CHAT_INSTRUCTIONS="",this.REALTIME_VOICE_INSTRUCTIONS="",this.apps={}}}const O={LOGIN_REDIRECT:!1,ABOUT_TEXT:"Codicent APP SDK",ANONYMOUS_CODICENT:void 0,ANONYMOUS_TOKEN:void 0,API_BASE_URL:"https://codicent.com/",APP_BUTTONS:void 0,APP_CHAT_TEXT_PLACEHOLDER:void 0,APP_CHAT_TITLE:void 0,APP_CONFIG:new T,APP_FOOTER_COLOR:void 0,APP_FOOTER_SELECTED_COLOR:void 0,APP_FOOTER_TEXT_COLOR:void 0,APP_HEADER_COLOR:void 0,APP_HEADER_ICON_URL:void 0,APP_HEADER_TEXT_COLOR:void 0,APP_ICON_URL:void 0,APP_LOG_CODICENT:"",APP_LOG_TOKEN:"",APP_LOGBOOK_TITLE:void 0,APP_MENU_TITLE:void 0,APP_NAME:void 0,APP_PREFIX:void 0,APP_SAVE_TITLE:void 0,APP_SEARCH_TITLE:void 0,APP_SLOGAN:void 0,APP_SPLASH_TEXT:void 0,APP_SPLASH_URL:void 0,APP_TEMPLATE:"",APP_TITLE:void 0,AUTH_REDIRECT_URL:void 0,AUTH0_AUDIENCE:"https://codicent.com/api",AUTH0_CLIENT_ID:"80STzWmmzN3Tgf76HgFRyv54keYmvnaw",AUTH0_DOMAIN:"auth.codicent.com",AUTH0_PROVIDER_SCOPE:"read:current_user update:current_user_metadata openid profile email",AUTH0_SCOPE:"read:current_user",AUTH0_USER_DOMAIN:void 0,BUTTON_ACTIVE_COLOR:void 0,BUTTON_BACKGROUND_COLOR:void 0,BUTTON_BORDER_RADIUS:void 0,BUTTON_HOVER_COLOR:void 0,BUTTON_TAG:"app-button",BUTTON_TEXT_COLOR:void 0,CHAT_BACKGROUND_IMAGE_URL:void 0,CHAT_BOT_BACKGROUND_COLOR:void 0,CHAT_BOT_TEXT_COLOR:void 0,CHAT_INSTRUCTIONS:void 0,CHAT_USER_BACKGROUND_COLOR:void 0,CHAT_USER_TEXT_COLOR:void 0,CHAT_WELCOME:"Welcome",COMPOSE_BACKGROUND_IMAGE_URL:void 0,COMPOSE_HIDE_LOCATION:void 0,COMPOSE_SIMPLE_ATTACH_FILE:void 0,DEFAULT_LANGUAGE:"en",HIDE_CHAT_BUTTON:!1,HIDE_MENU_BUTTON:!1,HIDE_REGISTER_BUTTON:!1,HIDE_SAVE_BUTTON:!1,HOME_BACKGROUND_IMAGE_URL:void 0,INDEX_TITLE:void 0,LOGBOOK_TAG_DEFINITIONS:{},LOGBOOK_TAGS:"[]",MENU_BACKGROUND_IMAGE_URL:void 0,MESSAGE_HIDE_BAR:!1,MODULE_VOICE:!1,PUBLIC_FLOW_CODICENT:void 0,REALTIME_VOICE_API_KEY:"",SEND_BUTTON_ROUND_BACKGROUND:!1,SHOW_CANVAS_BUTTON:!1,SHOW_CHAT_PROMPTS:!1,SHOW_HELP_BUTTON:!1,SHOW_LOGBOOK_BUTTON:!1,SHOW_MICROPHONE_BUTTON:!1,SHOW_SETTINGS_BUTTON:!1,SHOW_SNAP_BUTTON:!1,SHOW_VOICE_BUTTON:!1,STRIP_CUSTOMER_PORTAL:"",STRIPE_PRICE_ID:"",STRIPE_PUBLIC_KEY:"",SUBSCRIPTION_NEEDED:!1,THEME_WELCOME:void 0,USER_PREFIX:void 0,WELCOME_STATUS_PROMPT:"",SHOW_SEND_BUTTON_TEXT:!1,SHOW_SAVE_BUTTON_TEXT:!1,FORM_BACKGROUND_IMAGE_URL:void 0,AUTO_TRANSLATE:!0,FORCE_LANGUAGE:void 0,TRANSLATIONS:void 0,LOGIN_WELCOME_TEXT:void 0,LOGIN_HIDE_WELCOME:!1,LOGIN_LOGO_URL:void 0,HIDE_CHAT_ADD_FILE_BUTTON:!1,FORM_ACCEPT_MARKDOWN:void 0,RESTART_AUDIO_ON_TAKE_PHOTO:!1};const E=function(_){return new Proxy(_,{get:(_,T,O)=>Reflect.get(_,T,O)})}(O);function A(_){return E[_]}function N(T={}){for(const[_,E]of Object.entries(T))void 0!==E&&(O[_]=E);void 0!==T.TRANSLATIONS&&(globalThis.__CODICENT_REINIT_I18N__=!0),_.initialize({startOnLoad:!1})}export{T as AppConfig,A as getConfigValue,N as initCodicentApp};
|
|
1
|
+
import _ from"../node_modules/mermaid/dist/mermaid.core.js";class T{constructor(){this.CHAT_INSTRUCTIONS="",this.REALTIME_VOICE_INSTRUCTIONS="",this.apps={}}}const O={LOGIN_REDIRECT:!1,ABOUT_TEXT:"Codicent APP SDK",ANONYMOUS_CODICENT:void 0,ANONYMOUS_TOKEN:void 0,API_BASE_URL:"https://codicent.com/",APP_BUTTONS:void 0,APP_CHAT_TEXT_PLACEHOLDER:void 0,APP_CHAT_TITLE:void 0,APP_CONFIG:new T,APP_FOOTER_COLOR:void 0,APP_FOOTER_SELECTED_COLOR:void 0,APP_FOOTER_TEXT_COLOR:void 0,APP_HEADER_COLOR:void 0,APP_HEADER_ICON_URL:void 0,APP_HEADER_TEXT_COLOR:void 0,APP_ICON_URL:void 0,APP_LOG_CODICENT:"",APP_LOG_TOKEN:"",APP_LOGBOOK_TITLE:void 0,APP_MENU_TITLE:void 0,APP_NAME:void 0,APP_PREFIX:void 0,APP_SAVE_TITLE:void 0,APP_SEARCH_TITLE:void 0,APP_SLOGAN:void 0,APP_SPLASH_TEXT:void 0,APP_SPLASH_URL:void 0,APP_TEMPLATE:"",APP_TITLE:void 0,AUTH_REDIRECT_URL:void 0,AUTH0_AUDIENCE:"https://codicent.com/api",AUTH0_CLIENT_ID:"80STzWmmzN3Tgf76HgFRyv54keYmvnaw",AUTH0_DOMAIN:"auth.codicent.com",AUTH0_PROVIDER_SCOPE:"read:current_user update:current_user_metadata openid profile email",AUTH0_SCOPE:"read:current_user",AUTH0_USER_DOMAIN:void 0,BUTTON_ACTIVE_COLOR:void 0,BUTTON_BACKGROUND_COLOR:void 0,BUTTON_BORDER_RADIUS:void 0,BUTTON_HOVER_COLOR:void 0,BUTTON_TAG:"app-button",BUTTON_TEXT_COLOR:void 0,CHAT_BACKGROUND_IMAGE_URL:void 0,CHAT_BOT_BACKGROUND_COLOR:void 0,CHAT_BOT_TEXT_COLOR:void 0,CHAT_INSTRUCTIONS:void 0,CHAT_USER_BACKGROUND_COLOR:void 0,CHAT_USER_TEXT_COLOR:void 0,CHAT_WELCOME:"Welcome",COMPOSE_BACKGROUND_IMAGE_URL:void 0,COMPOSE_HIDE_LOCATION:void 0,COMPOSE_SIMPLE_ATTACH_FILE:void 0,DEFAULT_LANGUAGE:"en",HIDE_CHAT_BUTTON:!1,HIDE_MENU_BUTTON:!1,HIDE_REGISTER_BUTTON:!1,HIDE_SAVE_BUTTON:!1,HOME_BACKGROUND_IMAGE_URL:void 0,INDEX_TITLE:void 0,LOGBOOK_TAG_DEFINITIONS:{},LOGBOOK_TAGS:"[]",MENU_BACKGROUND_IMAGE_URL:void 0,MESSAGE_HIDE_BAR:!1,MODULE_VOICE:!1,PUBLIC_FLOW_CODICENT:void 0,REALTIME_VOICE_API_KEY:"",REALTIME_VOICE_MODEL:"alloy",USE_REALTIME_SESSION_ENDPOINT:!0,REALTIME_SESSION_ENDPOINT:"/realtime/session",REALTIME_CONFIG_ENDPOINT:"/realtime/config",SEND_BUTTON_ROUND_BACKGROUND:!1,SHOW_CANVAS_BUTTON:!1,SHOW_CHAT_PROMPTS:!1,SHOW_HELP_BUTTON:!1,SHOW_LOGBOOK_BUTTON:!1,SHOW_MICROPHONE_BUTTON:!1,SHOW_SETTINGS_BUTTON:!1,SHOW_SNAP_BUTTON:!1,SHOW_VOICE_BUTTON:!1,STRIP_CUSTOMER_PORTAL:"",STRIPE_PRICE_ID:"",STRIPE_PUBLIC_KEY:"",SUBSCRIPTION_NEEDED:!1,THEME_WELCOME:void 0,USER_PREFIX:void 0,WELCOME_STATUS_PROMPT:"",SHOW_SEND_BUTTON_TEXT:!1,SHOW_SAVE_BUTTON_TEXT:!1,FORM_BACKGROUND_IMAGE_URL:void 0,AUTO_TRANSLATE:!0,FORCE_LANGUAGE:void 0,TRANSLATIONS:void 0,LOGIN_WELCOME_TEXT:void 0,LOGIN_HIDE_WELCOME:!1,LOGIN_LOGO_URL:void 0,HIDE_CHAT_ADD_FILE_BUTTON:!1,FORM_ACCEPT_MARKDOWN:void 0,RESTART_AUDIO_ON_TAKE_PHOTO:!1};const E=function(_){return new Proxy(_,{get:(_,T,O)=>Reflect.get(_,T,O)})}(O);function A(_){return E[_]}function N(T={}){for(const[_,E]of Object.entries(T))void 0!==E&&(O[_]=E);void 0!==T.TRANSLATIONS&&(globalThis.__CODICENT_REINIT_I18N__=!0),_.initialize({startOnLoad:!1})}export{T as AppConfig,A as getConfigValue,N as initCodicentApp};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCodicentApp.d.ts","sourceRoot":"","sources":["../../../src/hooks/useCodicentApp.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,kBAAkB,EAAyB,MAAM,UAAU,CAAC;AACpG,OAAyB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAqB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAA2B,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAIzE,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,kBAAkB,CAAC;IAC1B,IAAI,EAAE,YAAY,CAAC;IACnB,YAAY,EAAE,eAAe,CAAC;IAC9B,OAAO,EAAE,eAAe,CAAC;IACzB,OAAO,EAAE,YAAY,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,QA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E,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACvC,SAAS,EAAE,kBAAkB,CAAC;IAC9B,MAAM,EAAE,MAAM,OAAO,CAAC;IACtB,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,eAAO,MAAM,cAAc,cAAe;IAAE,KAAK,EAAE,qBAAqB,CAAA;CAAE,KAmKnE,gBACN,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useRef as e,useState as t,useCallback as r,useMemo as n,useEffect as s}from"react";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import{createAppStateMachine as o}from"../utils/appState.js";import"../_virtual/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import{useAudioRecorder as i}from"./useAudioRecorder.js";import a from"./useAuthState.js";import c from"./useRealtimeVoiceAI.js";import u from"./useTools.js";import{getConfigValue as l}from"../config/index.js";const m=({auth0:m})=>{const p=a(m),d=e(o(p.codicentService,(()=>{}))),[f,g]=t(),{service:h,context:v}=d.current,{nickname:k,name:A,error:w,errorType:j,selectedApp:y}=v,b=r(((e,t)=>{const r=e.get("file").name;h.uploadFile(r,e).then((e=>{h.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[h]),x=i(b),[S,C]=t(),[T,_]=t(),[I,N]=t(!1),R=n((()=>new Audio("./notification.mp3")),[]),E=r((()=>N(!0)),[]),M=u(h,C,_,R,S,E),O=n((()=>l("REALTIME_VOICE_API_KEY")||""),[]),J=c(O,M);s((()=>{I&&(J?.disconnectConversation(),N(!1))}),[I,J]),s((()=>{p.isAuthenticated&&p.user&&p.accessToken&&d.current.updateContext({isAuthenticated:p.isAuthenticated,user:{sub:p.user.sub,email:p.user.email},accessToken:p.accessToken})}),[p.isAuthenticated,p.user,p.accessToken]),s((()=>d.current.updateContext({nickname:p.nickname})),[p.nickname]),s((()=>{d.current.update();let e,t=d.current.getCurrentStateName();g(d.current.getCurrentStateName()),JSON.stringify(d.current.context);let r=!1;const n=s=>setInterval((()=>{const s=d.current.getCurrentStateName();if("hasAccess"===s&&!r)return console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),r=!0,clearInterval(e),void(e=n(1e3));if("hasAccess"!==s&&r)return console.log("🚨 Left stable state - switching to fast polling (200ms)"),r=!1,clearInterval(e),void(e=n(200));const o=JSON.stringify(d.current.context);d.current.update();const i=JSON.stringify(d.current.context),a=d.current.getCurrentStateName();a===t&&o===i||(g(a),t=a)}),s);return e=n(200),()=>clearInterval(e)}),[]);const L=r((e=>e.replace("{nickname}",k||"unknown").replace("{token}",encodeURIComponent(p.accessToken||"unknown")).replace("{app}",y||"unknown")),[k,p.accessToken,y]),B=r((e=>{d.current.updateContext({isAnonymous:e})}),[]),U=r((()=>d.current.isBusy()),[]);return n((()=>({audio:x,auth:p,currentStateName:f,stateMachine:d.current,service:h,context:v,state:f,nickname:k,name:A,error:w,errorType:j,fixAppUrl:L,setAnonymous:B,allStates:d.current.allStates,isBusy:U,voice:J,html:S,setHtml:C,script:T})),[f,k,A,w,j,S,T,p.isAuthenticated,p.isLoading,x.isRecording,J?.isConnected,L,B,U])};export{m as useCodicentApp};
|
|
1
|
+
import{useRef as e,useState as t,useCallback as r,useMemo as n,useEffect as s}from"react";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import{createAppStateMachine as o}from"../utils/appState.js";import"../_virtual/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import{useAudioRecorder as i}from"./useAudioRecorder.js";import a from"./useAuthState.js";import c from"./useRealtimeVoiceAI.js";import u from"./useTools.js";import{getConfigValue as l}from"../config/index.js";const m=({auth0:m})=>{const p=a(m),d=e(o(p.codicentService,(()=>{}))),[f,g]=t(),{service:h,context:v}=d.current,{nickname:k,name:A,error:w,errorType:j,selectedApp:y}=v,b=r(((e,t)=>{const r=e.get("file").name;h.uploadFile(r,e).then((e=>{h.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[h]),x=i(b),[S,C]=t(),[T,_]=t(),[I,N]=t(!1),R=n((()=>new Audio("./notification.mp3")),[]),E=r((()=>N(!0)),[]),M=u(h,C,_,R,S,E),O=n((()=>l("REALTIME_VOICE_API_KEY")||""),[]),J=c(h,O,M);s((()=>{I&&(J?.disconnectConversation(),N(!1))}),[I,J]),s((()=>{p.isAuthenticated&&p.user&&p.accessToken&&d.current.updateContext({isAuthenticated:p.isAuthenticated,user:{sub:p.user.sub,email:p.user.email},accessToken:p.accessToken})}),[p.isAuthenticated,p.user,p.accessToken]),s((()=>d.current.updateContext({nickname:p.nickname})),[p.nickname]),s((()=>{d.current.update();let e,t=d.current.getCurrentStateName();g(d.current.getCurrentStateName()),JSON.stringify(d.current.context);let r=!1;const n=s=>setInterval((()=>{const s=d.current.getCurrentStateName();if("hasAccess"===s&&!r)return console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),r=!0,clearInterval(e),void(e=n(1e3));if("hasAccess"!==s&&r)return console.log("🚨 Left stable state - switching to fast polling (200ms)"),r=!1,clearInterval(e),void(e=n(200));const o=JSON.stringify(d.current.context);d.current.update();const i=JSON.stringify(d.current.context),a=d.current.getCurrentStateName();a===t&&o===i||(g(a),t=a)}),s);return e=n(200),()=>clearInterval(e)}),[]);const L=r((e=>e.replace("{nickname}",k||"unknown").replace("{token}",encodeURIComponent(p.accessToken||"unknown")).replace("{app}",y||"unknown")),[k,p.accessToken,y]),B=r((e=>{d.current.updateContext({isAnonymous:e})}),[]),U=r((()=>d.current.isBusy()),[]);return n((()=>({audio:x,auth:p,currentStateName:f,stateMachine:d.current,service:h,context:v,state:f,nickname:k,name:A,error:w,errorType:j,fixAppUrl:L,setAnonymous:B,allStates:d.current.allStates,isBusy:U,voice:J,html:S,setHtml:C,script:T})),[f,k,A,w,j,S,T,p.isAuthenticated,p.isLoading,x.isRecording,J?.isConnected,L,B,U])};export{m as useCodicentApp};
|
|
@@ -1,4 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ToolDefinitionType } from "@openai/realtime-api-beta/dist/lib/client";
|
|
2
|
+
import { CodicentService } from "../services";
|
|
3
|
+
/**
|
|
4
|
+
* Type for conversation items
|
|
5
|
+
*/
|
|
6
|
+
export interface ItemType {
|
|
7
|
+
id: string;
|
|
8
|
+
type: string;
|
|
9
|
+
status?: string;
|
|
10
|
+
role?: string;
|
|
11
|
+
content?: any[];
|
|
12
|
+
formatted?: {
|
|
13
|
+
audio?: Int16Array;
|
|
14
|
+
text?: string;
|
|
15
|
+
transcript?: string;
|
|
16
|
+
file?: any;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
2
19
|
/**
|
|
3
20
|
* Type for all event logs
|
|
4
21
|
*/
|
|
@@ -32,9 +49,9 @@ export interface RealtimeVoice {
|
|
|
32
49
|
updateInstructions: (instructions: string) => void;
|
|
33
50
|
setLanguage: (language: string) => void;
|
|
34
51
|
}
|
|
35
|
-
declare const useRealtimeVoiceAI: (apiKey: string, tools: {
|
|
52
|
+
declare const useRealtimeVoiceAI: (codicentService: CodicentService, apiKey: string, tools: {
|
|
36
53
|
definition: ToolDefinitionType;
|
|
37
54
|
handler: Function;
|
|
38
|
-
}[]) => RealtimeVoice | undefined;
|
|
55
|
+
}[], voice?: string) => RealtimeVoice | undefined;
|
|
39
56
|
export default useRealtimeVoiceAI;
|
|
40
57
|
//# sourceMappingURL=useRealtimeVoiceAI.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRealtimeVoiceAI.d.ts","sourceRoot":"","sources":["../../../src/hooks/useRealtimeVoiceAI.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useRealtimeVoiceAI.d.ts","sourceRoot":"","sources":["../../../src/hooks/useRealtimeVoiceAI.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAK/E,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,GAAG,EAAE,CAAC;IAChB,SAAS,CAAC,EAAE;QACV,KAAK,CAAC,EAAE,UAAU,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,IAAI,CAAC,EAAE,GAAG,CAAC;KACZ,CAAC;CACH;AAED;;GAEG;AACH,UAAU,aAAa;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;CAC/B;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,QAAQ,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CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{useRef as e,useState as t,useCallback as n,useEffect as r,useMemo as o}from"react";import{WavRenderer as a}from"../utils/wav_renderer.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import{WavStreamPlayer as s}from"../lib/wavtools/lib/wav_stream_player.js";import{WavRecorder as i}from"../lib/wavtools/lib/wav_recorder.js";import{getConfigValue as c}from"../config/index.js";const l=(l,u,d,p)=>{const m=!!c("APP_CONFIG"),f=!!c("APP_BUTTONS");m||console.warn("APP_CONFIG is not set. Voice AI will not be available."),f||console.warn("APP_BUTTONS is not set. Voice AI will not be available.");const g=c("APP_CONFIG"),w=c("APP_BUTTONS");c("API_BASE_URL").replace(/\/$/,""),c("USE_REALTIME_SESSION_ENDPOINT"),c("REALTIME_SESSION_ENDPOINT");const h=p||c("REALTIME_VOICE_MODEL")||"alloy",y=["alloy","shimmer","echo"],_=y.includes(h)?h:"alloy";h!==_&&console.warn(`[codicent-app-sdk] Voice "${h}" is not supported in the current SDK version. Supported voices: ${y.join(", ")}. Falling back to "${_}".`);const v=e(new i({sampleRate:24e3})),S=e(new s({sampleRate:24e3})),O=e(null),I=e(null),T=e(null),E=e(null),N=e(!1),C=e(null),R=e(null),A=e(null),b=e((new Date).toISOString()),[P,D]=t([]),[k,F]=t([]),[L,M]=t(!1),[x,$]=t(!1),[U,j]=t(!1),J=e(0),B=e(0),[V,G]=t(""),[q,W]=t("en-US"),[H,z]=t((()=>m&&f&&w&&g&&g.apps&&g.apps[w]?g.apps[w].voiceInstructions||g.REALTIME_VOICE_INSTRUCTIONS||"":g&&g.REALTIME_VOICE_INSTRUCTIONS||"")),K=n((e=>{const t=b.current,n=new Date(t).valueOf(),r=new Date(e).valueOf()-n,o=Math.floor(r/10)%100,a=Math.floor(r/1e3)%60,s=e=>{let t=e+"";for(;t.length<2;)t="0"+t;return t};return`${s(Math.floor(r/6e4)%60)}:${s(a)}.${s(o)}`}),[]),Q=n((async()=>{try{b.current=(new Date).toISOString(),M(!0),F([]),D([]);const e=await l.getRealtimeSessionToken(_);if(!e)throw new Error("No ephemeral key returned from session endpoint");const t=new RTCPeerConnection;O.current=t,T.current||(T.current=new Audio,T.current.autoplay=!0),t.ontrack=e=>{T.current&&e.streams[0]&&(T.current.srcObject=e.streams[0])};const n=await navigator.mediaDevices.getUserMedia({audio:!0});E.current=n;const r=n.getTracks()[0];t.addTrack(r,n);const o=t.createDataChannel("oai-events");I.current=o,o.addEventListener("message",(e=>{try{const t=JSON.parse(e.data);"session.created"===t.type||("conversation.item.created"===t.type?D((e=>[...e,t.item])):"conversation.item.input_audio_transcription.completed"===t.type?D((e=>{const n=[...e],r=n.findIndex((e=>e.id===t.item_id));return-1!==r&&n[r].formatted&&(n[r].formatted.transcript=t.transcript),n})):"response.audio_transcript.delta"===t.type||"response.audio_transcript.done"===t.type||"error"===t.type&&console.error("Server error:",t.error))}catch(t){console.warn("Invalid message:",e.data)}})),o.onopen=()=>{console.log("Data channel opened, configuring session"),o.send(JSON.stringify({type:"session.update",session:{instructions:H.replace("{{name}}",V).replace("{{language}}",q).replace("{{time}}",(new Date).toISOString()),modalities:["text","audio"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:500},voice:_,temperature:.8,max_response_output_tokens:4096,input_audio_format:"pcm16",output_audio_format:"pcm16",tools:d.map((e=>({type:"function",...e.definition})))}}))},o.onclose=()=>{console.log("Data channel closed")};const a=await t.createOffer();await t.setLocalDescription(a);let s="gpt-4o-realtime-preview";try{if(c("REALTIME_CONFIG_ENDPOINT")){const e=await l.getRealtimeConfig();e&&e.model&&(s=e.model)}}catch(e){console.warn("Failed to fetch realtime config, using default model:",e)}const i="https://api.openai.com/v1/realtime",u=await fetch(`${i}?model=${s}`,{method:"POST",body:a.sdp,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/sdp"}});if(!u.ok)throw new Error(`Failed to get SDP answer: ${u.statusText}`);const p={type:"answer",sdp:await u.text()};await t.setRemoteDescription(p),$(!1);const m=v.current,f=S.current;await m.begin(),await f.connect()}catch(e){throw console.error("[codicent-app-sdk] Failed to establish WebRTC connection:",e),M(!1),e}}),[l,_,H,V,q,d]),X=n((async()=>{M(!1),F([]),D([]),I.current&&(I.current.close(),I.current=null),O.current&&(O.current.close(),O.current=null),E.current&&(E.current.getTracks().forEach((e=>e.stop())),E.current=null),T.current&&(T.current.pause(),T.current.srcObject=null);const e=v.current;await e.end();const t=S.current;await t.interrupt()}),[]),Y=n((async e=>{const t=I.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"conversation.item.delete",item_id:e}))}),[]),Z=n((async()=>{j(!0);const e=I.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"input_audio_buffer.commit"}))}),[]),ee=n((async()=>{j(!1);const e=I.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"response.create"}))}),[]),te=n((async e=>{const t=I.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"session.update",session:{turn_detection:"none"===e?null:{type:"server_vad"}}})),$("none"===e)}),[]);r((()=>{if(V&&L){const e=I.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"session.update",session:{instructions:H.replace("{{name}}",V).replace("{{language}}",q).replace("{{time}}",(new Date).toISOString())}}))}}),[H,V,q,L]),r((()=>{let e=!0;const t=v.current,n=C.current;let r=null;const o=S.current,s=R.current;let i=null;const c=()=>{if(e){if(n&&(n.width&&n.height||(n.width=n.offsetWidth,n.height=n.offsetHeight),r=r||n.getContext("2d"),r)){r.clearRect(0,0,n.width,n.height);const e=t.recording?t.getFrequencies("voice"):{values:new Float32Array([0])},o=1-Math.max(...e.values);J.current=o,a.drawCircularBars(n,r,e.values,"#0099ff",20,0,8)}if(s&&(s.width&&s.height||(s.width=s.offsetWidth,s.height=s.offsetHeight),i=i||s.getContext("2d"),i)){i.clearRect(0,0,s.width,s.height);const e=o.analyser?o.getFrequencies("voice"):{values:new Float32Array([0])},t=1-Math.max(...e.values);B.current=t,a.drawCircularBars(s,i,e.values,"#009900",20,0,8)}window.requestAnimationFrame(c)}};return c(),()=>{e=!1}}),[]),r((()=>{!N.current&&d&&H&&(N.current=!0)}),[d,H]);const ne=n((e=>{const t=e.replace("{{name}}",V).replace("{{language}}",q).replace("{{time}}",(new Date).toISOString()),n=I.current;n&&"open"===n.readyState&&n.send(JSON.stringify({type:"session.update",session:{instructions:t}})),z(e)}),[V,q]);return o((()=>{if(m&&f)return{items:P,realtimeEvents:k,isConnected:L,canPushToTalk:x,isRecording:U,clientCanvasRef:C,serverCanvasRef:R,eventsScrollRef:A,formatTime:K,connectConversation:Q,disconnectConversation:X,deleteConversationItem:Y,startRecording:Z,stopRecording:ee,changeTurnEndType:te,getRecorderLevel:()=>J.current,getStreamLevel:()=>B.current,setUsername:G,updateInstructions:ne,setLanguage:W}}),[m,f,P,k,L,x,U,C,R,A])};export{l as default};
|
|
@@ -128,5 +128,9 @@ export declare class CodicentService {
|
|
|
128
128
|
private handleUnauthorized;
|
|
129
129
|
getTodoStatus: (messageId: string) => Promise<"done" | "undone" | "unknown">;
|
|
130
130
|
updateTodoStatus: (messageId: string, status: "done" | "undone") => Promise<boolean>;
|
|
131
|
+
getRealtimeSessionToken(voice?: string): Promise<string>;
|
|
132
|
+
getRealtimeConfig(): Promise<{
|
|
133
|
+
model: string;
|
|
134
|
+
} | null>;
|
|
131
135
|
}
|
|
132
136
|
//# sourceMappingURL=codicent.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAmCA,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI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B;IAM1B,aAAa,cAAqB,MAAM,KAAG,OAAO,CAAC,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC,CAiB/E;IAEF,gBAAgB,cAAqB,MAAM,UAAU,MAAM,GAAG,QAAQ,sBAcpE;IAEI,uBAAuB,CAAC,KAAK,GAAE,MAAgB,GAAG,OAAO,CAAC,MAAM,CAAC;IAsBjE,iBAAiB,IAAI,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CAmB7D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let a="https://codicent.com/",n="-";const s=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let i=s();if(!i){const t=setInterval((()=>{i=s(),i&&clearInterval(t)}),100)}class r{constructor(o){this.createDataMessage=async(t,e)=>await window.Codicent.data.create({codicent:this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e)=>await window.Codicent.data.read({codicent:this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e)=>await window.Codicent.data.update({id:t,data:e,codicent:this.codicent}),this.deleteDataMessage=async t=>await window.Codicent.data.delete({id:t,codicent:this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),a=o[0],n=o.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e)=>window.Codicent.postMessage({message:`@${this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e)=>window.Codicent.getChatReply3({message:t,codicent:this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0)=>{const s=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:this.codicent,search:e,length:o})});let i=await s.json();if(i.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);i=i.concat(t),i.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return i},this.getMessages=async(t,e)=>{let o=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:10});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{o=o.concat(t)})),e)try{const t=await this.getPublicFlow(e);o=o.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return o=o.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),o.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),o},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({priceId:t,successUrl:window.location.href,cancelUrl:window.location.href})});if(!e.ok)throw new Error("Failed to create checkout session");const{id:o}=await e.json();return o},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(e),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}}o=r,r.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,r.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,r.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),a=document.createElement("a");a.style.display="none",a.href=o,a.download=t.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},r.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},r.getMiniChatReply=async(t,e="codicent-mini",o,a=3e5,s=2e3)=>{const i={project:e,message:t};let r;o&&(i.messageId=o);try{const t="https://dev.codicent.com/",e=await fetch(`${t}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(i)});if(!e.ok)return e.status,void console.error(`Failed to start AI chat: ${e.status}`);if(r=(await e.json()).promptMessageId,!r)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const c=Date.now();for(;Date.now()-c<a;)try{const t="https://dev.codicent.com/",o=await fetch(`${t}app/GetAi2ChatReplyStatus?promptMessageId=${r}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===o.status){await new Promise((t=>setTimeout(t,s)));continue}if(!o.ok)return void console.error(`Error polling AI chat status: ${o.status}`);const a=await o.json();return a.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")};export{r as CodicentService};
|
|
1
|
+
import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let a="https://codicent.com/",n="-";const s=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let i=s();if(!i){const t=setInterval((()=>{i=s(),i&&clearInterval(t)}),100)}class r{constructor(o){this.createDataMessage=async(t,e)=>await window.Codicent.data.create({codicent:this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e)=>await window.Codicent.data.read({codicent:this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e)=>await window.Codicent.data.update({id:t,data:e,codicent:this.codicent}),this.deleteDataMessage=async t=>await window.Codicent.data.delete({id:t,codicent:this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),a=o[0],n=o.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e)=>window.Codicent.postMessage({message:`@${this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e)=>window.Codicent.getChatReply4({message:t,codicent:this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0)=>{const s=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:this.codicent,search:e,length:o})});let i=await s.json();if(i.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);i=i.concat(t),i.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return i},this.getMessages=async(t,e)=>{let o=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:10});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{o=o.concat(t)})),e)try{const t=await this.getPublicFlow(e);o=o.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return o=o.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),o.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),o},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({priceId:t,successUrl:window.location.href,cancelUrl:window.location.href})});if(!e.ok)throw new Error("Failed to create checkout session");const{id:o}=await e.json();return o},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(e),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy"){const e=`${a}realtime/session?voice=${t}`,o=await fetch(e,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!o.ok)throw new Error(`Failed to fetch session token: ${o.statusText}`);const n=await o.json(),s=n.client_secret?.value;if(!s)throw new Error("No ephemeral key returned from session endpoint");return s}async getRealtimeConfig(){try{const t=`${a}realtime/config`,e=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return e.ok?await e.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}o=r,r.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,r.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,r.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),a=document.createElement("a");a.style.display="none",a.href=o,a.download=t.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},r.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},r.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")};export{r as CodicentService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e}from"react/jsx-runtime";import{useState as
|
|
1
|
+
import{jsx as e}from"react/jsx-runtime";import{useState as r,useEffect as n}from"react";import o from"../node_modules/nosleep.js/src/index.js";function a(a){return function(c){const[t,s]=r(null),[l]=r((()=>new o));return n((()=>{!async function(){if("wakeLock"in navigator)try{const e=await navigator.wakeLock.request("screen");s(e)}catch(e){console.warn(`Error acquiring wake lock API: ${e}`);try{l.enable()}catch(e){console.error(`Error enabling NoSleep.js: ${e}`)}}else try{l.enable()}catch(e){console.warn(`Error enabling NoSleep.js: ${e}`)}}()}),[]),n((()=>()=>{t&&t.release().then((()=>{})).catch((e=>{console.warn("Error releasing wake lock:",e)}));try{l.disable()}catch(e){console.warn("Error disabling NoSleep.js:",e)}}),[t,l]),e(a,{...c})}}export{a as default};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import * as React$1 from 'react';
|
|
3
3
|
import React__default, { ComponentType, PropsWithChildren, ReactNode, FC } from 'react';
|
|
4
|
-
import {
|
|
4
|
+
import { ToolDefinitionType } from '@openai/realtime-api-beta/dist/lib/client';
|
|
5
5
|
import { RedirectLoginOptions, AppState, Auth0ContextInterface } from '@auth0/auth0-react';
|
|
6
6
|
import { State, StateMachine } from 'statechart-lib';
|
|
7
7
|
export { State, StateMachine } from 'statechart-lib';
|
|
@@ -140,6 +140,10 @@ declare class CodicentService {
|
|
|
140
140
|
private handleUnauthorized;
|
|
141
141
|
getTodoStatus: (messageId: string) => Promise<"done" | "undone" | "unknown">;
|
|
142
142
|
updateTodoStatus: (messageId: string, status: "done" | "undone") => Promise<boolean>;
|
|
143
|
+
getRealtimeSessionToken(voice?: string): Promise<string>;
|
|
144
|
+
getRealtimeConfig(): Promise<{
|
|
145
|
+
model: string;
|
|
146
|
+
} | null>;
|
|
143
147
|
}
|
|
144
148
|
|
|
145
149
|
declare const Markdown: ({ content }: {
|
|
@@ -443,6 +447,22 @@ declare const useTools: (api: CodicentService, setHtml: ((html: string | undefin
|
|
|
443
447
|
handler: any;
|
|
444
448
|
}[];
|
|
445
449
|
|
|
450
|
+
/**
|
|
451
|
+
* Type for conversation items
|
|
452
|
+
*/
|
|
453
|
+
interface ItemType {
|
|
454
|
+
id: string;
|
|
455
|
+
type: string;
|
|
456
|
+
status?: string;
|
|
457
|
+
role?: string;
|
|
458
|
+
content?: any[];
|
|
459
|
+
formatted?: {
|
|
460
|
+
audio?: Int16Array;
|
|
461
|
+
text?: string;
|
|
462
|
+
transcript?: string;
|
|
463
|
+
file?: any;
|
|
464
|
+
};
|
|
465
|
+
}
|
|
446
466
|
/**
|
|
447
467
|
* Type for all event logs
|
|
448
468
|
*/
|
|
@@ -476,10 +496,10 @@ interface RealtimeVoice {
|
|
|
476
496
|
updateInstructions: (instructions: string) => void;
|
|
477
497
|
setLanguage: (language: string) => void;
|
|
478
498
|
}
|
|
479
|
-
declare const useRealtimeVoiceAI: (apiKey: string, tools: {
|
|
499
|
+
declare const useRealtimeVoiceAI: (codicentService: CodicentService, apiKey: string, tools: {
|
|
480
500
|
definition: ToolDefinitionType;
|
|
481
501
|
handler: Function;
|
|
482
|
-
}[]) => RealtimeVoice | undefined;
|
|
502
|
+
}[], voice?: string) => RealtimeVoice | undefined;
|
|
483
503
|
|
|
484
504
|
interface LanguageSource {
|
|
485
505
|
source: "force_config" | "url_param" | "browser" | "default";
|
|
@@ -814,6 +834,10 @@ interface AppConfigOptions {
|
|
|
814
834
|
MODULE_VOICE: boolean;
|
|
815
835
|
PUBLIC_FLOW_CODICENT: undefined | string;
|
|
816
836
|
REALTIME_VOICE_API_KEY: string;
|
|
837
|
+
REALTIME_VOICE_MODEL: string;
|
|
838
|
+
USE_REALTIME_SESSION_ENDPOINT: boolean;
|
|
839
|
+
REALTIME_SESSION_ENDPOINT: string;
|
|
840
|
+
REALTIME_CONFIG_ENDPOINT: string;
|
|
817
841
|
SEND_BUTTON_ROUND_BACKGROUND: boolean;
|
|
818
842
|
SHOW_CANVAS_BUTTON: boolean;
|
|
819
843
|
SHOW_CHAT_PROMPTS: boolean;
|
|
@@ -910,4 +934,4 @@ interface HtmlViewerProps {
|
|
|
910
934
|
}
|
|
911
935
|
declare const HtmlViewer: React__default.FC<HtmlViewerProps>;
|
|
912
936
|
|
|
913
|
-
export { AiInput, AppConfig, AppConfigOptions, AppFrame, AppInfo, AppStateDefinition, AppStateMachine, AudioIcon, AudioRecorder, AudioRecorderState, Button, Chat, ChatInput, ChatMessage, CodicentAppState, CodicentService, CodicentServiceOptions, ColorPicker, CombinedPlaceholderDialog, Compose, Content, CrmPage, DatePicker, FilePlaceholder, FileThumbnail, Footer, Form, FormAccept, FormInvite, Header, HtmlView, HtmlViewer, ImageViewer as ImageView, Input, Label, Login, Logout, Markdown, Message$1 as Message, Content$1 as MessageContent, MessageInput, MessageItem, Page, Profile, Prompt, RealtimeVoice, Sales, Search, SearchBox, Snap, SnapFooter, Spinner, StateContext, TemplateVariable, Text, TextHeader, Textarea, TimePicker, Title, TypingIndicator, UploadFile, UploadFileProps, UploadFileRef, UrlProcessor, UseAuthState, UserInfo, VoiceIcon, WavRecorder, WavStreamPlayer, createAppStateMachine, generateBrandVariants, getConfigValue, getGpsLocation, getTimeString, initCodicentApp, isMobileDevice, log, useAppStyles, useAudioRecorder, useAuthState, useChat, useCodicentApp, useCodicentState, useLocalization, useRealtimeVoiceAI, useStateWithLocalStorage, useTemplateVariables, useToaster, useTools, withWakeLock };
|
|
937
|
+
export { AiInput, AppConfig, AppConfigOptions, AppFrame, AppInfo, AppStateDefinition, AppStateMachine, AudioIcon, AudioRecorder, AudioRecorderState, Button, Chat, ChatInput, ChatMessage, CodicentAppState, CodicentService, CodicentServiceOptions, ColorPicker, CombinedPlaceholderDialog, Compose, Content, CrmPage, DatePicker, FilePlaceholder, FileThumbnail, Footer, Form, FormAccept, FormInvite, Header, HtmlView, HtmlViewer, ImageViewer as ImageView, Input, ItemType, Label, Login, Logout, Markdown, Message$1 as Message, Content$1 as MessageContent, MessageInput, MessageItem, Page, Profile, Prompt, RealtimeVoice, Sales, Search, SearchBox, Snap, SnapFooter, Spinner, StateContext, TemplateVariable, Text, TextHeader, Textarea, TimePicker, Title, TypingIndicator, UploadFile, UploadFileProps, UploadFileRef, UrlProcessor, UseAuthState, UserInfo, VoiceIcon, WavRecorder, WavStreamPlayer, createAppStateMachine, generateBrandVariants, getConfigValue, getGpsLocation, getTimeString, initCodicentApp, isMobileDevice, log, useAppStyles, useAudioRecorder, useAuthState, useChat, useCodicentApp, useCodicentState, useLocalization, useRealtimeVoiceAI, useStateWithLocalStorage, useTemplateVariables, useToaster, useTools, withWakeLock };
|