@boldare/askdare-admin 0.0.0-placeholder

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Boldare S.A.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # @boldare/askdare-admin
2
+
3
+ The admin dashboard for [`@boldare/askdare`](https://www.npmjs.com/package/@boldare/askdare): cost, ratings, unanswered questions, leads, handoffs and conversation reviews, inside askdare's admin console.
4
+
5
+ **[askdare website and docs](https://askdare.vercel.app)** ยท [GitHub](https://github.com/boldare/askdare/tree/main/packages/askdare-admin)
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @boldare/askdare-admin
11
+ ```
12
+
13
+ ## Use
14
+
15
+ The dashboard plugs into the admin console that `createChatHandler` serves. It has no route, sign-in or storage of its own: askdare writes the records to your admin store, checks who signs in and serves the dashboard.
16
+
17
+ ```ts
18
+ import { adminDashboard } from '@boldare/askdare-admin';
19
+ import { postgresAdminStore } from '@boldare/askdare-postgres';
20
+
21
+ export const { GET, POST, DELETE } = createChatHandler({
22
+ bots,
23
+ conversations,
24
+ admin: {
25
+ store: postgresAdminStore({ pool: db }),
26
+ transcripts: true,
27
+ console: {
28
+ allow: ['user_123'],
29
+ dashboard: adminDashboard({
30
+ // Your prices per million tokens, in your currency.
31
+ prices: { 'your-model-id': { input: 1.25, cachedInput: 0.125, output: 10 } },
32
+ }),
33
+ },
34
+ },
35
+ });
36
+ ```
37
+
38
+ After signing into the console, the dashboard shows, for the last 7, 30 or 90 days and per bot:
39
+
40
+ - cost per bot, day and model, from your `prices`; a model without a price shows its tokens and "no price";
41
+ - new conversations, turns, ๐Ÿ‘ and ๐Ÿ‘Ž per day;
42
+ - unanswered questions: a heuristic that counts answers without sources from bots with knowledge, and withheld or failed ones;
43
+ - leads and handoffs per day, and the resolution rate: the share of new conversations without a handoff, per day;
44
+ - the most expensive conversations, and the ๐Ÿ‘Ž answers with the visitors' comments;
45
+ - a review of a conversation from its stored transcript (with `admin.transcripts: true`), or from the conversation store through the console.
46
+
47
+ askdare keeps tokens, not money, and holds no price table: set the prices you pay. Playground turns from the console are left out.
48
+
49
+ ## Privacy
50
+
51
+ The browser never gets a conversation's ID, only references sealed to the admin session. Transcripts and comments are the visitors' words: they are shown as text, never as HTML, and kept only as long as the admin store's retention.
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `@boldare/askdare-admin`: the stage 2 dashboard (ADR-0032, decision 9). It plugs into the admin
3
+ * console that `createChatHandler` serves: core writes the records, checks access, sets the headers
4
+ * and serves the assets; this package holds the dashboard's browser app and its read handlers.
5
+ */
6
+ import { AdminDashboard } from "@boldare/askdare";
7
+ /**
8
+ * What one model costs, per million tokens, in the app's own currency. `cachedInput` is the price
9
+ * of input tokens read from the prompt cache; without it they cost as much as other input.
10
+ */
11
+ interface AdminModelPrice {
12
+ readonly input: number;
13
+ readonly cachedInput?: number | undefined;
14
+ readonly output: number;
15
+ }
16
+ /** Prices by model ID, as the model is reported (the configured model if none answered). */
17
+ type AdminPrices = Readonly<Record<string, AdminModelPrice>>;
18
+ /** Options of `adminDashboard()`. */
19
+ export interface AdminDashboardOptions {
20
+ /**
21
+ * The app's prices per million tokens, by model ID. A model without one shows its tokens and
22
+ * "no price". askdare holds no price table: OpenAI changes prices, and they are yours to set.
23
+ */
24
+ readonly prices?: AdminPrices | undefined;
25
+ }
26
+ /**
27
+ * The dashboard: pass it as `createChatHandler({ admin: { console: { dashboard } } })`. After
28
+ * signing into the console, its owner sees cost per bot, day and model, ratings, new
29
+ * conversations, unanswered questions (a heuristic), leads and handoffs with the resolution rate,
30
+ * the most expensive conversations, the ๐Ÿ‘Ž answers and their comments, and stored transcripts.
31
+ */
32
+ export declare function adminDashboard(options?: AdminDashboardOptions): AdminDashboard;
33
+ export type { AdminModelPrice, AdminPrices };
package/dist/index.js ADDED
@@ -0,0 +1,286 @@
1
+ // src/generated/assets.ts
2
+ const DASHBOARD_JS = "(function(){var e,t,n,r,i,a,o,s,c,l,u=Symbol.for(`pv`),d={},f=[],p=/^m(i|n|o|s|text|space)$/,m=Array.isArray,h=f.slice,g=Object.assign;function _(e){e&&e.parentNode&&e.remove()}function v(n,r,i,a,o){var s={type:n,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:u,__v:o||++t,__i:-1,__u:0};return!o&&e.vnode&&e.vnode(s),s}function y(e){return e.children}function b(e,t){this.props=e,this.context=t,this.__g=0}function x(e,t){if(t==null)return e.__&&x(e.__,e.__i+1);for(var n;t<e.__k.length;t++)if((n=e.__k[t])&&n.__e)return n.__e;return typeof e.type!=`function`||e.props.__P?null:x(e)}function S(t){var n,r=t.__v,i=r.__e,a=[],o=[],s=t.__P;s&&((n=g({constructor:u},r)).__v=r.__v+1,e.vnode&&e.vnode(n),M(s,n,r,t.__n,s.namespaceURI,32&r.__u?[i]:null,a,i||x(r),32&r.__u,o),n.__v=r.__v,n.__.__k[n.__i]=n,P(a,n,o),r.__=r.__e=null,n.__e!=i&&C(n))}function C(e){if((e=e.__)&&e.__c&&!e.props.__P)return e.__e=null,e.__k.some(function(t){return t&&(e.__e=t.__e)}),C(e)}function w(t){(8&t.__g||(t.__g|=8,n.push(t),i++))&&r==e.debounceRendering||((r=e.debounceRendering)||queueMicrotask)(T)}function T(){try{for(var e,t=1;n.length;)n.length>t&&n.sort(a),e=n.shift(),t=n.length,8&e.__g&&S(e)}finally{(i=n.length)&&(r||queueMicrotask)(T)}}function ee(e,t,n,r,i,a,o,s,c,l,u){var p,m,h,g,_,v,y=r.__k||f,b=t.length;for(c=E(n,t,y,c,b),p=0;p<b;p++)(h=n.__k[p])!=null&&(m=~h.__i&&y[h.__i]||d,h.__i=p,v=M(e,h,m,i,a,o,s,c,l,u),g=h.__e,(m.ref!=h.ref||8&m.__u)&&(m.ref&&F(m.ref,null,h,m),h.ref&&u.push(h.ref,h.__c||g,h)),_||=g,4&h.__u?(c=D(h,c,e,!m.__v),m.__e&&(m.__e=null)):typeof h.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),h.__u&=-21);return n.__e=_,c}function E(e,t,n,r,i){var a,o,s,c,l,d,f,p,h,g=n.length,_=g,b=0,S=0,C=e.__k=Array(i);for(a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o!=`object`||o.constructor===String?o=C[a]=v(null,o):m(o)?o=C[a]=v(y,{children:o}):o.constructor===u&&o.__b?o=C[a]=v(o.type,o.props,o.key,o.ref,o.__v):C[a]=o,c=a+b,o.__=e,o.__b=e.__b+1,s=null,~(l=o.__i=O(o,n,c,_))&&(_--,(s=n[l])&&(s.__u|=2)),s&&s.__v?(o.__u|=16,l==c-1?b--:l==c+1?b++:l!=c&&(l>c?b--:b++,S=1)):(~l||(i>g?b--:i<g&&b++),typeof o.type!=`function`&&(o.__u|=4))):C[a]=null;if(S){for(d=[],f=[],a=0;a<i;a++)if((o=C[a])&&16&o.__u){for(b=0,p=d.length;b<p;)d[h=b+p>>1]<o.__i?b=h+1:p=h;d[b]=o.__i,f[a]=b+1}for(b=d.length;a--;)f[a]&&(f[a]==b?b--:C[a].__u|=4)}if(_)for(a=0;a<g;a++)!(s=n[a])||2&s.__u||(s.__e==r&&(r=x(s)),re(s,s));return r}function D(e,t,n,r){var i,a,o,s;if(typeof e.type==`function`){if(e.props.__P)return t;if(i=e.__k)for(a=0;a<i.length;a++)i[a]&&(i[a].__=e,t=D(i[a],t,n,!1));return t}for(t&&!t.parentNode&&(t=x(e))&&!t.parentNode&&(t=null),o=e.__e,s=t;s&&s.nodeType==8;)s=s.nextSibling;for(o!=s&&(!r&&n.moveBefore&&o.parentNode?n.moveBefore(o,t):n.insertBefore(o,t||null)),t=o;(t&&=t.nextSibling)&&t.nodeType==8&&!t.data.startsWith(`$s`););return t}function O(e,t,n,r){var i,a=e.key,o=e.type,s=t[n],c=s&&!(2&s.__u);if(s===null&&a==null||c&&a==s.key&&o==s.type)return n;if(r>+!!c){for(i=n-1;i>=0;i--)if((s=t[i])&&!(2&s.__u)&&a==s.key&&o==s.type)return i;for(i=n+1;i<t.length;i++)if((s=t[i])&&!(2&s.__u)&&a==s.key&&o==s.type)return i}return-1}function k(e,t,n){n??=``,t[0]==`-`?e.setProperty(t,n):e[t]=n}function A(e,t,n,r,i){var a,o;if(t==`style`){if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||k(e.style,t);if(n)for(t in n)r&&n[t]==r[t]||k(e.style,t,n[t])}}else if(t[0]==`o`&&t[1]==`n`)typeof n!=`function`&&(n=null),typeof r!=`function`&&(r=null),(e.__e||={})[t]=n,n&&r||(o=l[t]||(l[t]=j(t)),(e.__a||={})[t]=c,a=t!=(t=t.replace(s,`$1`)),(t=t.slice(2))[0]<`a`&&(t=t.toLowerCase()),n?e.addEventListener(t,o,a):e.removeEventListener(t,o,a));else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;return}catch{}if(typeof n==`function`)return;n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n)}}function j(t){return function(n){var r=this.__e;if(r){if(r=r[t],n[o]==null)n[o]=c++;else if(n[o]<this.__a[t])return;return r(e.event?e.event(n):n)}}}function M(t,n,r,i,a,o,s,c,l,d){var p,h,v,S,C,w,T,E,D,O,k,A,j,M,P,F,I,L,R=n.type;if(n.constructor!==u)return null;128&r.__u&&(l=32&r.__u,p=r.__c.__z)&&(n.__u|=l,h=o=[],p.nodeType==8?c=N(p,o):o.push(p),c=o[0]||c),(p=e.__b)&&p(n);n:if(typeof R==`function`){v=s.length;try{if(E=n.props,D=(p=R.prototype)&&p.render,O=(p=R.contextType)&&i[p.__c],k=p?O?O.props.value:p.__:i,(S=r.__c)?(n.__c=S,2&S.__g&&(S.__g|=1)):(D?n.__c=S=new R(E,k):(n.__c=S=new b(E,k),S.constructor=R,S.render=ie),O&&O.sub(S),S.state||(S.state={}),S.__n=i,S.__g|=8,S.__h=[],S.__k=[]),D&&(S.__s||(S.__s=S.state),R.getDerivedStateFromProps&&(S.__s==S.state&&(S.__s=g({},S.__s)),g(S.__s,R.getDerivedStateFromProps(E,S.__s)))),C=S.props,w=S.state,S.__v=n,r.__c){if(E!==C&&D&&!R.getDerivedStateFromProps&&S.componentWillReceiveProps&&S.componentWillReceiveProps(E,k),n.__v==r.__v&&!(8&S.__g)||!(4&S.__g)&&S.shouldComponentUpdate&&!1===S.shouldComponentUpdate(E,S.__s,k)){n.__v!=r.__v&&(S.props=E,S.state=S.__s,S.__g&=-9),n.__e=r.__e,n.__k=r.__k,n.__k.some(function(e){e&&(e.__=n)}),f.push.apply(S.__h,S.__k),S.__k=[],S.__h.length&&s.push(S),c=x(r);break n}S.componentWillUpdate&&S.componentWillUpdate(E,S.__s,k),D&&S.componentDidUpdate&&S.__h.push(function(){S.componentDidUpdate(C,w,T)})}else D&&!R.getDerivedStateFromProps&&S.componentWillMount&&S.componentWillMount(),D&&S.componentDidMount&&S.__h.push(S.componentDidMount);S.context=k,S.props=E,S.__P=t,S.__g&=-5,A=e.__r,j=D?25:0;do S.__g&=-9,A&&A(n),p=S.render(S.props,S.state=S.__s,S.context);while(8&S.__g&&++j<25);D&&(f.push.apply(S.__h,S.__k),S.__k=[]),S.state=S.__s,S.getChildContext&&(i=g({},i,S.getChildContext())),D&&r.__c&&S.getSnapshotBeforeUpdate&&(T=S.getSnapshotBeforeUpdate(C,w)),M=p&&p.type===y&&p.key==null?p.props.children:p,E.__P&&(p=c,a=(t=E.__P).namespaceURI,l=o=null,r.props&&r.props.__P!=t&&(r.__k.some(function(e){e&&re(e,e)}),r.__k=null),c=r.__k?x(r,0):null),c=ee(t,m(M)?M:[M],n,r,i,a,o,s,c,l,d),E.__P&&(n.__e=null,c=p),n.__u&=-161,h&&h.some(_),S.__h.length&&s.push(S),1&S.__g&&(S.__g&=-4)}catch(t){if(s.length=v,n.__v=null,l||o){if(t&&t.then){if(n.__u|=128|l,o){for(~(I=o.indexOf(c||void 0))||(I=o.length);(L=o[I-1])&&L.nodeType==8;)I--;for(;I<o.length;I++)if(L=o[I]){if(o[I]=null,P){if(L==F)break}else{if(L.nodeType!=8)break;L.data.startsWith(`$s`)&&(F=N(P=L))}}}if(!P){for(;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;P=c}(p=N(P=n.__c.__z||(n.__c.__z=P)))?(n.__e=P,c=p):n.__e=c,c&&=c.nextSibling}else o&&o.some(_)}else n.__e=r.__e;n.__k||=r.__k||[],t&&t.then||te(n),e.__e(t,n,r)}}else c=n.__e=ne(r.__e,n,r,i,a,o,s,l,d,t);return(p=e.diffed)&&p(n),c}function N(e,t){if(e&&e.nodeType==8&&e.data.startsWith(`$s`))for(var n=1;e=e.nextSibling;){if(e.nodeType==8){if(e.data.startsWith(`$s`))n++;else if(e.data.startsWith(`/$s`)&&!--n)return e}t&&t.push(e)}}function te(e){e&&(e.__c&&(e.__c.__g|=4),e.__k&&e.__k.some(te))}function P(t,n,r){for(var i=0;i<r.length;)F(r[i++],r[i++],r[i++]);e.__c&&e.__c(n,t),t.some(function(n){try{t=n.__h,n.__h=[],t.some(function(e){e.call(n)})}catch(t){e.__e(t,n.__v)}})}function ne(t,n,r,i,a,o,s,c,l,u){var f,g,v,y,b,S,C,w,T=r.props||d,E=n.props,D=n.type;if(D==`svg`?a=`http://www.w3.org/2000/svg`:D==`math`?a=`http://www.w3.org/1998/Math/MathML`:a||=`http://www.w3.org/1999/xhtml`,o){for(f=0;f<o.length;f++)if((b=o[f])&&(D?b.localName==D:b.nodeType==3)){t=b,o[f]=null;break}}if(!t){if(w=u.ownerDocument||document,!D)return w.createTextNode(E);t=w.createElementNS(a,D,E.is?E:u),c&&=(e.__m&&e.__m(n,o),!1),o=null}if(D){if(u=D==`template`&&t.content||t,o=D==`textarea`&&E.defaultValue!=null?null:o&&h.call(u.childNodes),!c&&o)for(T={},f=0;f<t.attributes.length;f++)T[(b=t.attributes[f]).name]=b.value;for(f in T)b=T[f],f==`dangerouslySetInnerHTML`?v=b:f==`children`||f in E||f==`value`&&`defaultValue`in E||f==`checked`&&`defaultChecked`in E||A(t,f,null,b,a);for(f in E)b=E[f],f==`children`?y=b:f==`dangerouslySetInnerHTML`?g=b:f==`value`?S=b:f==`checked`?C=b:c&&typeof b!=`function`||T[f]===b||A(t,f,b,T[f],a);g?(c||v&&(g.__html==v.__html||g.__html==t.innerHTML)||(t.innerHTML=g.__html),n.__k=[]):(v&&(t.textContent=``),(D==`foreignObject`||a==`http://www.w3.org/1998/Math/MathML`&&p.test(D))&&(a=`http://www.w3.org/1999/xhtml`),ee(u,m(y)?y:[y],n,r,i,a,o,s,o?o[0]:r.__k&&x(r,0),c,l),o&&o.some(_)),c&&D!=`textarea`||(f=`value`,D==`progress`&&S==null?t.removeAttribute(f):S==null||S===t[f]&&(D!=`progress`||S)||A(t,f,S,T[f],a),f=`checked`,C!=null&&C!=t[f]&&A(t,f,C,T[f],a))}else T===E||c&&t.data==E||(t.data=E);return t}function F(t,n,r,i){try{typeof t==`function`?n?n.__x=t(n)||1:(i&&=i.__c||i.__e)&&(n=i.__x)&&(i.__x=null,typeof n==`function`?n():t(null)):t.current=n}catch(t){e.__e(t,r)}}function re(t,n,r){var i,a,o,s;if(e.unmount&&e.unmount(t),!(i=t.ref)||i.current&&i.current!=t.__e||F(i,null,n,t),i=t.__c){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(t){e.__e(t,n)}i.__P=i.__n=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&re(i[s],n,typeof t.type!=`function`||r&&!t.props.__P);!r&&(i=t.__c)&&(i=i.__z)&&(a=N(i,o=[]))&&(i==t.__e&&o.some(_),_(a),_(i)),r||_(t.__e),t.__e=t.__c=t.__=null}function ie(e,t,n){return this.constructor(e,n)}function I(t,n){var r,i,a,o;e.__&&e.__(t,n),n.nodeType==9&&(n=n.documentElement),i=(r=t&&32&t.__u)?null:n.__k,n.__k=v(y,{children:[t]}),a=[],o=[],M(n,n.__k,i||d,d,n.namespaceURI,i?null:n.firstChild?h.call(n.childNodes):null,a,i?i.__e:n.firstChild,r,o),P(a,n.__k,o),n.__k.props.children=null}e={__e:function(e,t,n,r){for(var a,o,s;t=t.__;)if((a=t.__c)&&!(1&a.__g)){a.__g|=4;try{if((s=(o=a.constructor)&&o.getDerivedStateFromError)&&a.setState(o.getDerivedStateFromError(e)),a.componentDidCatch&&(a.componentDidCatch(e,r||{}),s=1),s&&8&a.__g)return void(a.__g|=2)}catch(t){e=t}}throw i=0,e}},t=0,b.prototype.setState=function(e,t){var n=this.__s;n&&n!=this.state||(n=this.__s=g({},this.state)),typeof e==`function`&&(e=e(g({},n),this.props)),e&&(g(n,e),this.__v&&(t&&this.__k.push(t),w(this)))},b.prototype.forceUpdate=function(e){this.__v&&(this.__g|=4,e&&this.__h.push(e),w(this))},b.prototype.render=y,n=[],i=0,a=function(e,t){return e.__v.__b-t.__v.__b},o=Symbol(),s=/(PointerCapture)$|Capture$/i,c=0,l={};var L,R,z,ae,B=Object.is,V=0,oe=[],H=[],U=e,se=U.__b,ce=U.__r,le=U.diffed,ue=U.__c,de=U.unmount,fe=U.__;function pe(e,t){U.__h&&U.__h(R,e,V||t),V=0;var n=R.__H||(R.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function W(e){return V=1,me(xe,e)}function me(e,t,n){var r=pe(L++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):xe(void 0,t),function(e){var t=(r.__N||r.__)[0],n=r.t(t,e);B(t,n)||(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=R,!R.__f)){R.__f=!0;var i=R.shouldComponentUpdate;R.shouldComponentUpdate=function(e,t,n){var r=this.__H;if(!r)return!0;var a=!1,o=this.props!=e;if(r.__.some(function(e){e.__N&&(a=!0,B(e.__[0],e.__N[0])||(o=!0))}),i){var s=i.call(this,e,t,n);return a?s||o:s}return!a||o}}return r.__}function he(e,t){var n=pe(L++,3);!U.__s&&be(n.__H,t)&&(n.__P=!0,n.__=e,n.u=t,R.__H.__h.push(n))}function ge(){var e;do{for(;e=H.shift();)try{G(e)}catch(t){U.__e(t,{__:(e=e.__P)&&e.__v})}for(;e=oe.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(G),t.__h.some(K),t.__h=[]}catch(n){t.__h=[],U.__e(n,e.__v)}}}while(H.length)}U.__b=function(e){R=null,se&&se(e)},U.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),fe&&fe(e,t)},U.__r=function(e){ce&&ce(e),L=0;var t=(R=e.__c).__H;t&&(z==R?R.__h=[]:(t.__h.some(G),t.__h.some(K),L=0),t.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})),z=R},U.diffed=function(e){le&&le(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&ye(oe.push(t)),t.__H.__.some(function(e){e.u&&(e.__H=e.u)})),z=R=null},U.__c=function(e,t){t.some(function(e){try{e.__h.some(G),e.__h=e.__h.filter(function(e){return!e.__||K(e)})}catch(t){e.__h=[function(){throw t}]}}),ue&&ue(e,t)},U.unmount=function(e){de&&de(e);var t,n,r=e.__c;r&&r.__H&&(r.__H.__.some(function(r){try{if(r.__P&&r.__c){if(n===void 0){for(n=e.__;n&&(!n.__c||!n.__c.__P);)n=n.__;n&&=n.__c}r.__P=n,ye(H.push(r))}else G(r)}catch(e){t=e}}),r.__H=void 0,t&&U.__e(t,r.__v))};var _e=typeof requestAnimationFrame==`function`;function ve(e){var t,n=function(){clearTimeout(r),_e&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);_e&&(t=requestAnimationFrame(n))}function ye(e){e!=1&&ae==U.requestAnimationFrame||((ae=U.requestAnimationFrame)||ve)(ge)}function G(e){var t=R,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),R=t}function K(e){var t=R;e.__c=e.__(),R=t}function be(e,t){return!e||e.length!=t.length||t.some(function(t,n){return!B(t,e[n])})}function xe(e,t){return typeof t==`function`?t(e):t}var Se=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Ce=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:4}),we=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:0}),q=e=>Se.format(e),J=e=>e===null?`no price`:Ce.format(e),Te=e=>e===null?`โ€“`:we.format(e),Y=e=>new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}),Ee=864e5,De=e=>new Date(e).toISOString().slice(0,10);function Oe(e,t=Date.now()){return{from:De(t-(e-1)*Ee),to:De(t)}}function ke(e,t){let n=[],r=Date.parse(`${t}T00:00:00Z`);for(let t=Date.parse(`${e}T00:00:00Z`);t<=r;t+=Ee)n.push(De(t));return n}var Ae=Symbol.for(`pv`),je=0;Array.isArray;function X(t,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l&&typeof t!=`function`)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:t,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:Ae,__v:--je,__i:-1,__u:0};return(a||o)&&(u.__source=a,u.__self=o),e.vnode&&e.vnode(u),u}var Me=[7,30,90],Z={days:30,bot:``,view:`overview`,order:`tokens`};function Ne(e,t,n,r){let[i,a]=W({});return he(()=>{let r=!0;return a({}),e.call(t,n).then(e=>r&&a({data:e}),e=>r&&a({error:e instanceof Error?e.message:`internal_error`})),()=>{r=!1}},[r]),i}var Pe=e=>e.input+e.output;function Fe({host:e}){let[t,n]=W(Z.days),[r,i]=W(Z.bot),[a,o]=W(Z.view);Z.days=t,Z.bot=r,Z.view=a;let[s,c]=W(),l={...Oe(t),...r?{bot:r}:{}},u=Ne(e,`days`,l,JSON.stringify(l)),d=u.data?.bots??[];return X(`div`,{class:`askdare-dashboard`,children:[X(`header`,{class:`ad-bar`,children:[X(`nav`,{class:`ad-tabs`,\"aria-label\":`Dashboard views`,children:[[`overview`,`Overview`],[`conversations`,`Conversations`],[`ratings`,`๐Ÿ‘Ž answers`]].map(([e,t])=>X(`button`,{type:`button`,\"aria-pressed\":a===e&&s===void 0,onClick:()=>{o(e),c(void 0)},children:t},e))}),X(`div`,{class:`ad-filters`,children:[X(`label`,{children:[`Days`,` `,X(`select`,{value:t,onChange:e=>n(Number(e.currentTarget.value)),children:Me.map(e=>X(`option`,{value:e,children:[`Last `,e]},e))})]}),X(`label`,{children:[`Bot`,` `,X(`select`,{value:r,onChange:e=>i(e.currentTarget.value),children:[X(`option`,{value:``,children:`All bots`}),[...new Set([...d,...r?[r]:[]])].map(e=>X(`option`,{value:e,children:e},e))]})]})]})]}),s===void 0?a===`overview`?X(Ie,{state:u}):X(a===`conversations`?Re:Ve,{host:e,filter:l,onReview:c}):X(He,{host:e,reference:s,onBack:()=>c(void 0)})]})}function Q({error:e}){return e===void 0?X(`p`,{class:`ad-muted`,children:`Loadingโ€ฆ`}):X(`p`,{class:`ad-error`,role:`alert`,children:[`Couldn't load this (`,e,`).`]})}function $({label:e,value:t,hint:n}){return X(`div`,{class:`ad-tile`,children:[X(`span`,{class:`ad-muted`,children:e}),X(`strong`,{children:t}),n?X(`small`,{class:`ad-muted`,children:n}):null]})}function Ie({state:e}){let t=e.data;if(!t)return X(Q,{error:e.error});let{totals:n}=t,r=ke(t.from,t.to).map(e=>{let n=t.models.filter(t=>t.day===e),r=t.days.filter(t=>t.day===e),i=(e,t)=>e.reduce((e,n)=>e+t(n),0),a=i(r,e=>e.conversations),o=i(r,e=>e.handoffs);return{day:e,turns:i(n,e=>e.turns),cost:i(n,e=>e.cost??0),unanswered:i(n,e=>e.unanswered),conversations:a,up:i(r,e=>e.up),down:i(r,e=>e.down),leads:i(r,e=>e.leads),handoffs:o,resolution:a===0?null:Math.min(1,Math.max(0,1-o/a))}}),i=Math.max(...r.map(e=>e.cost),0),a=new Map;for(let e of t.models){let t=`${e.bot}\\u0000${e.model}`,n=a.get(t);n?(n.turns+=e.turns,n.tokens={input:n.tokens.input+e.tokens.input,cachedInput:n.tokens.cachedInput+e.tokens.cachedInput,output:n.tokens.output+e.tokens.output},n.cost=n.cost===null||e.cost===null?null:n.cost+e.cost):a.set(t,{bot:e.bot,model:e.model,turns:e.turns,tokens:e.tokens,cost:e.cost})}return X(`section`,{children:[X(`div`,{class:`ad-tiles`,children:[X($,{label:`Cost`,value:J(n.cost),...n.unpriced.length>0?{hint:`no price: ${n.unpriced.join(`, `)}`}:{}}),X($,{label:`New conversations`,value:q(n.conversations)}),X($,{label:`Turns`,value:q(n.turns),hint:`${q(n.failed)} failed`}),X($,{label:`Ratings`,value:`๐Ÿ‘ ${q(n.up)} ยท ๐Ÿ‘Ž ${q(n.down)}`}),X($,{label:`Unanswered questions`,value:q(n.unanswered),hint:`Heuristic: no sources, withheld or failed`}),X($,{label:`Leads`,value:q(n.leads)}),X($,{label:`Handoffs`,value:q(n.handoffs)}),X($,{label:`Resolution rate`,value:Te(n.resolution),hint:`New conversations without a handoff`})]}),X(`h3`,{children:`By day`}),X(`div`,{class:`ad-scroll`,children:X(`table`,{children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{scope:`col`,children:`Day`}),X(`th`,{scope:`col`,children:`Cost`}),X(`th`,{scope:`col`,children:`Conversations`}),X(`th`,{scope:`col`,children:`Turns`}),X(`th`,{scope:`col`,children:`๐Ÿ‘`}),X(`th`,{scope:`col`,children:`๐Ÿ‘Ž`}),X(`th`,{scope:`col`,children:`Unanswered`}),X(`th`,{scope:`col`,children:`Leads`}),X(`th`,{scope:`col`,children:`Handoffs`}),X(`th`,{scope:`col`,children:`Resolution`})]})}),X(`tbody`,{children:r.slice().reverse().map(e=>X(`tr`,{children:[X(`th`,{scope:`row`,children:e.day}),X(`td`,{children:X(`span`,{class:`ad-bar-cell`,children:[X(`span`,{class:`ad-bar-fill`,style:{width:`${i>0?e.cost/i*100:0}%`}}),X(`span`,{children:J(e.cost)})]})}),X(`td`,{children:q(e.conversations)}),X(`td`,{children:q(e.turns)}),X(`td`,{children:q(e.up)}),X(`td`,{children:q(e.down)}),X(`td`,{children:q(e.unanswered)}),X(`td`,{children:q(e.leads)}),X(`td`,{children:q(e.handoffs)}),X(`td`,{children:Te(e.resolution)})]},e.day))})]})}),X(`h3`,{children:`By bot and model`}),X(`div`,{class:`ad-scroll`,children:X(`table`,{children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{scope:`col`,children:`Bot`}),X(`th`,{scope:`col`,children:`Model`}),X(`th`,{scope:`col`,children:`Turns`}),X(`th`,{scope:`col`,children:`Input tokens`}),X(`th`,{scope:`col`,children:`Cached`}),X(`th`,{scope:`col`,children:`Output tokens`}),X(`th`,{scope:`col`,children:`Cost`})]})}),X(`tbody`,{children:[...a.values()].map(e=>X(`tr`,{children:[X(`td`,{children:e.bot}),X(`td`,{children:e.model}),X(`td`,{children:q(e.turns)}),X(`td`,{children:q(e.tokens.input)}),X(`td`,{children:q(e.tokens.cachedInput)}),X(`td`,{children:q(e.tokens.output)}),X(`td`,{children:J(e.cost)})]},`${e.bot}\\u0000${e.model}`))})]})})]})}function Le(e,t,n){let r=JSON.stringify(n),i=Ne(e,t,n,r),[a,o]=W(),[s,c]=W(),l=a?.key===r?a:void 0,u=[...i.data?.items??[],...l?.items??[]],d=l?l.cursor:i.data?.cursor;return{loaded:i.data!==void 0,error:i.error??s,items:u,cursor:d,loadMore:()=>e.call(t,{...n,cursor:d}).then(e=>{let t=e;o({items:[...l?.items??[],...t.items],cursor:t.cursor,key:r})},e=>c(e instanceof Error?e.message:`internal_error`))}}function Re({host:e,filter:t,onReview:n}){let[r,i]=W(Z.order);Z.order=r;let a=Le(e,`conversations`,{...t,order:r});return X(`section`,{children:[X(`label`,{children:[`Order`,` `,X(`select`,{value:r,onChange:e=>i(e.currentTarget.value),children:[X(`option`,{value:`tokens`,children:`Most expensive first`}),X(`option`,{value:`latest`,children:`Latest first`})]})]}),a.loaded?a.items.length===0?X(`p`,{class:`ad-muted`,children:`No conversations started in this range.`}):X(`div`,{class:`ad-scroll`,children:X(`table`,{children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{scope:`col`,children:`Started`}),X(`th`,{scope:`col`,children:`Bot`}),X(`th`,{scope:`col`,children:`Turns`}),X(`th`,{scope:`col`,children:`Tokens`}),X(`th`,{scope:`col`,children:`Cost`}),X(`th`,{scope:`col`,children:`๐Ÿ‘ / ๐Ÿ‘Ž`}),X(`th`,{scope:`col`,children:X(`span`,{class:`ad-hidden`,children:`Review`})})]})}),X(`tbody`,{children:a.items.map(t=>X(`tr`,{children:[X(`td`,{children:Y(t.firstAt)}),X(`td`,{children:t.bot}),X(`td`,{children:q(t.turns)}),X(`td`,{children:q(Pe(t.tokens))}),X(`td`,{children:t.cost===null?`no price`:`โ‰ˆ ${J(t.cost)}`}),X(`td`,{children:[q(t.up),` / `,q(t.down)]}),X(`td`,{children:X(ze,{host:e,item:t,onReview:n})})]},t.ref))})]})}):X(Q,{error:a.error}),X(Be,{list:a})]})}function ze({host:e,item:t,onReview:n}){return t.transcript===!1&&!e.review?null:X(`button`,{type:`button`,onClick:()=>e.review?e.review(t.ref):n(t.ref),children:`Review`})}function Be({list:e}){return X(y,{children:[e.loaded&&e.error?X(Q,{error:e.error}):null,e.loaded&&e.cursor?X(`button`,{type:`button`,class:`ad-more`,onClick:e.loadMore,children:`More`}):null]})}function Ve({host:e,filter:t,onReview:n}){let r=Le(e,`ratings`,{...t,rating:`down`});return X(`section`,{children:[r.loaded?r.items.length===0?X(`p`,{class:`ad-muted`,children:`No ๐Ÿ‘Ž answers in this range.`}):X(`ul`,{class:`ad-list`,children:r.items.map(t=>X(`li`,{children:[X(`div`,{class:`ad-row`,children:[X(`span`,{class:`ad-muted`,children:[Y(t.at),` ยท `,t.bot]}),X(ze,{host:e,item:t,onReview:n})]}),X(`p`,{class:`ad-text`,children:t.comment??X(`span`,{class:`ad-muted`,children:`No comment`})})]},`${t.ref}${t.at}`))}):X(Q,{error:r.error}),X(Be,{list:r})]})}function He({host:e,reference:t,onBack:n}){let r=Ne(e,`transcript`,{ref:t},t);return X(`section`,{children:[X(`button`,{type:`button`,onClick:n,children:`โ† Back`}),r.data?r.data.turns.length===0?X(`p`,{class:`ad-muted`,children:[`No transcript is stored for this conversation.`,` `,e.review?X(`button`,{type:`button`,onClick:()=>e.review?.(t),children:`Open it from the conversation store`}):null]}):X(`ol`,{class:`ad-list`,children:r.data.turns.map(e=>X(`li`,{children:[X(`p`,{class:`ad-muted`,children:Y(e.at)}),X(`p`,{class:`ad-text ad-visitor`,children:[e.input,e.attachments>0?X(`small`,{class:`ad-muted`,children:[` (`,e.attachments,` attached)`]}):null]}),X(`p`,{class:`ad-text`,children:e.answer??X(`span`,{class:`ad-muted`,children:[`No answer (`,e.reason,`)`]})}),e.check&&e.check!==`allowed`?X(`p`,{class:`ad-muted`,children:[`Output check: `,e.check]}):null,e.citations.length>0?X(`ul`,{class:`ad-sources`,children:e.citations.map(e=>X(`li`,{children:[`[`,e.index,`] `,e.title,e.url?X(`span`,{class:`ad-muted`,children:[` `,e.url]}):null]},e.index))}):null]},e.at))}):X(Q,{error:r.error})]})}globalThis.askdareAdminDashboard={mount(e,t){return I(X(Fe,{host:t}),e),()=>I(null,e)}},window.dispatchEvent(new Event(`askdare-admin-dashboard`))})();";
3
+ const DASHBOARD_CSS = ".askdare-dashboard{--ad-fg:var(--ink,#242424);--ad-muted:var(--muted,#5f5a68);--ad-card:var(--card,#fff);--ad-inset:var(--inset,#f6f2f7);--ad-line:var(--line,#2424241a);--ad-line-strong:var(--line-strong,#24242433);--ad-accent:var(--accent,#a3285a);--ad-accent-soft:var(--accent-soft,#c2386f14);--ad-button:var(--button,linear-gradient(115deg, #c2386f, #6b52e0));--ad-error:var(--fail,#b42318);--ad-shadow:var(--shadow,none);color:var(--ad-fg);font:inherit;gap:16px;display:grid}.askdare-dashboard>section,.askdare-dashboard section{align-content:start;gap:12px;min-width:0;display:grid}.askdare-dashboard section>label{justify-self:start}.askdare-dashboard h3{margin:12px 0 0;font-size:1rem;font-weight:700}.askdare-dashboard p{margin:0}.askdare-dashboard button{border:1px solid var(--ad-line-strong);background:var(--ad-card);min-height:32px;color:inherit;font:inherit;white-space:nowrap;cursor:pointer;border-radius:999px;align-items:center;padding:4px 14px;font-size:.86rem;font-weight:600;display:inline-flex}.askdare-dashboard button:hover{border-color:color-mix(in srgb, var(--ad-accent) 50%, var(--ad-line-strong));background:var(--ad-accent-soft)}.askdare-dashboard :focus-visible{outline:2px solid var(--ad-accent);outline-offset:2px}.askdare-dashboard label{color:var(--ad-muted);align-items:center;gap:8px;font-size:.9rem;display:inline-flex}.ad-bar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px 16px;display:flex}.ad-tabs{border:1px solid var(--ad-line);background:var(--ad-card);border-radius:999px;gap:2px;padding:4px;display:flex;overflow-x:auto}.askdare-dashboard .ad-tabs button{color:var(--ad-muted);background:0 0;border:0}.askdare-dashboard .ad-tabs button:hover{background:var(--ad-accent-soft);color:var(--ad-fg)}.askdare-dashboard .ad-tabs button[aria-pressed=true]{background:var(--ad-button);color:#fff}.ad-filters{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.ad-tiles{grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:12px;display:grid}.ad-tile{border:1px solid var(--ad-line);background:var(--ad-card);box-shadow:var(--ad-shadow);border-radius:16px;flex-direction:column;gap:2px;padding:16px;display:flex}.ad-tile>span{font-size:.82rem;font-weight:600}.ad-tile strong{letter-spacing:-.02em;font-variant-numeric:tabular-nums;font-size:1.5rem;font-weight:800}.ad-tile small{font-size:.8rem}.ad-muted{color:var(--ad-muted)}.ad-error{color:var(--ad-error);font-weight:500}.ad-scroll{border:1px solid var(--ad-line);background:var(--ad-card);box-shadow:var(--ad-shadow);border-radius:16px;overflow-x:auto}.askdare-dashboard table{border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;font-size:.92rem}.askdare-dashboard th,.askdare-dashboard td{border-bottom:1px solid var(--ad-line);text-align:left;white-space:nowrap;padding:10px 14px}.askdare-dashboard tbody tr:last-child>*{border-bottom:0}.askdare-dashboard tbody tr:hover{background:var(--ad-accent-soft)}.askdare-dashboard thead th{color:var(--ad-muted);font-size:.8rem;font-weight:700}.askdare-dashboard tbody th{font-weight:600}.ad-bar-cell{min-width:120px;display:inline-block;position:relative}.ad-bar-fill{background:var(--ad-button);opacity:.22;border-radius:6px;position:absolute;inset:0 auto 0 0}.ad-bar-cell>span:last-child{padding:0 6px;position:relative}.ad-list{gap:12px;margin:0;padding:0;list-style:none;display:grid}.ad-list>li{border:1px solid var(--ad-line);background:var(--ad-card);box-shadow:var(--ad-shadow);border-radius:16px;gap:6px;padding:16px;display:grid}.ad-row{justify-content:space-between;align-items:center;gap:8px;display:flex}.ad-text{white-space:pre-wrap;overflow-wrap:anywhere}.ad-visitor{font-weight:600}.ad-sources{color:var(--ad-muted);overflow-wrap:anywhere;margin:0;padding-left:20px;font-size:.88rem}.askdare-dashboard .ad-more{justify-self:start}.ad-hidden{clip-path:inset(50%);width:1px;height:1px;position:absolute;overflow:hidden}@media (prefers-reduced-motion:no-preference){.askdare-dashboard button{transition:background-color .16s,border-color .16s}}\n/*$vite$:1*/";
4
+ // src/handlers.ts
5
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
6
+ const MAX_TEXT = 200;
7
+ const MAX_REF = 4096;
8
+ /** Prefix of sealed cursors, so a cursor can't pass for a conversation reference. */
9
+ const CURSOR = "askdare-admin-cursor\0";
10
+ const DEFAULT_LIMIT = 20;
11
+ /** An error core answers by its `code` (ADR-0032 contract with the console). */
12
+ var DashboardError = class extends Error {
13
+ name = "DashboardError";
14
+ code;
15
+ constructor(code, message) {
16
+ super(message);
17
+ this.code = code;
18
+ }
19
+ };
20
+ const invalid = (message) => new DashboardError("invalid_input", message);
21
+ function object(input) {
22
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw invalid("The request must be a JSON object.");
23
+ return input;
24
+ }
25
+ function text(input, name, max = MAX_TEXT) {
26
+ const value = input[name];
27
+ if (value === void 0) return void 0;
28
+ if (typeof value !== "string" || value.length === 0 || value.length > max) throw invalid(`${name} must be a string of 1 to ${max} characters.`);
29
+ return value;
30
+ }
31
+ function oneOf(input, name, values) {
32
+ const value = input[name];
33
+ if (value === void 0) return void 0;
34
+ if (!values.includes(value)) throw invalid(`${name} must be one of ${values.join(", ")}.`);
35
+ return value;
36
+ }
37
+ /** The day range: `from` and `to` as `YYYY-MM-DD`; the store checks the span. Playground turns are left out. */
38
+ function range(input) {
39
+ const from = text(input, "from");
40
+ const to = text(input, "to");
41
+ if (from === void 0 || to === void 0 || !DAY.test(from) || !DAY.test(to)) throw invalid("from and to must be YYYY-MM-DD.");
42
+ const bot = text(input, "bot");
43
+ return bot === void 0 ? {
44
+ from,
45
+ to,
46
+ source: "chat"
47
+ } : {
48
+ from,
49
+ to,
50
+ bot,
51
+ source: "chat"
52
+ };
53
+ }
54
+ function limit(input) {
55
+ const value = input["limit"] ?? DEFAULT_LIMIT;
56
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 100) throw invalid("limit must be an integer from 1 to 100.");
57
+ return value;
58
+ }
59
+ async function openCursor(input, request) {
60
+ const sealed = text(input, "cursor", MAX_REF);
61
+ if (sealed === void 0) return void 0;
62
+ const cursor = await request.open(sealed);
63
+ if (cursor === void 0 || !cursor.startsWith(CURSOR)) throw invalid("Unknown cursor.");
64
+ return cursor.slice(21);
65
+ }
66
+ const sealCursor = async (cursor, request) => cursor === void 0 ? {} : { cursor: await request.seal(CURSOR + cursor) };
67
+ const tokens = (usage) => ({
68
+ input: usage.inputTokens,
69
+ cachedInput: usage.cachedInputTokens,
70
+ output: usage.outputTokens
71
+ });
72
+ const addTokens = (a, b) => ({
73
+ input: a.input + b.input,
74
+ cachedInput: a.cachedInput + b.cachedInput,
75
+ output: a.output + b.output
76
+ });
77
+ const NO_TOKENS = {
78
+ input: 0,
79
+ cachedInput: 0,
80
+ output: 0
81
+ };
82
+ /** The cost of the tokens at `price`, or `null` without a price. */
83
+ function cost(usage, price) {
84
+ if (price === void 0) return null;
85
+ const cached = Math.min(usage.cachedInput, usage.input);
86
+ return ((usage.input - cached) * price.input + cached * (price.cachedInput ?? price.input) + usage.output * price.output) / 1e6;
87
+ }
88
+ const handedOff = (counts) => counts.sent + counts.saved + counts.unavailable + counts.failed;
89
+ /**
90
+ * The resolution rate of decision 5: one minus handoffs (any final state but `limited`) over new
91
+ * conversations, kept within 0 and 1. A daily ratio, since handoffs aren't tied to conversations.
92
+ */
93
+ function resolution(conversations, handoffs) {
94
+ if (conversations === 0) return null;
95
+ return Math.min(1, Math.max(0, 1 - handoffs / conversations));
96
+ }
97
+ function priceOf(prices, model) {
98
+ return Object.hasOwn(prices, model) ? prices[model] : void 0;
99
+ }
100
+ function daysAnswer(days, from, to, prices) {
101
+ const models = days.turns.map((row) => {
102
+ const rowTokens = tokens(row.usage);
103
+ return {
104
+ day: row.day,
105
+ bot: row.bot,
106
+ model: row.model,
107
+ turns: row.turns,
108
+ failed: row.failed,
109
+ unanswered: row.unanswered,
110
+ tokens: rowTokens,
111
+ cost: cost(rowTokens, priceOf(prices, row.model))
112
+ };
113
+ });
114
+ const botDays = days.bots.map((row) => {
115
+ const handoffs = handedOff(row.handoffs);
116
+ return {
117
+ day: row.day,
118
+ bot: row.bot,
119
+ conversations: row.conversations,
120
+ up: row.up,
121
+ down: row.down,
122
+ leads: row.leads,
123
+ handoffs,
124
+ limited: row.handoffs.limited,
125
+ resolution: resolution(row.conversations, handoffs)
126
+ };
127
+ });
128
+ const bots = [.../* @__PURE__ */ new Set([...models.map((row) => row.bot), ...botDays.map((row) => row.bot)])].sort();
129
+ const unpriced = [...new Set(models.filter((row) => row.cost === null).map((row) => row.model))].sort();
130
+ const sum = (rows, of) => rows.reduce((total, row) => total + of(row), 0);
131
+ const conversations = sum(botDays, (row) => row.conversations);
132
+ const handoffs = sum(botDays, (row) => row.handoffs);
133
+ return {
134
+ from,
135
+ to,
136
+ bots,
137
+ models,
138
+ days: botDays,
139
+ totals: {
140
+ turns: sum(models, (row) => row.turns),
141
+ failed: sum(models, (row) => row.failed),
142
+ unanswered: sum(models, (row) => row.unanswered),
143
+ conversations,
144
+ up: sum(botDays, (row) => row.up),
145
+ down: sum(botDays, (row) => row.down),
146
+ leads: sum(botDays, (row) => row.leads),
147
+ handoffs,
148
+ resolution: resolution(conversations, handoffs),
149
+ tokens: models.reduce((total, row) => addTokens(total, row.tokens), NO_TOKENS),
150
+ cost: sum(models, (row) => row.cost ?? 0),
151
+ unpriced
152
+ }
153
+ };
154
+ }
155
+ /**
156
+ * The read handlers by action name. `prices` stays on the server; the browser gets costs, never
157
+ * the price table.
158
+ */
159
+ function createHandlers(prices) {
160
+ return {
161
+ /** Daily rows of the range, priced, with resolution rates. */
162
+ days: async (request) => {
163
+ const query = range(object(request.input));
164
+ return daysAnswer(await request.store.days(query, request.signal), query.from, query.to, prices);
165
+ },
166
+ /**
167
+ * The conversations started in the range, most expensive (`tokens`) or latest first. The store
168
+ * doesn't say which model a conversation used, so its cost is given only when its bot answered
169
+ * with a single priced model in the range.
170
+ */
171
+ conversations: async (request) => {
172
+ const input = object(request.input);
173
+ const query = range(input);
174
+ const order = oneOf(input, "order", ["tokens", "latest"]) ?? "tokens";
175
+ const rated = oneOf(input, "rated", ["down"]);
176
+ const cursor = await openCursor(input, request);
177
+ const [page, days] = await Promise.all([request.store.conversations({
178
+ ...query,
179
+ order,
180
+ limit: limit(input),
181
+ ...rated === void 0 ? {} : { rated },
182
+ ...cursor === void 0 ? {} : { cursor }
183
+ }, request.signal), request.store.days(query, request.signal)]);
184
+ const modelsOf = /* @__PURE__ */ new Map();
185
+ for (const row of days.turns) {
186
+ const set = modelsOf.get(row.bot) ?? /* @__PURE__ */ new Set();
187
+ set.add(row.model);
188
+ modelsOf.set(row.bot, set);
189
+ }
190
+ const priceFor = (bot) => {
191
+ const models = modelsOf.get(bot);
192
+ if (models?.size !== 1) return void 0;
193
+ const [model] = models;
194
+ return model === void 0 ? void 0 : priceOf(prices, model);
195
+ };
196
+ return {
197
+ items: await Promise.all(page.items.map(async (item) => {
198
+ const itemTokens = tokens(item.usage);
199
+ return {
200
+ ref: await request.seal(item.conversationId),
201
+ bot: item.bot,
202
+ firstAt: item.firstAt,
203
+ lastAt: item.lastAt,
204
+ turns: item.turns,
205
+ tokens: itemTokens,
206
+ cost: cost(itemTokens, priceFor(item.bot)),
207
+ up: item.up,
208
+ down: item.down,
209
+ transcript: item.transcript
210
+ };
211
+ })),
212
+ ...await sealCursor(page.cursor, request)
213
+ };
214
+ },
215
+ /** The ratings given in the range, newest first, with the visitor's comments. */
216
+ ratings: async (request) => {
217
+ const input = object(request.input);
218
+ const query = range(input);
219
+ const rating = oneOf(input, "rating", ["up", "down"]);
220
+ const cursor = await openCursor(input, request);
221
+ const page = await request.store.ratings({
222
+ ...query,
223
+ limit: limit(input),
224
+ ...rating === void 0 ? {} : { rating },
225
+ ...cursor === void 0 ? {} : { cursor }
226
+ }, request.signal);
227
+ return {
228
+ items: await Promise.all(page.items.map(async (item) => ({
229
+ ref: await request.seal(item.conversationId),
230
+ bot: item.bot,
231
+ at: item.at,
232
+ rating: item.rating,
233
+ ...item.comment === void 0 ? {} : { comment: item.comment }
234
+ }))),
235
+ ...await sealCursor(page.cursor, request)
236
+ };
237
+ },
238
+ /** A conversation's stored transcript, by its sealed reference; empty without one. */
239
+ transcript: async (request) => {
240
+ const ref = text(object(request.input), "ref", MAX_REF);
241
+ if (ref === void 0) throw invalid("ref is required.");
242
+ const conversationId = await request.open(ref);
243
+ if (conversationId === void 0 || conversationId.startsWith(CURSOR)) throw new DashboardError("not_found", "Unknown conversation.");
244
+ return { turns: (await request.store.transcript(conversationId, request.signal)).map((record) => ({
245
+ at: record.at,
246
+ input: record.input,
247
+ attachments: record.attachments,
248
+ answer: record.answer ?? null,
249
+ citations: record.citations.map((citation) => ({
250
+ index: citation.index,
251
+ title: citation.title,
252
+ ...citation.url === void 0 ? {} : { url: citation.url }
253
+ })),
254
+ ...record.check === void 0 ? {} : { check: record.check },
255
+ reason: record.reason
256
+ })) };
257
+ }
258
+ };
259
+ }
260
+ // src/index.ts
261
+ function checkPrices(prices) {
262
+ const checked = Object.create(null);
263
+ for (const [model, price] of Object.entries(prices)) {
264
+ if (![
265
+ price.input,
266
+ price.output,
267
+ ...price.cachedInput === void 0 ? [] : [price.cachedInput]
268
+ ].every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0)) throw new TypeError(`adminDashboard: the price of "${model}" must be numbers of 0 or more.`);
269
+ checked[model] = { ...price };
270
+ }
271
+ return Object.freeze(checked);
272
+ }
273
+ /**
274
+ * The dashboard: pass it as `createChatHandler({ admin: { console: { dashboard } } })`. After
275
+ * signing into the console, its owner sees cost per bot, day and model, ratings, new
276
+ * conversations, unanswered questions (a heuristic), leads and handoffs with the resolution rate,
277
+ * the most expensive conversations, the ๐Ÿ‘Ž answers and their comments, and stored transcripts.
278
+ */
279
+ function adminDashboard(options = {}) {
280
+ return {
281
+ script: DASHBOARD_JS,
282
+ style: DASHBOARD_CSS,
283
+ handlers: createHandlers(checkPrices(options.prices ?? {}))
284
+ };
285
+ }
286
+ export { adminDashboard };
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@boldare/askdare-admin",
3
+ "version": "0.0.0-placeholder",
4
+ "description": "The admin dashboard for @boldare/askdare: cost, ratings, unanswered questions, leads, handoffs and conversation reviews, inside the admin console.",
5
+ "license": "MIT",
6
+ "author": {
7
+ "name": "Boldare",
8
+ "url": "https://www.boldare.com"
9
+ },
10
+ "homepage": "https://github.com/boldare/askdare/tree/main/packages/askdare-admin#readme",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/boldare/askdare.git",
14
+ "directory": "packages/askdare-admin"
15
+ },
16
+ "bugs": "https://github.com/boldare/askdare/issues",
17
+ "keywords": [
18
+ "askdare",
19
+ "admin",
20
+ "dashboard",
21
+ "chatbot"
22
+ ],
23
+ "type": "module",
24
+ "sideEffects": false,
25
+ "engines": {
26
+ "node": ">=22"
27
+ },
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "types": "./dist/index.d.ts",
36
+ "files": [
37
+ "dist",
38
+ "LICENSE",
39
+ "CHANGELOG.md"
40
+ ],
41
+ "peerDependencies": {
42
+ "@boldare/askdare": "^0.6.1"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public",
46
+ "provenance": true
47
+ },
48
+ "devDependencies": {
49
+ "@arethetypeswrong/cli": "^0.18.5",
50
+ "@boldare/askdare": "^0.6.1",
51
+ "preact": "11.2.0",
52
+ "publint": "^0.3.25",
53
+ "tsdown": "^0.23.7",
54
+ "vite": "^8.3.8"
55
+ },
56
+ "scripts": {
57
+ "build:assets": "vite build -c vite.config.ts && node scripts/inline-assets.mjs",
58
+ "build": "pnpm run build:assets && tsdown && node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\"",
59
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.ui.json",
60
+ "check:package": "publint --strict && attw --pack . --profile esm-only && node ../../scripts/check-dts-no-leak.mjs dist"
61
+ }
62
+ }