ai-ax 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/{react.d.ts → client/react.d.ts} +2 -2
- package/dist/{react.js → client/react.js} +1 -1
- package/dist/client/ui.d.ts +651 -0
- package/dist/client/ui.js +7 -0
- package/dist/client.d.ts +6 -6
- package/dist/client.js +2 -2
- package/dist/hono/d1.d.ts +137 -0
- package/dist/hono/d1.js +1 -0
- package/dist/hono/r2.d.ts +194 -0
- package/dist/hono/r2.js +1 -0
- package/dist/hono.d.ts +1 -1
- package/dist/hono.js +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/types.d.ts +4 -6
- package/package.json +33 -5
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{atom as e,setAtom as t,useAtomValue as n}from"./react.js";import{useEffect as r,useLayoutEffect as i,useRef as a,useState as o}from"react";import{Fragment as s,jsx as c,jsxs as l}from"react/jsx-runtime";import u from"@material-symbols/svg-400/outlined/support_agent.svg?raw";import d from"@material-symbols/svg-400/outlined/drag_indicator.svg?raw";import f,{default as p}from"@material-symbols/svg-400/outlined/close.svg?raw";import m,{default as h}from"@material-symbols/svg-400/outlined/search.svg?raw";import ee from"@material-symbols/svg-400/outlined/mic.svg?raw";import te from"@material-symbols/svg-400/outlined/send.svg?raw";import ne from"@material-symbols/svg-400/outlined/stop_circle.svg?raw";import re from"@material-symbols/svg-400/outlined/graphic_eq.svg?raw";import ie from"@material-symbols/svg-400/outlined/attach_file_add.svg?raw";import ae from"@material-symbols/svg-400/outlined/keyboard_arrow_down.svg?raw";import oe from"@material-symbols/svg-400/outlined/more_horiz.svg?raw";import se,{default as ce}from"@material-symbols/svg-400/outlined/check.svg?raw";import le from"markdown-it";import ue from"@material-symbols/svg-400/outlined/add.svg?raw";import de from"@material-symbols/svg-400/outlined/arrow_back.svg?raw";import fe from"@material-symbols/svg-400/outlined/arrow_drop_down.svg?raw";import pe from"@material-symbols/svg-400/outlined/chevron_right.svg?raw";import me from"@material-symbols/svg-400/outlined/cloud.svg?raw";import he from"@material-symbols/svg-400/outlined/delete.svg?raw";import ge from"@material-symbols/svg-400/outlined/folder.svg?raw";import _e from"@material-symbols/svg-400/outlined/home.svg?raw";import ve from"@material-symbols/svg-400/outlined/keep.svg?raw";import ye from"@material-symbols/svg-400/outlined/keep-fill.svg?raw";import be from"@material-symbols/svg-400/outlined/left_panel_close.svg?raw";import xe from"@material-symbols/svg-400/outlined/left_panel_open.svg?raw";import Se from"@material-symbols/svg-400/outlined/menu.svg?raw";import Ce from"@material-symbols/svg-400/outlined/more_vert.svg?raw";import we from"@material-symbols/svg-400/outlined/redo.svg?raw";import Te from"@material-symbols/svg-400/outlined/schedule.svg?raw";import Ee from"@material-symbols/svg-400/outlined/settings.svg?raw";import De from"@material-symbols/svg-400/outlined/help.svg?raw";import Oe from"@material-symbols/svg-400/outlined/keyboard.svg?raw";import ke from"@material-symbols/svg-400/outlined/sync.svg?raw";import Ae from"@material-symbols/svg-400/outlined/undo.svg?raw";import je from"@material-symbols/svg-400/outlined/unfold_more.svg?raw";import Me from"@material-symbols/svg-400/outlined/visibility_off.svg?raw";import Ne from"@material-symbols/svg-400/outlined/create_new_folder.svg?raw";import Pe from"@material-symbols/svg-400/outlined/upload_file.svg?raw";import Fe from"@material-symbols/svg-400/outlined/drive_folder_upload.svg?raw";import Ie from"@material-symbols/svg-400/outlined/edit.svg?raw";import Le from"@material-symbols/svg-400/outlined/download.svg?raw";import Re from"@material-symbols/svg-400/outlined/info.svg?raw";import ze from"@material-symbols/svg-400/outlined/open_in_new.svg?raw";import Be from"@material-symbols/svg-400/outlined/restore_from_trash.svg?raw";import Ve from"@material-symbols/svg-400/outlined/description.svg?raw";const g=({name:e,size:t=20,color:n,className:r=``})=>c(`span`,{className:`inline-block shrink-0 [&>svg]:h-full [&>svg]:w-full [&>svg]:fill-current ${r}`,style:{width:t,height:t,color:n},dangerouslySetInnerHTML:{__html:e}}),He=e=>e.stopPropagation(),Ue=e=>e.preventDefault(),We=({show:e,children:t})=>e?c(s,{children:t}):null,Ge=(e,t,n={})=>{let{align:r=`right`,point:i=null,gap:a=4,margin:o=8}=n,s=e?.getBoundingClientRect(),c=t?.getBoundingClientRect(),l=i?{left:i.x,right:i.x,top:i.y,bottom:i.y}:s;if(!l||!c)return null;let u=window.innerWidth,d=window.innerHeight,f=Math.min(c.height,d-o*2),p=i||r===`left`?l.left:l.right-c.width,m=Math.min(Math.max(o,p),Math.max(o,u-c.width-o)),h=l.bottom+a;return{x:m,y:h+f>d-o?Math.max(o,l.top-f-a):h,h:f}},Ke=({m:e,value:t,check:n})=>l(s,{children:[l(`span`,{className:`flex min-w-0 flex-1 flex-col items-start`,children:[c(`span`,{className:`truncate`,children:e.label}),c(`span`,{className:`truncate text-[12px] text-mute`,children:e.desc})]}),t===e.id&&c(g,{name:n,size:18,color:`#4185f4`})]}),qe=({m:e,value:t,check:n})=>l(s,{children:[t===e.id&&c(g,{name:n,size:18}),t!==e.id&&e.icon&&c(g,{name:e.icon,size:18,color:e.color,className:e.color?``:`text-mute`}),t!==e.id&&!e.icon&&c(`span`,{className:`w-[18px] shrink-0`}),c(`span`,{className:`truncate`,children:e.label})]}),Je=({cls:e,items:t,value:n,pick:r,style:i,check:a})=>c(`div`,{className:`absolute z-50 rounded-xl border border-line bg-white py-2 shadow-[0_8px_24px_rgba(0,0,0,0.12)] ${e}`,style:i,onClick:He,children:t.map(e=>c(`div`,{className:e.top?`mt-2 border-t border-line pt-2`:``,children:c(`button`,{onClick:()=>r(e),className:`flex w-full items-center gap-3 px-4 text-left hover:bg-pale ${e.desc?`py-2`:`h-11`}`,children:e.desc?c(Ke,{m:e,value:n,check:a}):c(qe,{m:e,value:n,check:a})})},e.id))}),Ye=({items:e,value:t,pick:n,align:r=`right`,cls:u=`w-72`,point:d,check:f})=>{let p=a(null),m=a(null),[h,ee]=o(null);return i(()=>ee(Ge(p.current?.parentElement,m.current?.firstElementChild,{align:r,point:d})),[]),l(s,{children:[c(`span`,{ref:p,className:`absolute h-0 w-0`}),c(`div`,{ref:m,className:`fixed z-50`,style:h?{left:h.x,top:h.y}:{left:0,top:0,visibility:`hidden`},children:c(Je,{cls:`left-0 top-0 overflow-y-auto ${u}`,style:{maxHeight:h?.h??window.innerHeight-16},items:e,value:t,pick:n,check:f})})]})},Xe=`#1f1f21`,Ze=`#8b8b8b`,Qe=`#ececec`,$e=`#d9d9d9`,et=`#fafafa`,tt=`#f1f1f1`,nt=`#202020`,rt=`#4185f4`,_={row:36,indent:20,slot:20,icon:20,gap:8,brand:22,width:233},it={card:200,suggest:264},at=15360,ot=104857600,st=`ファイルサイズが大きすぎます (上限 100 MB)`,ct=768,lt=1073741824,ut=1048576,dt=1024,ft=e=>String(e).padStart(2,`0`),pt=e=>{let t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?`${t.getHours()}:${ft(t.getMinutes())}`:t.getFullYear()===n.getFullYear()?`${t.getMonth()+1}月${t.getDate()}日`:`${t.getFullYear()}/${ft(t.getMonth()+1)}/${ft(t.getDate())}`},mt=e=>e>=1048576?`${(e/ut).toFixed(1)} MB`:e>=1024?`${Math.round(e/dt)} KB`:`${e} B`,ht=e=>e>=1073741824?`${(e/lt).toFixed(2)} GB`:`${Math.round(e/ut)} MB`,gt=e=>{let t=Math.max(0,(Date.now()-new Date(e).getTime())/1e3);return t<60?`たった今`:t<3600?`${Math.floor(t/60)} 分前`:t<86400?`${Math.floor(t/3600)} 時間前`:`${Math.floor(t/86400)} 日前`},_t=(e,t)=>{if(!t.has(e))return e;let n=e.lastIndexOf(`.`),r=n>0?e.slice(0,n):e,i=n>0?e.slice(n):``,a=1;for(;t.has(`${r}(${a})${i}`);)a++;return`${r}(${a})${i}`},vt={position:`fixed`,left:`0`,top:`0`,zIndex:`60`,overflow:`hidden`,pointerEvents:`none`,background:`#fff`,transition:`width 0.16s ease, height 0.16s ease, left 0.16s ease, top 0.16s ease`},yt={width:`100%`,height:`100%`},bt={width:`264px`,height:`62px`,borderRadius:`12px`,boxShadow:`0 8px 24px rgba(0, 0, 0, 0.12)`},xt={display:`flex`,alignItems:`center`,padding:`12px`,border:`1px solid ${$e}`,borderRadius:`12px`,background:`#fff`},v=(e,t)=>Object.assign(e.style,t),St=()=>{let e=null,t=0,n=0;return{start(r,i,a){if(!r||e)return;let o=r.getBoundingClientRect(),s=r.cloneNode(!0);t=i??o.left,n=a??o.top,e=document.createElement(`div`),v(e,vt),v(s,yt),e.appendChild(s),e.style.left=`${o.left}px`,e.style.top=`${o.top}px`,e.style.width=`${o.width}px`,e.style.height=`${o.height}px`,document.body.appendChild(e),requestAnimationFrame(()=>{e&&(v(e,bt),v(s,xt),s.querySelectorAll(`[data-ghost-hide]`).forEach(e=>v(e,{display:`none`})),e.style.left=`${t}px`,e.style.top=`${n}px`)})},move(r,i){e&&(e.style.transform=`translate(${r-t}px, ${i-n}px)`)},end(){e?.remove(),e=null}}},Ct=(e,t)=>{let n=e.getAttribute(`data-drop-from`);return n===null||n.split(` `).includes(t)},wt=(e,t,n,r)=>{let i=document.elementFromPoint(e,t),a=i?.closest(`[data-drop]`),o=a?.getAttribute(`data-drop`);return!i||!a||typeof o!=`string`||!Ct(a,n)||r(i,o)?null:a},Tt=e=>{let t=e.closest(`[data-drop-scope]`)??document,n=Array.from(t.querySelectorAll(`[data-drop-mark="${CSS.escape(e.getAttribute(`data-drop`))}"]`));return n.length>0?n:e.hasAttribute(`data-drop-scope`)?[]:[e]},Et=[`outline-2`,`-outline-offset-2`,`rounded-lg`,`outline-ink`],Dt=()=>{let e=``,t=()=>!1,n=null,r=[];return{begin(n,r=()=>!1){e=n,t=r},move(i,a){let o=wt(i,a,e,t);o!==n&&(r.forEach(e=>e.classList.remove(...Et)),n=o,r=o?Tt(o):[],r.forEach(e=>e.classList.add(...Et)))},read(){return n?.getAttribute(`data-drop`)??null},end(){r.forEach(e=>e.classList.remove(...Et)),r=[],n=null}}},Ot=typeof Float32Array<`u`?Float32Array:Array,y=(e=0,t=0,n=new Ot(2))=>(n[0]=e,n[1]=t,n),kt=(e,t,n=y())=>(n[0]=e[0]+t[0],n[1]=e[1]+t[1],n),At=(e,t,n=y())=>(n[0]=e[0]-t[0],n[1]=e[1]-t[1],n),jt=(e,t=y())=>(t[0]=e[0],t[1]=e[1],t),b=typeof window<`u`&&!!window.document&&!!window.document.createElement,Mt=()=>b&&`ontouchstart`in window,Nt=()=>Mt()||b&&window.navigator.maxTouchPoints>1,Pt=()=>b&&`onpointerdown`in window,Ft=()=>b&&`exitPointerLock`in window.document,It=()=>{try{return`constructor`in GestureEvent}catch{return!1}},x={isBrowser:b,get gesture(){return x._gesture??=It()},get touch(){return x._touch??=Mt()},get touchscreen(){return x._touchscreen??=Nt()},get pointer(){return x._pointer??=Pt()},get pointerLock(){return x._pointerLock??=Ft()}},Lt=(e=!1)=>e&&x.pointerLock?`mouse`:x.pointer?`pointer`:x.touch?`touch`:`mouse`,Rt=(e,t,n)=>{if(t!==`touch`)return y(e.clientX,e.clientY,n);let[r]=e.changedTouches;return y(r.clientX,r.clientY,n)},zt={touch:{start:`touchstart`,move:`touchmove`,end:`touchend`,up:`touchcancel`},pointer:{start:`pointerdown`,move:`pointermove`,end:`pointerup`,up:`pointercancel`},mouse:{start:`mousedown`,move:`mousemove`,end:`mouseup`,up:`mousecancel`}};let S=null;const Bt=(e,t=()=>!0)=>{let n=()=>{y(0,0,r.value),y(0,0,r._value),y(0,0,r.delta),y(0,0,r.movement)},r={_active:!1,active:!1,pointerId:null,device:Lt(),_value:y(0,0),value:y(0,0),delta:y(0,0),offset:y(0,0),movement:y(0,0),target:null,event:null,memo:{},isDragStart:!1,isDragging:!1,isDragEnd:!1,drag:()=>{let t=r._active;r.isDragStart=r.active&&!t,r.isDragging=r.active&&t,r.isDragEnd=!r.active&&t,e?.(),r._active=r.active},dragStart:e=>{r.active||S&&S!==r||t(e)&&(e.stopPropagation(),S=r,r.pointerId=e.pointerId??null,r.event=e,r._active=!1,r.active=!0,n(),Rt(e,r.device,r.value),r.target.setPointerCapture&&`pointerId`in e&&r.target.setPointerCapture(e.pointerId),r.drag(r))},dragging:e=>{r.event=e,!(r.active&&r.pointerId!==null&&e.pointerId!==r.pointerId)&&(r.active&&e.cancelable&&e.preventDefault(),r.active&&e.stopPropagation(),jt(r.value,r._value),Rt(e,r.device,r.value),r.active&&(At(r.value,r._value,r.delta),kt(r.offset,r.delta,r.offset),kt(r.movement,r.delta,r.movement)),r.drag(r))},dragEnd:e=>{r.active&&r.pointerId!==null&&e.pointerId!==r.pointerId||(S===r&&(S=null),r.event=e,r.active=!1,n(),r.pointerId=null,r.target.releasePointerCapture&&`pointerId`in e&&r.target.releasePointerCapture(e.pointerId),r.drag(r))},mount:e=>{r.target=e;let{start:t,move:n,end:i,up:a}=zt[r.device];e.addEventListener(t,r.dragStart),e.addEventListener(n,r.dragging,{passive:!1}),e.addEventListener(i,r.dragEnd),e.addEventListener(a,r.dragEnd)},clean:()=>{let e=r.target;if(!e)return;let{start:t,move:n,end:i,up:a}=zt[r.device];e.removeEventListener(t,r.dragStart),e.removeEventListener(n,r.dragging),e.removeEventListener(i,r.dragEnd),e.removeEventListener(a,r.dragEnd),S===r&&(S=null)},ref:e=>{e?r.mount(e):r.clean(null)}};return r},Vt=[`select-none`,`cursor-grabbing`],Ht=e=>{e.preventDefault(),e.stopPropagation()},Ut=(e,t,n,r,i)=>{let a=()=>{u.memo.moved=!0,navigator.vibrate?.(15),document.body.classList.add(...Vt),n.start(u.target,u.value[0],u.value[1]),r.begin(t,(t,n)=>u.target.contains(t)||n===e||n.startsWith(`${e}/`))},o=()=>{clearTimeout(u.memo.timer),u.memo.moved=!1,u.memo.touch=u.event?.pointerType===`touch`,u.memo.touch&&(u.memo.timer=setTimeout(()=>{u.active&&a()},300))},s=()=>{let e=Math.hypot(u.movement[0],u.movement[1])>8;if(u.memo.touch&&!u.memo.moved){e&&clearTimeout(u.memo.timer);return}!u.memo.moved&&!e||(u.memo.moved||a(),n.move(u.value[0],u.value[1]),r.move(u.value[0],u.value[1]))},c=()=>{let e=u.memo.moved?r.read():null;r.end(),n.end(),document.body.classList.remove(...Vt),u.memo.moved&&(window.addEventListener(`click`,Ht,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener(`click`,Ht,{capture:!0}),0)),e!==null&&i(e)},l=e=>{if(u.active){if(e.type===`contextmenu`&&u.memo.touch)return Ht(e);u.memo.moved&&e.preventDefault()}},u=Bt(()=>{u.isDragStart&&o(),u.isDragging&&s(),u.isDragEnd&&c()},e=>e.button===0&&!e.target?.closest?.(`button, a, input, label`));return e=>{if(!e){clearTimeout(u.memo.timer),u.clean();return}u.mount(e),e.addEventListener(`contextmenu`,l),e.addEventListener(`touchmove`,l,{passive:!1})}},Wt=e=>{let t=St(),n=Dt(),r=new Map;return(i,a=``)=>{let o=`${a}:${i}`;return r.has(o)||r.set(o,Ut(i,a,t,n,t=>e(i,t))),r.get(o)}},Gt={start:`dragenter`,move:`dragover`,leave:`dragleave`,end:`drop`},Kt=(e,t=()=>!0)=>{let n={_active:!1,active:!1,depth:0,value:y(0,0),target:null,event:null,memo:{},isDropStart:!1,isDropping:!1,isDropEnd:!1,drop:()=>{let t=n._active;n.isDropStart=n.active&&!t,n.isDropping=n.active&&t,n.isDropEnd=!n.active&&t,e?.(),n._active=n.active},dropStart:e=>{n.depth++,!n.active&&t(e)&&(e.preventDefault(),n.event=e,n._active=!1,n.active=!0,y(e.clientX,e.clientY,n.value),n.drop(n))},dropping:e=>{n.active&&(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),n.event=e,y(e.clientX,e.clientY,n.value),n.drop(n))},dropLeave:e=>{n.depth>0&&n.depth--,!(n.depth>0||!n.active)&&(n.event=e,n.active=!1,n.drop(n))},dropEnd:e=>{n.depth=0,n.active&&(e.preventDefault(),n.event=e,n.active=!1,y(e.clientX,e.clientY,n.value),n.drop(n))},mount:e=>{n.target=e;let{start:t,move:r,leave:i,end:a}=Gt;e.addEventListener(t,n.dropStart),e.addEventListener(r,n.dropping),e.addEventListener(i,n.dropLeave),e.addEventListener(a,n.dropEnd)},clean:()=>{let e=n.target;if(!e)return;let{start:t,move:r,leave:i,end:a}=Gt;e.removeEventListener(t,n.dropStart),e.removeEventListener(r,n.dropping),e.removeEventListener(i,n.dropLeave),e.removeEventListener(a,n.dropEnd),n.depth=0,n.active=!1},ref:e=>{if(e)return void n.mount(e);n.clean()}};return n},qt=e=>!!e.dataTransfer?.types.includes(`Files`),Jt=e=>new Promise(t=>e.readEntries(t)),Yt=async e=>{let t=e.createReader(),n=[],r=await Jt(t);for(;r.length>0;)n.push(...r),r=await Jt(t);return n},Xt=e=>new Promise(t=>e.file(t)),Zt=async(e,t,n)=>{let r=t===``?e.name:`${t}/${e.name}`;if(e.isFile)return void n.push({path:r,file:await Xt(e)});n.push({path:r,file:null});for(let t of await Yt(e))await Zt(t,r,n)},Qt=async e=>{let t=Array.from(e?.items??[]).map(e=>e.webkitGetAsEntry()).filter(e=>!!e),n=[];for(let e of t)await Zt(e,``,n);return n},$t=(e,t,n=()=>!0)=>{let r=Dt(),i=()=>r.begin(e,()=>!n()),a=()=>r.move(s.value[0],s.value[1]),o=()=>{let e=s.event.type===`drop`?r.read():null;r.end(),e!==null&&Qt(s.event.dataTransfer).then(n=>t(n,e))},s=Kt(()=>{s.isDropStart&&i(),s.isDropping&&a(),s.isDropEnd&&o()},qt);return s.ref},C={ask:`Ask me anything...`,brand:`Claude`,voice:`音声モード`,file:`ファイル`},w=[{id:`claude-fable-5`,label:`Fable 5`,desc:`最も困難な課題に`},{id:`claude-opus-5`,label:`Opus 5`,desc:`複雑なタスク向け`},{id:`claude-sonnet-5`,label:`Sonnet 5`,desc:`日常のタスクに最適`},{id:`claude-haiku-4-5`,label:`Haiku 4.5`,desc:`素早い回答に最適`}],T={w:376,left:12,top:12,bottom:16,minH:180},E=e(``),D={send:async()=>``,stream:{parse:()=>[],send:async()=>[]},icon:``,path:``,headers:{},hello:()=>({greet:``,title:``,desc:``,prompts:[]}),commands:()=>[],hints:()=>[],menu:{useOpen:()=>n(E),flip:e=>n=>{n.stopPropagation(),t(E,E.value===e?``:e)},close:()=>t(E,``)}},en=e=>void Object.assign(D,e),tn=(e,t=20,n=6)=>{let r=a(null);return i(()=>{let e=r.current;if(!e)return;e.style.height=`${t}px`;let i=Math.max(1,Math.round(e.scrollHeight/t));e.style.height=`${Math.min(i,n)*t}px`},[e]),r},nn=(()=>{let e=new le({linkify:!0,breaks:!0}),t=t=>e.render(t);return{render:t,plain:e=>{let n=document.createElement(`div`);return n.innerHTML=t(e),n.textContent?.trim()??``}}})(),O=e(!1),k=e([]),A=e(``),j=e([0,0]),rn=e(w[0].id),M=e(!1),N=e(!1),P=e(!1);let F=null;const an=()=>{let e=window.SpeechRecognition??window.webkitSpeechRecognition;if(!e)return null;let n=new e;return n.lang=`ja-JP`,n.continuous=!0,n.interimResults=!1,n.onresult=e=>{let n=``;for(let t=e.resultIndex;t<e.results.length;t++)e.results[t].isFinal&&(n+=e.results[t][0].transcript);n!==``&&t(A,A.value+n)},n.onend=()=>t(P,!1),n},on=()=>{if(P.value)return void F?.stop();F??=an(),F&&(F.start(),t(P,!0))};let I=[0,0,28,28];const sn=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),cn=()=>{let[e,t]=j.value,n=L.target.getBoundingClientRect();I=[n.left-e,n.top-t,n.width,n.height]},ln=()=>{let e=sn(L.offset[0],-I[0],window.innerWidth-I[2]-I[0]),n=sn(L.offset[1],-I[1],window.innerHeight-I[3]-I[1]);y(e,n,L.offset),t(j,[e,n])},L=Bt(()=>{L.isDragStart&&cn(),ln()}),un=()=>{y(0,0,L.offset),t(j,[0,0])},dn=()=>{let e=L.target;!e||!e.isConnected||(cn(),ln())},fn=()=>{r(()=>(dn(),window.addEventListener(`resize`,dn),()=>window.removeEventListener(`resize`,dn)),[])},pn=e=>`calc(max(${T.left}px, 100vw - ${T.w+T.left}px) + ${e}px)`,mn=e=>T.top+e,hn=e=>`max(${T.minH}px, min(calc(100dvh - ${T.top+T.left}px), calc(100dvh - ${T.top+T.bottom+e}px)))`,R=e(null),z=e(0),gn=(e,t)=>{if(t)return t;if(!e.startsWith(`/`))return[];let n=e.slice(1).trim().toLowerCase();return D.commands().filter(e=>e.name.toLowerCase().startsWith(n))},B=()=>{t(R,null),t(z,0)},V=async e=>{t(A,``),B();let n=await e.run();Array.isArray(n)&&t(R,n)},_n=e=>{if(!e.startsWith(`/`))return;let t=e.slice(1).trim().toLowerCase();return D.commands().find(e=>e.name.toLowerCase()===t)??gn(e,null)[0]},vn=e=>{if(e.nativeEvent?.isComposing)return!1;let n=gn(A.value,R.value);if(n.length===0)return!1;let r=z.value%n.length;return e.key===`ArrowDown`?(e.preventDefault(),t(z,(r+1)%n.length),!0):e.key===`ArrowUp`?(e.preventDefault(),t(z,(r-1+n.length)%n.length),!0):e.key===`Escape`?(e.preventDefault(),t(A,``),B(),!0):e.key===`Enter`&&(e.preventDefault(),V(n[r]),!0)},yn=(()=>{let e=e=>e.replace(/[^0-9A-Za-zぁ-んァ-ヴー一-龠々\s]/g,` `).replace(/\s+/g,` `).trim(),t=e=>{let t=document.createElement(`div`);return t.innerHTML=nn.render(e),t.querySelectorAll(`pre`).forEach(e=>e.remove()),t.textContent??``};return{lines:n=>t(n).split(`
|
|
2
|
+
`).map(e).filter(e=>e!==``)}})();let H=0,bn=[];const xn=[`Kyoko`,`O-Ren`,`Nanami`,`Ayumi`,`Haruka`,`Sayaka`,`Samantha`,`Zira`,`Aria`,`Jenny`,`Ava`,`Sonia`,`Google 日本語`,`Google US English`],Sn=[`Otoya`,`Ichiro`,`Keita`,`David`,`Mark`,`Guy`,`Alex`,`Daniel`,`Fred`,`Andrew`,`Brian`],Cn=()=>bn=speechSynthesis.getVoices(),wn=e=>{bn.length===0&&Cn();let t=bn.filter(t=>t.lang.replace(`_`,`-`).startsWith(e.slice(0,2)));return t.find(e=>xn.some(t=>e.name.includes(t)))??t.find(e=>!Sn.some(t=>e.name.includes(t)))??t[0]??null},Tn=e=>{(e.match(/[A-Za-z][0-9A-Za-z]*(?: (?:[0-9]+ )*[A-Za-z][0-9A-Za-z]*)*|(?:(?![A-Za-z]).)+/g)??[]).forEach(e=>{if(e.trim()===``)return;let t=new SpeechSynthesisUtterance(e);t.lang=/^[A-Za-z]/.test(e)?`en-US`:`ja-JP`,t.voice=wn(t.lang),speechSynthesis.speak(t)})};speechSynthesis.addEventListener(`voiceschanged`,Cn);const En=e=>{if(!N.value)return;let t=e.split(`
|
|
3
|
+
`).slice(0,-1).join(`
|
|
4
|
+
`),n=yn.lines(t);n.slice(H).forEach(Tn),H=n.length},Dn=e=>{N.value&&yn.lines(e).slice(H).forEach(Tn),H=0},On=()=>{H=0,speechSynthesis.cancel()},kn=()=>t(O,!0),An=()=>{un(),On(),B(),t(O,!1)},jn=()=>{if(O.value)return An();kn()},Mn=e=>{B(),t(A,e.target.value)},Nn=()=>{let e=A.value.trim();if(e===``||M.value)return;let n=_n(e);if(n)return void V(n);t(A,``),D.send({prompt:e})},Pn=e=>{vn(e)||e.key!==`Enter`||e.nativeEvent?.isComposing||e.shiftKey||(e.preventDefault(),Nn())},Fn=e=>()=>{let t=_n(e);if(t)return void V(t);D.send({prompt:e})},In=()=>{N.value&&On(),t(N,!N.value)},Ln=e=>{D.menu.close(),t(rn,e.id)},Rn=()=>l(`div`,{className:`flex shrink-0 items-start justify-between px-2`,children:[c(g,{name:u,size:50,className:`text-mute`}),l(`div`,{className:`flex items-center gap-2`,children:[c(`button`,{ref:L.ref,className:`flex h-7 w-7 cursor-grab touch-none select-none items-center justify-center rounded-full text-mute hover:bg-band hover:text-ink active:cursor-grabbing`,children:c(g,{name:d,size:20})}),c(`button`,{onClick:An,className:`flex h-7 w-7 cursor-pointer items-center justify-center rounded-full text-mute hover:bg-band hover:text-ink`,children:c(g,{name:p,size:20})})]})]}),zn=()=>{let e=D.hello();return l(`div`,{className:`flex h-full flex-col items-center justify-center px-3 text-center`,children:[c(g,{name:u,size:56,className:`mb-5 text-mute`}),c(`p`,{className:`text-mute`,children:e.greet}),c(`p`,{className:`mt-1 font-bold leading-[26px]`,children:e.title}),c(`p`,{className:`mt-3 text-mute`,children:e.desc}),c(`div`,{className:`-mx-6 mt-6 flex flex-wrap justify-center gap-1.5`,children:e.prompts.map(e=>l(`button`,{onClick:Fn(e.prompt??e.label),className:`flex cursor-pointer items-center gap-1 whitespace-nowrap rounded-full border border-edge bg-white px-2.5 py-1 text-[12px] leading-[16px] hover:bg-pale`,children:[e.icon&&c(g,{name:e.icon,size:14,color:e.color}),e.label]},e.label))})]})},Bn=({t:e})=>l(`div`,{className:`-mt-4 ml-3 flex max-w-full items-center rounded-lg border border-edge bg-band p-2`,children:[e.icon&&c(g,{name:e.icon,size:16}),c(`span`,{className:`mx-2 truncate text-[12px]`,children:e.label}),c(`button`,{className:`hidden ml-1 flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center rounded-full text-mute hover:bg-line`,children:c(g,{name:oe,size:16})})]}),Vn=({m:e})=>l(`div`,{className:`mr-7 flex flex-col items-start ${e.tools?.length?`mb-6`:``}`,children:[c(`div`,{className:`chat-md w-full rounded-xl border border-edge bg-white p-3 ${e.tools?.length?`pb-5`:``}`,dangerouslySetInnerHTML:{__html:nn.render(e.text)}}),e.tools?.map((e,t)=>c(Bn,{t:e},t))]}),Hn=({m:e})=>c(`div`,{className:`ml-7 min-w-0 whitespace-pre-wrap [overflow-wrap:anywhere] rounded-2xl border border-edge bg-band p-3`,children:e.text}),Un=()=>c(`div`,{className:`flex w-fit items-center rounded-lg border border-edge bg-white px-2 py-1 text-mute`,children:c(g,{name:oe,size:20,className:`animate-pulse`})}),Wn=()=>{let e=n(k),t=n(M),i=a(null);return r(()=>void i.current?.scrollTo(0,9e9),[e]),c(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:l(`div`,{ref:i,className:`flex h-full flex-col gap-5 overflow-y-auto px-2 pb-4 pt-10 text-[14px] leading-[22px]`,children:[e.length===0&&c(zn,{}),e.map((e,t)=>e.role===`user`?c(Hn,{m:e},t):c(Vn,{m:e},t)),t&&e[e.length-1]?.role===`user`&&c(Un,{})]})})},Gn=()=>{let e=n(A);return n(P)?c(`button`,{onClick:on,className:`flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center text-[#EA4335]`,children:c(g,{name:ne,size:20})}):e.trim()===``?c(`button`,{onClick:on,className:`flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center text-mute hover:text-ink`,children:c(g,{name:ee,size:20})}):c(`button`,{onClick:Nn,className:`flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center text-ink hover:text-[#4185F4]`,children:c(g,{name:te,size:20})})},Kn=()=>{let e=n(A),t=n(R),r=n(z),i=gn(e,t);return i.length===0?null:c(`div`,{className:`absolute inset-x-0 bottom-full z-10 mb-2 max-h-56 overflow-y-auto rounded-xl border border-edge bg-white py-1 shadow-[0_8px_24px_rgba(0,0,0,0.12)]`,children:i.map((e,n)=>l(`button`,{onClick:()=>void V(e),className:`flex w-full cursor-pointer items-center gap-3 px-3 py-1.5 text-left text-[12px] leading-[16px] ${n===r%i.length?`bg-band`:`hover:bg-pale`}`,children:[c(`span`,{className:`shrink-0 font-bold`,children:t?e.label??e.name:`/${e.name}`}),c(`span`,{className:`min-w-0 flex-1 truncate text-right text-mute`,children:e.desc})]},`${e.name}-${n}`))})},qn=()=>{let e=n(k),t=n(M)?[]:D.hints(e);return t.length===0?null:c(`div`,{className:`flex shrink-0 flex-wrap justify-end gap-1.5 pb-2`,children:t.map(e=>c(`button`,{onClick:()=>void V(e),className:`cursor-pointer rounded-full border border-edge bg-white px-2.5 py-1 text-[12px] leading-[16px] hover:bg-pale`,children:e.label??e.name},e.name))})},Jn=()=>{let e=n(A),t=n(rn),r=n(N),i=D.menu.useOpen(),a=tn(e),o=w.find(e=>e.id===t)??w[0];return l(`div`,{className:`relative shrink-0 rounded-xl border border-edge`,children:[c(Kn,{}),l(`label`,{className:`flex items-start gap-2 px-3 pb-7 pt-3`,children:[c(g,{name:h,size:20,className:`text-mute`}),c(`textarea`,{ref:a,rows:1,value:e,onChange:Mn,onKeyDown:Pn,placeholder:C.ask,className:`min-w-0 flex-1 resize-none overflow-y-auto bg-transparent text-[14px] leading-[20px] outline-none placeholder:text-mute`}),c(Gn,{})]}),l(`div`,{className:`flex h-9 items-center border-t border-line px-3 text-[12px]`,children:[l(`span`,{className:`relative flex`,children:[l(`button`,{onClick:D.menu.flip(`chat-model`),className:`flex cursor-pointer items-center gap-1`,children:[C.brand,` `,o.label,c(g,{name:ae,size:16,className:`text-mute`})]}),i===`chat-model`&&c(Ye,{align:`left`,cls:`w-64`,items:w,value:t,pick:Ln,check:ce})]}),l(`div`,{className:`ml-auto flex items-center gap-3`,children:[l(`button`,{onClick:In,className:`flex cursor-pointer items-center gap-1 ${r?`text-[#4185F4]`:``}`,children:[c(g,{name:re,size:18}),C.voice]}),l(`button`,{className:`flex cursor-pointer items-center gap-1`,children:[c(g,{name:ie,size:18}),C.file]})]})]})]})},Yn=()=>c(`button`,{onClick:jn,className:`flex h-8 w-8 shrink-0 cursor-pointer items-center justify-center rounded-full text-mute hover:bg-band hover:text-ink`,children:c(g,{name:u,size:22})}),Xn=()=>{fn();let[e,t]=n(j);return l(`div`,{className:`fixed z-50 flex w-[376px] max-w-[calc(100vw-24px)] flex-col rounded-2xl border border-line bg-white p-3 text-ink shadow-[0_8px_24px_rgba(0,0,0,0.12)]`,style:{left:pn(e),top:mn(t),height:hn(t)},children:[c(Rn,{}),c(Wn,{}),c(qn,{}),c(Jn,{})]})},Zn=()=>n(O)?c(Xn,{}):null,Qn=e=>({role:`agent`,text:e.text,tools:e.tools.map(e=>({icon:D.icon,label:`${e.server?`${e.server} - `:``}${e.name} (MCP)`}))}),$n=e=>t(k,e.flatMap(e=>[{role:`user`,text:e.prompt},Qn({text:e.reply,tools:e.tools.map(e=>({server:``,name:e}))})])),er=e=>e.map(e=>e.tools.length?`${e.text}\n`:e.text).join(`
|
|
5
|
+
`),tr=async e=>{if(M.value)return`busy: previous chat is still running`;let n=[...k.value,{role:`user`,text:e}];On(),t(k,n),t(M,!0);let r=await D.stream.send({prompt:e,path:D.path,model:rn.value,headers:D.headers},e=>{t(k,[...n,...e.items.map(Qn)]),En(er(e.items))});return Dn(er(r)),t(M,!1),`chat sent: ${e}`},nr=e=>{let t=[],n=``,r=[],i=()=>Math.floor(new Date().getHours()/6),a=r=>{let a=i(),o=n,s=t.find(e=>e.name===r&&e.part===a&&e.after===o);s&&(s.count+=1),s||t.push({name:r,part:a,after:o,count:1}),n=r,e.store.save({name:r,part:a,after:o})},o=e=>t.reduce((t,r)=>r.name===e?t+r.count*(r.part===i()?2:1)*(r.after===n?2:1):t,0),s=e=>[...e].sort((e,t)=>o(t.name)-o(e.name)),c=()=>(r.length===0&&(r=e.deck.map(e=>({...e,run:()=>(a(e.name),e.run())}))),s(r));return{commands:c,hello:()=>{let t=c(),n=t.filter(t=>e.starters().includes(t.name)),r=[...new Set([...e.pinned(),...n.map(e=>e.name)])].flatMap(e=>t.filter(t=>t.name===e));return{...e.greet,prompts:r.map(e=>({label:e.label??e.name,prompt:`/${e.name}`}))}},hints:t=>e.hinted(t).flatMap(e=>c().filter(t=>t.name===e)),prime:async()=>{t=await e.store.list()}}},rr=(e,t)=>e.map((n,r)=>{let i=e[r+1]?.seq??1/0;return{...n,names:t.filter(e=>e.seq>n.seq&&e.seq<i).map(e=>e.name)}}),ir=e=>e.replace(/\s+/g,` `).trim().slice(0,40),ar=e=>{let t=Math.max(0,(Date.now()-new Date(e).getTime())/1e3);return t<60?`たった今`:t<3600?`${Math.floor(t/60)} 分前`:t<86400?`${Math.floor(t/3600)} 時間前`:`${Math.floor(t/86400)} 日前`},or=e=>{let t=crypto.randomUUID(),n=0,r=[],i=()=>{t=crypto.randomUUID(),n=0,r=[],e.show([])},a=async()=>(await e.store.list()).map(e=>({...e,when:ar(e.updatedAt)})),o=async i=>{let a=await e.store.load(i),o=rr(a.talks,a.tools).map(e=>({prompt:e.prompt,reply:e.reply,tools:e.names}));t=i,n=[...a.talks,...a.tools].reduce((e,t)=>Math.max(e,t.seq),0),r=o.flatMap(e=>[{role:`user`,content:e.prompt},{role:`assistant`,content:e.reply}]),e.show(o)},s=(i,a,o=``)=>{let s=a.filter(e=>!e.error),c=s.map(e=>e.text).filter(e=>e!==``).join(`
|
|
6
|
+
|
|
7
|
+
`);if(c===``)return;let l=s.flatMap(e=>e.tools.map(e=>e.name));r=[...r,{role:`user`,content:i},{role:`assistant`,content:c}];let u=n+1;n=u+l.length,e.store.save(t,{title:ir(i),seq:u,prompt:i,reply:c,model:o,tools:l.map((e,t)=>({seq:u+1+t,name:e}))})};return{wrap:e=>({...e,send:async(t,n)=>{let i=await e.send({...t,messages:r.slice(-40)},n);return s(t.prompt,i,t.model),i}}),reset:i,load:o,list:a}},sr=()=>M.value,cr=()=>n(M),U={add:ue,arrowBack:de,arrowDropDown:fe,check:se,chevronRight:pe,closeIcon:f,cloud:me,deleteIcon:he,folder:ge,home:_e,keep:ve,keepFill:ye,leftPanelClose:be,leftPanelOpen:xe,menuIcon:Se,moreVert:Ce,redoIcon:we,schedule:Te,searchIcon:m,settings:Ee,help:De,keyboard:Oe,sync:ke,undoIcon:Ae,unfoldMore:je,visibilityOff:Me,createNewFolder:Ne,uploadFile:Pe,driveFolderUpload:Fe,edit:Ie,download:Le,info:Re,openInNew:ze,restoreFromTrash:Be,description:Ve},lr=({count:e,min:t,cls:n=``,children:r})=>c(`div`,{className:`grid gap-4 overflow-x-auto ${n}`,style:{gridTemplateColumns:`repeat(${e}, minmax(${t}px, 1fr))`},children:r}),ur=({c:e,click:t})=>l(`button`,{onClick:t,className:`relative flex h-full w-full cursor-pointer flex-col items-start rounded-xl border border-edge bg-white p-3 text-left hover:bg-pale`,children:[c(`span`,{className:`flex h-[30px] w-[30px] items-center justify-center rounded-md bg-band`,children:c(g,{name:e.icon??``,size:18,color:e.color})}),c(g,{name:U.add,size:16,className:`absolute right-3 top-3 text-mute`}),c(`span`,{className:`mt-2 w-full truncate text-[14px] leading-[17px]`,children:e.label})]}),dr=({c:e,click:t})=>l(`button`,{onClick:t,className:`flex h-12 w-full cursor-pointer items-center gap-3 rounded-xl border border-edge bg-white px-4 text-left hover:bg-pale`,children:[c(g,{name:e.icon??``,size:18,color:e.color}),c(`span`,{className:`truncate`,children:e.label}),c(g,{name:U.add,size:16,className:`ml-auto shrink-0 text-mute`})]}),fr=({cards:e,click:t,popup:n,count:r=4})=>l(s,{children:[c(lr,{count:r,min:it.card,cls:`hidden md:grid`,children:e.map(e=>l(`div`,{className:`relative`,children:[c(ur,{c:e,click:t(e)}),n(e)]},e.id))}),c(`div`,{className:`flex flex-col gap-2 md:hidden`,children:e.map(e=>l(`div`,{className:`relative`,children:[c(dr,{c:e,click:t(e)}),n(e)]},e.id))})]}),pr=e=>c(`section`,{className:`relative shrink-0 px-4 pt-3 md:pl-7 md:pr-9`,children:c(fr,{...e})}),mr=({drawer:e,close:t,dropRef:n,children:r})=>l(`div`,{ref:n,onClick:t,className:`flex h-dvh overflow-hidden bg-white font-medium text-ink`,children:[e&&c(`div`,{className:`fixed inset-0 z-30 bg-black/30 md:hidden`,onClick:t}),r]}),hr=({drop:e,from:t,children:n})=>c(`main`,{"data-drop":e,"data-drop-from":t,"data-drop-scope":``,className:`flex min-w-0 flex-1 flex-col overflow-y-auto pt-14 md:pt-0`,children:n}),gr=`flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-mute hover:bg-band hover:text-ink`,_r=`flex h-8 w-8 shrink-0 cursor-pointer items-center justify-center rounded-full text-mute hover:bg-band hover:text-ink`,vr=({icon:e,color:t,label:n,home:r,actions:i,drawer:a})=>l(`header`,{className:`fixed inset-x-0 top-0 z-20 flex h-14 items-center gap-1 bg-white pl-4 pr-3 md:hidden`,children:[l(`button`,{onClick:r,className:`flex min-w-0 flex-1 cursor-pointer items-center gap-3`,children:[c(g,{name:e,size:24,color:t}),c(`span`,{className:`truncate text-sm font-bold`,children:n})]}),l(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[i,c(`button`,{onClick:a,className:gr,children:c(g,{name:U.menuIcon,size:22})})]})]}),yr=({bar:e,open:t,title:n,back:r,expand:i,actions:a})=>l(`div`,{className:`mt-2.5 flex h-8 shrink-0 items-center gap-2 px-4 md:pl-7 md:pr-9`,children:[!e&&c(`button`,{onClick:t,className:`${_r} hidden md:flex`,children:c(g,{name:U.leftPanelOpen,size:20})}),!r&&c(`h1`,{className:`min-w-0 truncate font-bold`,children:n}),r&&l(`button`,{onClick:r,className:`flex min-w-0 cursor-pointer items-center gap-2 font-bold`,children:[c(g,{name:U.arrowBack,size:20,className:`text-mute`}),c(`span`,{className:`truncate`,children:n})]}),l(`div`,{className:`relative ml-auto flex shrink-0 items-center gap-1`,children:[i&&l(`button`,{onClick:i.click,className:`flex h-8 cursor-pointer items-center gap-1 rounded-lg px-2 hover:bg-band ${i.on?`text-ink`:`text-mute`}`,children:[c(`span`,{className:`hidden md:inline`,children:i.label}),c(g,{name:i.icon||U.unfoldMore,size:18})]}),a]})]}),br=({icon:e,size:t=20,click:n,children:r})=>l(`span`,{className:`relative hidden md:flex`,children:[c(`button`,{onClick:n,className:_r,children:c(g,{name:e,size:t})}),r]}),xr=({icon:e,size:t=20,click:n,children:r})=>l(`span`,{className:`relative flex`,children:[c(`button`,{onClick:n,className:gr,children:c(g,{name:e,size:t})}),r]}),Sr=U.moreVert,Cr=`STORAGE`,wr=`アップグレード`,Tr=`https://stripe.com`,Er=`ゴミ箱を空にしますか?中のアイテムは完全に削除されます`,Dr=[{id:`manage`,icon:U.cloud,label:`保存容量を管理`},{id:`empty`,icon:U.deleteIcon,label:`ゴミ箱を空にする`},{id:`refresh`,icon:U.sync,label:`使用状況を更新`}],Or=[{id:`undo`,icon:U.undoIcon,label:`直前の操作を元に戻す`},{id:`redo`,icon:U.redoIcon,label:`最後に元に戻した操作をやり直す`},{id:`settings`,icon:U.settings,label:`設定`,top:!0},{id:`help`,icon:U.help,label:`ヘルプ`},{id:`shortcuts`,icon:U.keyboard,label:`キーボードショートカット`}],kr=Or.slice(2).map(e=>({...e,top:!1})),Ar=U.visibilityOff,jr=(e,t,n)=>[{id:`band`,icon:Ar,label:e?`すべての${t}を非表示`:`すべての${t}を表示`},...n.map((e,t)=>t===0?{...e,top:!0}:e)],Mr=`flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-mute hover:bg-band hover:text-ink`,Nr=({icon:e,color:t,label:n,click:r})=>l(`button`,{onClick:r,className:`flex min-w-0 flex-1 cursor-pointer items-center gap-3`,children:[c(g,{name:e,size:24,color:t}),c(`span`,{className:`truncate text-sm font-bold`,children:n})]}),Pr=({storage:e,upgrade:t,menu:n,more:r})=>l(`div`,{className:`relative shrink-0 border-t border-line px-4 pb-4 pt-3`,children:[l(`div`,{className:`flex h-6 items-center gap-2 text-mute`,children:[c(g,{name:U.cloud,size:18}),c(`span`,{className:`tracking-wider`,children:Cr}),l(`span`,{className:`relative ml-auto flex`,children:[c(`button`,{onClick:r,className:`flex h-6 w-6 items-center justify-center rounded-full text-mute hover:bg-band`,children:c(g,{name:U.moreVert,size:16})}),n]})]}),c(`div`,{className:`mt-1.5 h-2 overflow-hidden rounded-full bg-line`,children:c(`div`,{className:`h-full rounded-full bg-fill`,style:{width:`${Math.min(100,e.used/e.total*100)}%`}})}),c(`p`,{className:`mt-1.5`,children:e.text}),c(`button`,{onClick:t,className:`mt-2.5 h-9 w-full cursor-pointer rounded-full border border-ink font-bold hover:bg-band`,children:wr})]}),Fr=({brand:e,bar:t,drawer:n,fold:r,close:i,press:a,storage:o,upgrade:s,menu:u,more:d,children:f})=>l(`nav`,{"data-drop-scope":``,onClick:a,className:`fixed inset-y-0 left-0 z-40 flex shrink-0 flex-col border-r border-line bg-pale transition-transform md:static md:translate-x-0 ${n?`translate-x-0`:`-translate-x-full`} ${t?``:`md:hidden`}`,style:{width:_.width},children:[l(`div`,{className:`flex h-15 shrink-0 items-center gap-1 pr-2 text-[14px]`,style:{paddingLeft:_.brand},children:[c(Nr,{...e}),c(`button`,{onClick:r,className:`${Mr} hidden md:flex`,children:c(g,{name:U.leftPanelClose,size:20})}),c(`button`,{onClick:i,className:`${Mr} md:hidden`,children:c(g,{name:U.leftPanelClose,size:20})})]}),c(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-2 pb-4`,children:f}),c(Pr,{storage:o,upgrade:s,menu:u,more:d})]}),Ir=e=>`flex w-full cursor-pointer items-center rounded-lg text-left text-[14px] text-mute ${e?`bg-band`:`hover:bg-band`}`,Lr=({open:e,turn:t})=>t?c(`button`,{onClick:t,className:`flex shrink-0 items-center justify-center`,style:{width:_.slot,height:_.slot},children:c(g,{name:U.chevronRight,size:_.slot,className:e?`rotate-90`:``})}):c(`span`,{className:`shrink-0`,style:{width:_.slot}}),Rr=({depth:e=0,on:t=!1,open:n,turn:r,icon:i,color:a,label:o,drop:s,mark:u,from:d,click:f,dclick:p,rclick:m,dragRef:h,children:ee})=>l(`div`,{ref:h,"data-drop":s,"data-drop-mark":u,"data-drop-from":d,onClick:e=>(f?.(e),r?.(e)),onDoubleClick:p,onContextMenu:m,className:Ir(t),style:{height:_.row,paddingLeft:e*_.indent},children:[c(Lr,{open:n,turn:r}),c(g,{name:i,size:_.icon,color:a}),c(`span`,{className:`min-w-0 flex-1 truncate ${t?`text-ink`:``}`,style:{marginLeft:_.gap},children:o}),ee]}),W={base:`/api/v1/storage`,trash:`.trash`,editors:[]},zr=e=>void Object.assign(W,e),G=e=>e.kind.startsWith(`folder`),Br=(e,t)=>e.name.localeCompare(t.name),Vr=(e,t)=>t.iso.localeCompare(e.iso),Hr=(e,t)=>{let n=e.filter(e=>e.parent===t&&!e.trashed);return[...n.filter(G).sort(Br),...n.filter(e=>!G(e)).sort(Br)]},Ur=(e,t)=>e.filter(e=>!e.trashed&&e.kind===t).sort(Vr),Wr=e=>e.filter(e=>!e.trashed&&!G(e)).sort(Vr).slice(0,12),Gr=e=>e.filter(e=>e.trashed),Kr=e=>e.filter(e=>!e.trashed&&!G(e)).sort((e,t)=>t.bytes-e.bytes),qr=(e,t)=>e.filter(e=>!e.trashed&&e.parent===t),Jr=e=>{let t=e.split(`/`).filter(Boolean);return t.map((e,n)=>({name:n===0&&e===W.trash?`ゴミ箱`:e,path:t.slice(0,n+1).join(`/`)}))},Yr=e=>e.filter(e=>!G(e)).reduce((e,t)=>e+t.bytes,0),Xr=e=>{let{files:t,parent:n,depth:r,expand:i,active:a,kinds:o,fold:u,enter:d,open:f,menu:p,rclick:m,drag:h}=e;return c(s,{children:Hr(t,n).map(t=>{let n=(o[t.kind]??o.file).icon;return G(t)?l(`div`,{children:[c(Rr,{depth:r,on:a===t.id,open:i.includes(t.id),turn:u(t.id),icon:o.folder.icon,label:t.name,drop:t.id,mark:t.id,click:d(t.id),rclick:m(t),dragRef:h(t.id,`tree`),children:p(t)}),i.includes(t.id)&&c(Xr,{...e,parent:t.id,depth:r+1})]},t.id):c(Rr,{depth:r,icon:n,label:t.name,drop:t.parent,click:d(t.parent),dclick:f(t),rclick:m(t),dragRef:h(t.id,`tree`),children:p(t)},t.id)})})},K=e(!1),Zr=e(null),Qr=e=>{e.stopPropagation(),t(K,!0)},$r=()=>t(K,!1),ei=e=>t(Zr,{x:e.clientX,y:e.clientY}),ti=()=>t(Zr,null),ni=()=>K.value,ri=()=>n(K),ii=()=>n(Zr),ai=e=>e.split(`/`).map(encodeURIComponent).join(`/`),oi=(e,t)=>e.then(e=>e.ok?e.json():t).catch(()=>t),q=e=>`${W.base}/${ai(e)}`,J={list(e=``){return oi(fetch(`${W.base}?prefix=${encodeURIComponent(e)}`),[])},get(e){return fetch(q(e))},put(e,t,n={}){let r=`?kind=${encodeURIComponent(n.kind??``)}&site=${encodeURIComponent(n.site??``)}`;return oi(fetch(q(e)+r,{method:`POST`,headers:n.type?{"Content-Type":n.type}:void 0,body:t}),{path:e,size:0,date:new Date().toISOString()})},move(e,t){return fetch(`${q(e)}?to=${encodeURIComponent(t)}`,{method:`PUT`})},remove(e){return fetch(q(e),{method:`DELETE`})}},Y=(e,t)=>t===``?e:`${t}/${e}`,si=e=>e.split(`/`).slice(0,-1).join(`/`),ci=e=>e.path.endsWith(`/`)?e.path.slice(0,-1):e.path,li=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`)).filter(e=>e!==W.trash),ui=e=>e.includes(`.`)?(e.split(`.`).pop()??``).toLowerCase():``,di=e=>{let t=ui(e);return t===`pdf`?`pdf`:t===`mp4`||t===`mov`||t===`webm`?`mp4`:t===`jpg`||t===`jpeg`||t===`png`||t===`gif`?`jpg`:t===`xlsx`||t===`xls`||t===`csv`?`xlsx`:`file`},fi=(e,t)=>{let n=ci(e),r=n.startsWith(`${W.trash}/`),i=r?n.slice(W.trash.length+1):n,a=i.split(`/`).pop(),o=e.kind??t?.kind??(e.path.endsWith(`/`)?`folder`:di(a)),s=o.startsWith(`folder`)?`—`:mt(e.size);return{owner:`自分`,...t,id:n,name:a,kind:o,date:pt(e.date),iso:e.date,size:s,bytes:e.size,parent:si(i),trashed:r}},X=(e,t,n,r=!1)=>_t(e,new Set(t.filter(e=>e.parent===n&&!!e.trashed===r).map(e=>e.name))),Z=e=>e.scan(`files/`),Q=(e,t)=>{let n=fi(t,e[`files/${ci(t)}`]);return e[`files/${n.id}`]=n,li(n.id).forEach(n=>{e[`files/${n}`]||(e[`files/${n}`]=fi({path:`${n}/`,size:0,date:t.date}))}),n},pi=async(e,t,n,r,i,a)=>{let o=X(n.replace(/^\.+/,``)||`無題のファイル`,Z(e),r),s=Y(o,r),c={path:t.startsWith(`folder`)?`${s}/`:s,size:i?.size??0,date:new Date().toISOString(),kind:t};return Q(e,c),Q(e,await J.put(c.path,i,{kind:t,site:a,type:i?.type}))},$=async(e,t,n=``)=>{let r=n;for(let n of t.split(`/`).filter(Boolean)){let t=e[`files/${Y(n,r)}`];r=t?.kind.startsWith(`folder`)?t.id:(await pi(e,`folder`,n,r,``)).id}return r},mi=async(e,t,n)=>{for(let{path:r,file:i}of t){let t=r.split(`/`).filter(Boolean),a=t.pop(),o=await $(e,t.join(`/`),n);i||await $(e,a,o),i&&await pi(e,di(a),a,o,i)}},hi=async(e,t)=>{let n=await J.list(),r=new Set;for(let e of n){let n=Q(t,e);r.add(n.id),li(n.id).forEach(e=>r.add(e))}Z(t).forEach(e=>!r.has(e.id)&&delete t[`files/${e.id}`]);let i=n.reduce((e,t)=>e+t.size,0);return t.storage={used:i/1048576,total:at,text:`15 GB 中 ${ht(i)} を使用`},`synced ${n.length} objects`},gi=async({id:e,dir:t},n)=>{let r=n[`files/${e}`];if(!r||r.trashed)return`not found: ${e}`;if(r.parent===t)return`already in ${t===``?`root`:t}`;if(r.kind.startsWith(`folder`)&&(t===e||t.startsWith(`${e}/`)))return`cannot move ${r.name} into itself`;let i=X(r.name,Z(n),t),a=Y(i,t);return await J.move(e,a),delete n[`files/${e}`],n[`files/${a}`]={...r,id:a,name:i,parent:t},Z(n).forEach(t=>{if(!t.id.startsWith(`${e}/`))return;delete n[`files/${t.id}`];let r={...t,id:a+t.id.slice(e.length),parent:a+t.parent.slice(e.length)};n[`files/${r.id}`]=r}),`moved ${i} to ${t===``?`root`:t}`},_i=async({id:e},t)=>{let n=t[`files/${e}`];if(!n)return`not found: ${e}`;if(n.trashed)return delete t[`files/${e}`],Z(t).forEach(n=>n.id.startsWith(`${e}/`)&&delete t[`files/${n.id}`]),await J.remove(e),`deleted ${n.name}`;let r=X(n.name,Z(t),n.parent,!0),i=Y(r,n.parent);return await J.move(e,`${W.trash}/${i}`),delete t[`files/${e}`],t[`files/${W.trash}/${i}`]={...n,id:`${W.trash}/${i}`,name:r,trashed:!0},Z(t).forEach(n=>{if(!n.id.startsWith(`${e}/`))return;delete t[`files/${n.id}`];let r={...n,id:`${W.trash}/${i}${n.id.slice(e.length)}`,parent:i+n.parent.slice(e.length),trashed:!0};t[`files/${r.id}`]=r}),`trashed ${n.name}`},vi=async({id:e},t)=>{let n=t[`files/${e}`];if(!n?.trashed)return`not trashed: ${e}`;let r=await $(t,n.parent),i=X(n.name,Z(t),r),a=Y(i,r);await J.move(e,a),delete t[`files/${e}`];let o={...n,id:a,name:i,parent:r};return delete o.trashed,t[`files/${a}`]=o,`restored ${i}`},yi=async({id:e,name:t},n)=>{let r=n[`files/${e}`];if(!r)return`not found: ${e}`;let i=t.replace(/^\.+/,``)||r.name,a=X(i,Z(n),r.parent),o=Y(a,r.parent);return await J.move(e,o),delete n[`files/${e}`],n[`files/${o}`]={...r,id:o,name:a},Z(n).forEach(t=>{if(!t.id.startsWith(`${e}/`))return;delete n[`files/${t.id}`];let r={...t,id:o+t.id.slice(e.length),parent:o+t.parent.slice(e.length)};n[`files/${r.id}`]=r}),`renamed to ${a}`},bi=async(e,t)=>{let n=Z(t).filter(e=>e.trashed);n.forEach(e=>delete t[`files/${e.id}`]);let r=await J.list(`${W.trash}/`);return await Promise.all(r.map(e=>J.remove(e.path))),`emptied ${n.length} items`},xi=e=>Yr(Z(e));export{Zn as AiChat,Yn as AiChatButton,pr as Band,Nr as Brand,fr as Cards,Xr as DriveTree,Ye as Drop,Lr as Fold,mr as Frame,lt as GB,br as HeadBtn,g as Icon,dt as KB,ut as MB,hr as Main,yr as MainHead,Sr as MoreIcon,Je as Pop,Rr as Row,ct as SP_BREAK,Fr as Side,We as Slot,xr as SpBtn,vr as SpHead,Pr as StorageBox,lr as Strip,gt as ago,li as ancestors,ei as atPoint,tt as band,rt as blue,D as chatConfig,An as closeChat,$r as closeDrawer,en as configureChat,zr as configureDrive,nr as createCommands,Wt as createFileDrag,$t as createFileDrop,or as createHistory,Dt as createOver,Jr as crumbSegs,Bt as dragEvent,W as driveConfig,Kt as dropEvent,$e as edge,bi as emptyTrash,Er as emptyTrashAsk,fi as entryOf,ui as extOf,nt as fill,qr as folderRows,X as freeName,it as grid,U as icons,ci as idOf,Xe as ink,sr as isChatBusy,ni as isDrawerOpen,G as isFolder,di as kindOf,Ur as kindRows,Qe as line,nn as markdown,Q as mirrorFile,$ as mkdirp,w as models,jr as moreItems,gi as moveFile,Ze as mute,ti as noPoint,kn as openChat,Qr as openDrawer,Or as pageMenu,et as pale,si as parentOf,Y as pathname,Ge as place,Ue as prev,at as quota,J as r2,Wr as recentRows,_i as removeFile,yi as renameFile,$n as restoreChat,vi as restoreFile,Ir as rowCls,tr as runChat,pi as saveFile,_ as side,mt as sizeOf,kr as spMenu,pt as stamp,He as stop,Dr as storageMenu,Cr as storageName,Kr as storageRows,mi as storeFiles,hi as syncFiles,Qn as toMsg,jn as toggleChat,Gr as trashRows,Hr as treeOf,_t as unique,wr as upgradeLabel,Tr as upgradeUrl,st as uploadAlert,ot as uploadMax,q as url,ht as usageOf,cr as useChatBusy,ri as useDrawer,ii as usePoint,xi as usedBytes,Yr as usedOf,y as vec2};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import { Route } from "./types.js";
|
|
1
|
+
import { ActionDef, Ai, Config, Define, Grant, Own, Peer, Route, Saved, Side } from "./types.js";
|
|
2
|
+
//#region src/client/sync.d.ts
|
|
3
|
+
declare const client: <T extends object>(ai: T, route?: Route) => T;
|
|
4
|
+
declare const hydrate: <T extends object>(ai: T, entries: Record<string, any>, wake?: (key: string, value: any) => any) => T;
|
|
5
|
+
//#endregion
|
|
2
6
|
//#region src/client/stream.d.ts
|
|
3
7
|
interface StreamTool {
|
|
4
8
|
server: string;
|
|
@@ -26,8 +30,4 @@ declare const createStream: (endpoint?: string) => {
|
|
|
26
30
|
send: (input: StreamSend, update?: (u: StreamUpdate) => void) => Promise<StreamItem[]>;
|
|
27
31
|
};
|
|
28
32
|
//#endregion
|
|
29
|
-
|
|
30
|
-
declare const client: <T extends object>(ai: T, route?: Route) => T;
|
|
31
|
-
declare const hydrate: <T extends object>(ai: T, entries: Record<string, any>, wake?: (key: string, value: any) => any) => T;
|
|
32
|
-
//#endregion
|
|
33
|
-
export { type Route, type StreamItem, type StreamSend, type StreamTool, type StreamUpdate, client, createStream, hydrate };
|
|
33
|
+
export { type ActionDef, type Ai, type Config, type Define, type Grant, type Own, type Peer, type Route, type Saved, type Side, type StreamItem, type StreamSend, type StreamTool, type StreamUpdate, client, createStream, hydrate };
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ALIAS as e,LLM_PATH as t}from"./const.js";import n from"y-partyserver/provider";const r=/^\[tool\] (?:(\S+) )?(\S+)$/,
|
|
2
|
-
`)){if(
|
|
1
|
+
import{ALIAS as e,LLM_PATH as t}from"./const.js";import n from"y-partyserver/provider";const r=new WeakSet,i=(t,i={})=>{if(r.has(t))return t;r.add(t);let{room:a=e,path:o=``,host:s=location.host,party:c=`v1`,synced:l}=i,u=t.open().data().doc,d=a?new n(s,a,u,{party:c,params:{path:o}}):null;return l&&(!d||d.synced?l():d.once(`synced`,()=>l())),t},a=(e,t,n=(e,t)=>t)=>{if(r.has(e))return e;r.add(e);let i=e;return i.open().tx(()=>Object.entries(t).forEach(([e,t])=>i[e]=n(e,t))),e},o=/^\[tool\] (?:(\S+) )?(\S+)$/,s=(e=t)=>{let n=e=>{let t=[{text:``,tools:[]}],n=!1;for(let r of e.split(`
|
|
2
|
+
`)){if(r.startsWith(`[usage]`))continue;let e=o.exec(r),i=t[t.length-1];if(e){i.tools.push({server:e[1]??``,name:e[2]}),n=!0;continue}if(!(n&&r.trim()===``)){if(n){t.push({text:r,tools:[]}),n=!1;continue}i.text=i.text===``?r:`${i.text}\n${r}`}}return t.map(e=>({...e,text:e.text.trim()})).filter(e=>e.text!==``||e.tools.length>0)};return{parse:n,send:async(t,r)=>{let{headers:i={},...a}=t,o=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`,...i},body:JSON.stringify(a)});if(!o.ok){let e=(await o.text()).replace(/\n/g,` `),t=[{text:e,tools:[],error:!0}];return r?.({items:t,delta:e,raw:e}),t}let s=o.body.getReader(),c=new TextDecoder,l=``;for(;;){let{done:e,value:t}=await s.read();if(e)break;let i=c.decode(t,{stream:!0});l+=i,r?.({items:n(l),delta:i,raw:l})}return n(l)}}};export{i as client,s as createStream,a as hydrate};
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
//#region src/hono/d1/types.d.ts
|
|
2
|
+
interface ChatTables {
|
|
3
|
+
chats: any;
|
|
4
|
+
talks: any;
|
|
5
|
+
tools: any;
|
|
6
|
+
habits: any;
|
|
7
|
+
}
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/hono/d1/routes.d.ts
|
|
10
|
+
type D1Database$1 = any;
|
|
11
|
+
interface ChatRouteInput {
|
|
12
|
+
db: (env: any) => D1Database$1;
|
|
13
|
+
sub: (c: any) => Promise<string> | string;
|
|
14
|
+
tables: ChatTables;
|
|
15
|
+
}
|
|
16
|
+
declare const chatLog: ({ db, sub, tables }: ChatRouteInput) => import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, {
|
|
17
|
+
"/chats": {
|
|
18
|
+
$get: {
|
|
19
|
+
output: null;
|
|
20
|
+
outputFormat: "json";
|
|
21
|
+
status: 401;
|
|
22
|
+
input: {};
|
|
23
|
+
} | {
|
|
24
|
+
output: {
|
|
25
|
+
[x: string]: any;
|
|
26
|
+
}[];
|
|
27
|
+
outputFormat: "json";
|
|
28
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
29
|
+
input: {};
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
} & {
|
|
33
|
+
"/chats/:chatId": {
|
|
34
|
+
$get: {
|
|
35
|
+
output: null;
|
|
36
|
+
outputFormat: "json";
|
|
37
|
+
status: 401;
|
|
38
|
+
input: {
|
|
39
|
+
param: {
|
|
40
|
+
chatId: string;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
} | {
|
|
44
|
+
output: {
|
|
45
|
+
talks: {
|
|
46
|
+
[x: string]: any;
|
|
47
|
+
}[];
|
|
48
|
+
tools: {
|
|
49
|
+
[x: string]: any;
|
|
50
|
+
}[];
|
|
51
|
+
};
|
|
52
|
+
outputFormat: "json";
|
|
53
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
54
|
+
input: {
|
|
55
|
+
param: {
|
|
56
|
+
chatId: string;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
} & {
|
|
62
|
+
"/chats/:chatId": {
|
|
63
|
+
$post: {
|
|
64
|
+
output: null;
|
|
65
|
+
outputFormat: "json";
|
|
66
|
+
status: 401;
|
|
67
|
+
input: {
|
|
68
|
+
param: {
|
|
69
|
+
chatId: string;
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
} | {
|
|
73
|
+
output: {
|
|
74
|
+
ok: true;
|
|
75
|
+
};
|
|
76
|
+
outputFormat: "json";
|
|
77
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
78
|
+
input: {
|
|
79
|
+
param: {
|
|
80
|
+
chatId: string;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
} & {
|
|
86
|
+
"/habits": {
|
|
87
|
+
$get: {
|
|
88
|
+
output: null;
|
|
89
|
+
outputFormat: "json";
|
|
90
|
+
status: 401;
|
|
91
|
+
input: {};
|
|
92
|
+
} | {
|
|
93
|
+
output: {
|
|
94
|
+
[x: string]: any;
|
|
95
|
+
}[];
|
|
96
|
+
outputFormat: "json";
|
|
97
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
98
|
+
input: {};
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
} & {
|
|
102
|
+
"/habits": {
|
|
103
|
+
$post: {
|
|
104
|
+
output: null;
|
|
105
|
+
outputFormat: "json";
|
|
106
|
+
status: 401;
|
|
107
|
+
input: {};
|
|
108
|
+
} | {
|
|
109
|
+
output: {
|
|
110
|
+
ok: true;
|
|
111
|
+
};
|
|
112
|
+
outputFormat: "json";
|
|
113
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
114
|
+
input: {};
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
}, "/", "/habits">;
|
|
118
|
+
//#endregion
|
|
119
|
+
//#region src/hono/d1/queries.d.ts
|
|
120
|
+
type D1Database = any;
|
|
121
|
+
declare const createChatLog: (t: ChatTables) => {
|
|
122
|
+
listChats: (DB: D1Database, userId: string) => Omit<import("drizzle-orm/sqlite-core").SQLiteSelectBase<any, "async", any, any, "single", Record<any, "not-null"> | {}, false, "limit" | "orderBy" | "where", {
|
|
123
|
+
[x: string]: any;
|
|
124
|
+
}[], any>, "limit" | "orderBy" | "where">;
|
|
125
|
+
getChatLog: (DB: D1Database, userId: string, chatId: string) => Promise<[{
|
|
126
|
+
[x: string]: any;
|
|
127
|
+
}[], {
|
|
128
|
+
[x: string]: any;
|
|
129
|
+
}[]]>;
|
|
130
|
+
saveTalk: (DB: D1Database, userId: string, chatId: string, body: any) => Promise<any[]>;
|
|
131
|
+
listHabits: (DB: D1Database, userId: string) => Omit<import("drizzle-orm/sqlite-core").SQLiteSelectBase<any, "async", any, any, "single", Record<any, "not-null"> | {}, false, "where", {
|
|
132
|
+
[x: string]: any;
|
|
133
|
+
}[], any>, "where">;
|
|
134
|
+
bumpHabit: (DB: D1Database, userId: string, body: any) => import("drizzle-orm/sqlite-core").SQLiteInsertBase<any, "async", D1Result, undefined, false, never>;
|
|
135
|
+
};
|
|
136
|
+
//#endregion
|
|
137
|
+
export { type ChatRouteInput, type ChatTables, chatLog, createChatLog };
|
package/dist/hono/d1.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Hono as e}from"hono";import{drizzle as t}from"drizzle-orm/d1";import{and as n,desc as r,eq as i,sql as a}from"drizzle-orm";const o=e=>({listChats:(n,a)=>t(n).select().from(e.chats).where(i(e.chats.userId,a)).orderBy(r(e.chats.updatedAt)).limit(30),getChatLog:(r,a,o)=>{let s=t(r);return s.batch([s.select().from(e.talks).where(n(i(e.talks.userId,a),i(e.talks.chatId,o))).orderBy(e.talks.seq),s.select().from(e.tools).where(n(i(e.tools.userId,a),i(e.tools.chatId,o))).orderBy(e.tools.seq)])},saveTalk:(n,r,i,a)=>{let o=t(n),s=(a.tools??[]).map(e=>({userId:r,chatId:i,seq:e.seq,name:e.name}));return o.batch([o.insert(e.chats).values({userId:r,chatId:i,title:a.title}).onConflictDoUpdate({target:[e.chats.userId,e.chats.chatId],set:{updatedAt:new Date}}),o.insert(e.talks).values({userId:r,chatId:i,seq:a.seq,prompt:a.prompt,reply:a.reply,model:a.model}).onConflictDoNothing(),...s.length?[o.insert(e.tools).values(s).onConflictDoNothing()]:[]])},listHabits:(n,r)=>t(n).select().from(e.habits).where(i(e.habits.userId,r)),bumpHabit:(n,r,i)=>t(n).insert(e.habits).values({userId:r,name:i.name,part:i.part,after:i.after}).onConflictDoUpdate({target:[e.habits.userId,e.habits.name,e.habits.part,e.habits.after],set:{count:a`${e.habits.count} + 1`,updatedAt:new Date}})}),s=({db:t,sub:n,tables:r})=>{let i=o(r);return new e().get(`/chats`,async e=>{let r=await n(e);return r?e.json(await i.listChats(t(e.env),r)):e.json(null,401)}).get(`/chats/:chatId`,async e=>{let r=await n(e);if(!r)return e.json(null,401);let[a,o]=await i.getChatLog(t(e.env),r,e.req.param(`chatId`));return e.json({talks:a,tools:o})}).post(`/chats/:chatId`,async e=>{let r=await n(e);return r?(await i.saveTalk(t(e.env),r,e.req.param(`chatId`),await e.req.json()),e.json({ok:!0})):e.json(null,401)}).get(`/habits`,async e=>{let r=await n(e);return r?e.json(await i.listHabits(t(e.env),r)):e.json(null,401)}).post(`/habits`,async e=>{let r=await n(e);return r?(await i.bumpHabit(t(e.env),r,await e.req.json()),e.json({ok:!0})):e.json(null,401)})};export{s as chatLog,o as createChatLog};
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
//#region src/hono/r2/store.d.ts
|
|
2
|
+
interface Obj {
|
|
3
|
+
path: string;
|
|
4
|
+
size: number;
|
|
5
|
+
date: string;
|
|
6
|
+
kind?: string;
|
|
7
|
+
etag?: string;
|
|
8
|
+
}
|
|
9
|
+
type R2Bucket$2 = any;
|
|
10
|
+
declare const createR2: (bucket: R2Bucket$2) => {
|
|
11
|
+
list: (sub: string, prefix?: string, cursor?: string) => Promise<Obj[]>;
|
|
12
|
+
get: (sub: string, path: string) => any;
|
|
13
|
+
head: (sub: string, path: string) => any;
|
|
14
|
+
put(sub: string, path: string, body: any, meta?: any): Promise<Obj>;
|
|
15
|
+
move(sub: string, from: string, to: string): Promise<void>;
|
|
16
|
+
remove(sub: string, path: string): Promise<void>;
|
|
17
|
+
};
|
|
18
|
+
type Store = ReturnType<typeof createR2>;
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/hono/r2/routes.d.ts
|
|
21
|
+
type R2Bucket$1 = any;
|
|
22
|
+
interface RouteInput {
|
|
23
|
+
bucket: (env: any) => R2Bucket$1;
|
|
24
|
+
sub: (c: any) => Promise<string> | string;
|
|
25
|
+
}
|
|
26
|
+
declare const storage: ({ bucket, sub }: RouteInput) => import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, {
|
|
27
|
+
"/": {
|
|
28
|
+
$get: {
|
|
29
|
+
output: null;
|
|
30
|
+
outputFormat: "json";
|
|
31
|
+
status: 401;
|
|
32
|
+
input: {
|
|
33
|
+
query: {
|
|
34
|
+
prefix: string | string[];
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
} | {
|
|
38
|
+
output: {
|
|
39
|
+
path: string;
|
|
40
|
+
size: number;
|
|
41
|
+
date: string;
|
|
42
|
+
kind?: string;
|
|
43
|
+
etag?: string;
|
|
44
|
+
}[];
|
|
45
|
+
outputFormat: "json";
|
|
46
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
47
|
+
input: {
|
|
48
|
+
query: {
|
|
49
|
+
prefix: string | string[];
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
} & {
|
|
55
|
+
"/:path{.+}": {
|
|
56
|
+
$get: {
|
|
57
|
+
output: {};
|
|
58
|
+
outputFormat: "body";
|
|
59
|
+
status: 200;
|
|
60
|
+
input: {
|
|
61
|
+
param: {
|
|
62
|
+
path: string;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
} | {
|
|
66
|
+
output: null;
|
|
67
|
+
outputFormat: "json";
|
|
68
|
+
status: 401;
|
|
69
|
+
input: {
|
|
70
|
+
param: {
|
|
71
|
+
path: string;
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
} | {
|
|
75
|
+
output: "Not Found";
|
|
76
|
+
outputFormat: "text";
|
|
77
|
+
status: 404;
|
|
78
|
+
input: {
|
|
79
|
+
param: {
|
|
80
|
+
path: string;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
} & {
|
|
86
|
+
"/:path{.+}": {
|
|
87
|
+
$post: {
|
|
88
|
+
output: null;
|
|
89
|
+
outputFormat: "json";
|
|
90
|
+
status: 401;
|
|
91
|
+
input: {
|
|
92
|
+
query: {
|
|
93
|
+
kind: string | string[];
|
|
94
|
+
site: string | string[];
|
|
95
|
+
};
|
|
96
|
+
} & {
|
|
97
|
+
param: {
|
|
98
|
+
path: string;
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
} | {
|
|
102
|
+
output: {
|
|
103
|
+
path: string;
|
|
104
|
+
size: number;
|
|
105
|
+
date: string;
|
|
106
|
+
kind?: string;
|
|
107
|
+
etag?: string;
|
|
108
|
+
};
|
|
109
|
+
outputFormat: "json";
|
|
110
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
111
|
+
input: {
|
|
112
|
+
query: {
|
|
113
|
+
kind: string | string[];
|
|
114
|
+
site: string | string[];
|
|
115
|
+
};
|
|
116
|
+
} & {
|
|
117
|
+
param: {
|
|
118
|
+
path: string;
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
};
|
|
123
|
+
} & {
|
|
124
|
+
"/:path{.+}": {
|
|
125
|
+
$put: {
|
|
126
|
+
output: null;
|
|
127
|
+
outputFormat: "json";
|
|
128
|
+
status: 401;
|
|
129
|
+
input: {
|
|
130
|
+
query: {
|
|
131
|
+
to: string | string[];
|
|
132
|
+
};
|
|
133
|
+
} & {
|
|
134
|
+
param: {
|
|
135
|
+
path: string;
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
} | {
|
|
139
|
+
output: {
|
|
140
|
+
ok: true;
|
|
141
|
+
};
|
|
142
|
+
outputFormat: "json";
|
|
143
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
144
|
+
input: {
|
|
145
|
+
query: {
|
|
146
|
+
to: string | string[];
|
|
147
|
+
};
|
|
148
|
+
} & {
|
|
149
|
+
param: {
|
|
150
|
+
path: string;
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
} & {
|
|
156
|
+
"/:path{.+}": {
|
|
157
|
+
$delete: {
|
|
158
|
+
output: null;
|
|
159
|
+
outputFormat: "json";
|
|
160
|
+
status: 401;
|
|
161
|
+
input: {
|
|
162
|
+
param: {
|
|
163
|
+
path: string;
|
|
164
|
+
};
|
|
165
|
+
};
|
|
166
|
+
} | {
|
|
167
|
+
output: {
|
|
168
|
+
ok: true;
|
|
169
|
+
};
|
|
170
|
+
outputFormat: "json";
|
|
171
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
172
|
+
input: {
|
|
173
|
+
param: {
|
|
174
|
+
path: string;
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
}, "/", "/:path{.+}">;
|
|
180
|
+
//#endregion
|
|
181
|
+
//#region src/hono/r2/utils.d.ts
|
|
182
|
+
declare const MAX_PATH = 512;
|
|
183
|
+
declare const MAX_WRITE = 5242880;
|
|
184
|
+
type R2Bucket = any;
|
|
185
|
+
declare const normalize: (path: string) => string;
|
|
186
|
+
declare const binary: (text: string) => boolean;
|
|
187
|
+
declare const mime: (path: string) => string;
|
|
188
|
+
declare const putObject: (bucket: R2Bucket, key: string, body: any, meta?: {
|
|
189
|
+
type?: string;
|
|
190
|
+
kind?: string;
|
|
191
|
+
site?: string;
|
|
192
|
+
}) => any;
|
|
193
|
+
//#endregion
|
|
194
|
+
export { MAX_PATH, MAX_WRITE, type Obj, type RouteInput, type Store, binary, createR2, mime, normalize, putObject, storage };
|
package/dist/hono/r2.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Hono as e}from"hono";import{validator as t}from"hono/validator";const n=512,r=5242880,i=e=>Array.from(e).some(e=>e.charCodeAt(0)<32),a=e=>e===`..`||e.startsWith(`.`)||i(e),o=e=>{if(typeof e!=`string`||e.length>512)return``;let t=e.split(`/`).filter(e=>e!==``&&e!==`.`);return t.length===0||t.some(a)?``:t.join(`/`)},s=e=>Array.from(e.slice(0,4096)).some(e=>e.charCodeAt(0)===0),c={html:`text/html;charset=utf-8`,htm:`text/html;charset=utf-8`,svg:`image/svg+xml;charset=utf-8`,css:`text/css;charset=utf-8`,js:`text/javascript;charset=utf-8`,mjs:`text/javascript;charset=utf-8`,json:`application/json;charset=utf-8`,md:`text/markdown;charset=utf-8`,csv:`text/csv;charset=utf-8`,xml:`application/xml;charset=utf-8`,yaml:`text/yaml;charset=utf-8`,yml:`text/yaml;charset=utf-8`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,mp4:`video/mp4`,webm:`video/webm`,mp3:`audio/mpeg`,wav:`audio/wav`,pdf:`application/pdf`,wasm:`application/wasm`},l=e=>c[(e.split(`.`).pop()??``).toLowerCase()]??`text/plain;charset=utf-8`,u=(e,t,n,r={})=>{let i={};return r.kind&&(i.kind=r.kind),r.site&&(i.site=r.site),e.put(t,n,{httpMetadata:r.type?{contentType:r.type}:void 0,customMetadata:Object.keys(i).length?i:void 0})},d=e=>{let t=(e,t)=>`${e}/${t}`,n=(e,t)=>({path:t.key.slice(e.length+1),size:t.size,date:t.uploaded.toISOString(),kind:t.customMetadata?.kind,etag:t.etag}),r=async(i,a=``,o)=>{let s=await e.list({prefix:t(i,a),include:[`customMetadata`],cursor:o}),c=s.objects.map(e=>n(i,e));return s.truncated?[...c,...await r(i,a,s.cursor)]:c};return{list:r,get:(n,r)=>e.get(t(n,r)),head:(n,r)=>e.head(t(n,r)),async put(r,i,a,o={}){return n(r,await u(e,t(r,i),a,o))},async move(n,i,a){let o=(await r(n,i)).filter(e=>e.path===i||e.path.startsWith(`${i}/`));for(let r of o){let o=await e.get(t(n,r.path));o&&(await e.put(t(n,a+r.path.slice(i.length)),o.body,{httpMetadata:o.httpMetadata,customMetadata:o.customMetadata}),await e.delete(t(n,r.path)))}},async remove(n,i){let a=(await r(n,i)).filter(e=>e.path===i||e.path.startsWith(`${i}/`));await Promise.all(a.map(r=>e.delete(t(n,r.path))))}}},f=e=>typeof e==`string`?e:``,p=({bucket:n,sub:r})=>new e().get(`/`,t(`query`,e=>({prefix:f(e.prefix)})),async e=>{let t=await r(e);return t?e.json(await d(n(e.env)).list(t,e.req.valid(`query`).prefix)):e.json(null,401)}).get(`/:path{.+}`,async e=>{let t=await r(e);if(!t)return e.json(null,401);let i=await d(n(e.env)).get(t,e.req.param(`path`));return i?e.body(i.body,200,{"Content-Type":i.httpMetadata?.contentType??`application/octet-stream`}):e.text(`Not Found`,404)}).post(`/:path{.+}`,t(`query`,e=>({kind:f(e.kind),site:f(e.site)})),async e=>{let t=await r(e);if(!t)return e.json(null,401);let{kind:i,site:a}=e.req.valid(`query`);return e.json(await d(n(e.env)).put(t,e.req.param(`path`),await e.req.arrayBuffer(),{type:e.req.header(`Content-Type`),kind:i,site:a}))}).put(`/:path{.+}`,t(`query`,e=>({to:f(e.to)})),async e=>{let t=await r(e);return t?(await d(n(e.env)).move(t,e.req.param(`path`),e.req.valid(`query`).to),e.json({ok:!0})):e.json(null,401)}).delete(`/:path{.+}`,async e=>{let t=await r(e);return t?(await d(n(e.env)).remove(t,e.req.param(`path`)),e.json({ok:!0})):e.json(null,401)});export{n as MAX_PATH,r as MAX_WRITE,s as binary,d as createR2,l as mime,o as normalize,u as putObject,p as storage};
|
package/dist/hono.d.ts
CHANGED
package/dist/hono.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{PATH_HEADER as e,SUB_HEADER as t}from"./const.js";import{createMiddleware as n}from"hono/factory";import r from"@auth/core/providers/google";import{decode as i,encode as a}from"@auth/core/jwt";import{getAuthUser as o,initAuthConfig as s}from"@hono/auth-js";import{env as c}from"hono/adapter";import{streamText as l}from"hono/streaming";import{StreamableHTTPTransport as u}from"@hono/mcp";import{McpServer as d}from"@modelcontextprotocol/sdk/server/mcp.js";import{getServerByName as f,routePartykitRequest as p}from"partyserver";const m=`authjs.mcp-token`,h=e=>s(t=>{let n=new URL(t.req.url).host
|
|
2
|
-
`);u=f.pop()??``;for(let e of f){let c=y(e);if(c){if(c.type===`message_start`){let e=c.message?.usage??{};i+=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),a+=e.cache_read_input_tokens??0}c.type===`message_delta`&&(o=c.usage?.output_tokens??o,s=c.delta?.stop_reason??s),c.type===`content_block_start`&&(r={...c.content_block},n.push(r),r.type===`mcp_tool_use`&&await t(`\n[tool] ${r.server_name} ${r.name}\n`)),c.type===`content_block_delta`&&c.delta?.type===`text_delta`&&(r.text=(r.text??``)+c.delta.text,await t(c.delta.text)),c.type===`content_block_delta`&&c.delta?.type===`input_json_delta`&&(r.partial=(r.partial??``)+c.delta.partial_json),c.type===`content_block_delta`&&c.delta?.type===`thinking_delta`&&(r.thinking=(r.thinking??``)+c.delta.thinking),c.type===`content_block_delta`&&c.delta?.type===`signature_delta`&&(r.signature=(r.signature??``)+c.delta.signature),c.type===`content_block_stop`&&r?.partial!==void 0&&(r.input=r.partial?JSON.parse(r.partial):{},delete r.partial)}}}return{blocks:n,input:i,cached:a,output:o,stop:s}},S=async(e,t,n,r,i,a=10)=>{let o=r,s=0,c=0,l=0,u=``;for(let r=0;r<a;r++){let r=await x(o,i);if(s+=r.input,c+=r.cached,l+=r.output,u=r.stop||u,u!==`pause_turn`)break;if(n.push({role:`assistant`,content:r.blocks.filter(e=>e.type!==`thinking`||e.thinking||e.signature)}),o=await b(e,await t(),n),!o.ok){await i(`\n[error] ${(await o.text()).replace(/\n/g,` `)}\n`);break}}await i(`\n[usage] input ${s} (cache ${c}) / output ${l} tokens (${u})\n`)},C=e=>n(async t=>{let n=await g(t),{path:r=``,prompt:i,model:a=``,messages:o=[]}=await t.req.json(),s=!!e.lobby&&!r;if(!s&&!n)return t.text(`Unauthorized`,401);if(!s&&!await(e.own??(()=>``))({env:c(t),sub:n,path:r}))return t.text(`Forbidden`,403);let u=e.host??t.req.header(`x-original-host`)??t.req.header(`x-forwarded-host`)??new URL(t.req.url).host,d={key:c(t)
|
|
1
|
+
import{PATH_HEADER as e,SUB_HEADER as t}from"./const.js";import{createMiddleware as n}from"hono/factory";import r from"@auth/core/providers/google";import{decode as i,encode as a}from"@auth/core/jwt";import{getAuthUser as o,initAuthConfig as s}from"@hono/auth-js";import{env as c}from"hono/adapter";import{streamText as l}from"hono/streaming";import{StreamableHTTPTransport as u}from"@hono/mcp";import{McpServer as d}from"@modelcontextprotocol/sdk/server/mcp.js";import{getServerByName as f,routePartykitRequest as p}from"partyserver";const m=`authjs.mcp-token`,h=e=>s(t=>{let n=String(e.domain?.(t.env)??``),i=n.indexOf(`.`),a=i>=0&&new URL(t.req.url).host.endsWith(n),o=n.slice(0,i),s={sessionToken:{...o?{name:`authjs.session-token${o}`}:{},options:{domain:n.slice(i)}}},c=e.providers??[r({clientId:t.env.GOOGLE_CLIENT_ID,clientSecret:t.env.GOOGLE_CLIENT_SECRET})];return{...e.adapter?{adapter:e.adapter(t.env)}:{},providers:c,secret:e.secret?.(t.env)??t.env.AUTH_SECRET,session:{strategy:`jwt`},...a?{cookies:s}:{}}}),g=async e=>(await o(e))?.token?.sub??``,_=(e,t,n,r)=>a({token:{sub:t,path:n},secret:r?.secret?.(c(e))??c(e).AUTH_SECRET,salt:r?.salt??m,maxAge:r?.maxAge??43200}),v=async(e,t)=>{let n=(e.req.header(`Authorization`)??``).replace(/^Bearer\s+/i,``);if(!n)return null;let r=await i({token:n,secret:t?.secret?.(c(e))??c(e).AUTH_SECRET,salt:t?.salt??m}).catch(()=>null);return{sub:r?.sub??``,path:r?.path??``}},y=e=>e.startsWith(`data:`)?JSON.parse(e.slice(5)):null,b=(e,t,n)=>fetch(e.api,{method:`POST`,headers:{"x-api-key":e.key,"anthropic-version":`2023-06-01`,"anthropic-beta":`mcp-client-2025-11-20`,"content-type":`application/json`},body:JSON.stringify({model:e.model,max_tokens:e.maxTokens,stream:!0,cache_control:{type:`ephemeral`},system:e.system,mcp_servers:[{type:`url`,url:e.url,name:e.name,...t?{authorization_token:t}:{}}],tools:[{type:`mcp_toolset`,mcp_server_name:e.name}],messages:n})}),x=async(e,t)=>{let n=[],r=null,i=0,a=0,o=0,s=``,c=e.body.getReader(),l=new TextDecoder,u=``;for(;;){let{done:e,value:d}=await c.read();if(e)break;u+=l.decode(d,{stream:!0});let f=u.split(`
|
|
2
|
+
`);u=f.pop()??``;for(let e of f){let c=y(e);if(c){if(c.type===`message_start`){let e=c.message?.usage??{};i+=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),a+=e.cache_read_input_tokens??0}c.type===`message_delta`&&(o=c.usage?.output_tokens??o,s=c.delta?.stop_reason??s),c.type===`content_block_start`&&(r={...c.content_block},n.push(r),r.type===`mcp_tool_use`&&await t(`\n[tool] ${r.server_name} ${r.name}\n`)),c.type===`content_block_delta`&&c.delta?.type===`text_delta`&&(r.text=(r.text??``)+c.delta.text,await t(c.delta.text)),c.type===`content_block_delta`&&c.delta?.type===`input_json_delta`&&(r.partial=(r.partial??``)+c.delta.partial_json),c.type===`content_block_delta`&&c.delta?.type===`thinking_delta`&&(r.thinking=(r.thinking??``)+c.delta.thinking),c.type===`content_block_delta`&&c.delta?.type===`signature_delta`&&(r.signature=(r.signature??``)+c.delta.signature),c.type===`content_block_stop`&&r?.partial!==void 0&&(r.input=r.partial?JSON.parse(r.partial):{},delete r.partial)}}}return{blocks:n,input:i,cached:a,output:o,stop:s}},S=async(e,t,n,r,i,a=10)=>{let o=r,s=0,c=0,l=0,u=``;for(let r=0;r<a;r++){let r=await x(o,i);if(s+=r.input,c+=r.cached,l+=r.output,u=r.stop||u,u!==`pause_turn`)break;if(n.push({role:`assistant`,content:r.blocks.filter(e=>e.type!==`thinking`||e.thinking||e.signature)}),o=await b(e,await t(),n),!o.ok){await i(`\n[error] ${(await o.text()).replace(/\n/g,` `)}\n`);break}}await i(`\n[usage] input ${s} (cache ${c}) / output ${l} tokens (${u})\n`)},C=e=>n(async t=>{let n=await g(t),{path:r=``,prompt:i,model:a=``,messages:o=[]}=await t.req.json(),s=!!e.lobby&&!r;if(!s&&!n)return t.text(`Unauthorized`,401);if(!s&&!await(e.own??(()=>``))({env:c(t),sub:n,path:r}))return t.text(`Forbidden`,403);let u=e.host??t.req.header(`x-original-host`)??t.req.header(`x-forwarded-host`)??new URL(t.req.url).host,d={key:e.apiKey?.(c(t))??``,api:e.claude??`https://api.anthropic.com/v1/messages`,name:e.name??`aiax`,url:`https://${u}${e.endpoint??`/api/mcp`}`,model:a||e.model||`claude-sonnet-5`,system:e.system??``,maxTokens:e.maxTokens??32e3},f=()=>s?Promise.resolve(``):_(t,n,r,e),p=[...o,{role:`user`,content:i}],m=await b(d,await f(),p);return m.ok?l(t,t=>S(d,f,p,m,e=>t.write(e),e.maxTurns??10)):t.text(await m.text(),500)}),w=async(n,r,i,a,o)=>{let s=await f(n,r),c={[t]:i.sub,[e]:encodeURIComponent(i.path)};return(await s.fetch(`https://internal/act`,{method:`POST`,headers:c,body:JSON.stringify({name:a,input:o})})).json()},T=(e,t)=>n(async n=>{let r=await v(n,t),i=r?.sub??``,a=r?.path??``,o=t.lobby??``;if(r||!o){if(!i)return n.text(`Unauthorized`,401);if(o=await(t.own??(()=>``))({env:c(n),sub:i,path:a}),!o)return n.text(`Forbidden`,403)}let s=new d({name:t.name??`aiax`,version:t.version??`1.0.0`}),l=new u;return e.actions.forEach((e,r)=>s.registerTool(r,{description:e.description,inputSchema:{...e.input}},async e=>{let s=await w(c(n)[t.binding??`v1`],o,{sub:i,path:a},r,e);return{content:[{type:`text`,text:JSON.stringify(s)}]}})),await s.connect(l),l.handleRequest(n)}),E=async(n,r,i,a)=>{let o=new Headers(n.req.raw.headers);o.set(t,i),o.set(e,encodeURIComponent(a));let s=new URL(n.req.url),l=s.pathname.split(`/`);l[3]=encodeURIComponent(r),s.pathname=l.join(`/`);let u=new Request(s,new Request(n.req.raw,{headers:o}));return await p(u,c(n))??n.text(`Not Found`,404)},D=e=>n(async t=>{let n=decodeURIComponent(t.req.path.split(`/`)[3]??``),r=t.req.query(`path`)??``,i=await g(t);if(e.lobby&&n===e.lobby)return E(t,n,i,r);if(!i)return t.text(`Unauthorized`,401);let a=await(e.own??(()=>``))({env:c(t),sub:i,path:r});return!a||n!==a&&n!==(e.alias??`my-room`)?t.text(`Forbidden`,403):E(t,a,i,r)}),O=(e,t={})=>{let r=Object.assign(e.config,t),i={auth:h(r),party:D(r),mcp:T(e,r),llm:C(r)};return n(async(e,t)=>{let n=()=>e.req.path.startsWith(`/parties/`)?i.party(e,t):e.req.path===(r.endpoint??`/api/mcp`)?i.mcp(e,t):e.req.path===(r.relay??`/api/llm`)&&e.req.method===`POST`?i.llm(e,t):t(),a;if(await i.auth(e,async()=>void(a=await n())),a)return a})};export{O as hono};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { ActionDef, Ai, Config,
|
|
2
|
-
//#region src/index.d.ts
|
|
1
|
+
import { ActionDef, Ai, Config, Define, Grant, Own, Peer, Route, Saved, Side } from "./types.js";
|
|
2
|
+
//#region src/core/index.d.ts
|
|
3
3
|
declare const side: Side;
|
|
4
4
|
declare function x<P extends object>(params: P, config?: Config): Ai<P>;
|
|
5
5
|
declare function x<P extends object = {}>(params?: Partial<P>, config?: Config): Ai<P>;
|
|
6
6
|
//#endregion
|
|
7
|
-
export { type ActionDef, type Ai, type Config, type
|
|
7
|
+
export { type ActionDef, type Ai, type Config, type Define, type Grant, type Own, type Peer, type Route, type Saved, type Side, side, x };
|
package/dist/types.d.ts
CHANGED
|
@@ -22,10 +22,6 @@ interface Saved extends Peer {
|
|
|
22
22
|
room: string;
|
|
23
23
|
}
|
|
24
24
|
type Own = (at: Peer) => Promise<string> | string;
|
|
25
|
-
interface Cookie {
|
|
26
|
-
apex: string;
|
|
27
|
-
services: string[];
|
|
28
|
-
}
|
|
29
25
|
interface Route {
|
|
30
26
|
room?: string;
|
|
31
27
|
path?: string;
|
|
@@ -52,8 +48,10 @@ interface Config {
|
|
|
52
48
|
version?: string;
|
|
53
49
|
salt?: string;
|
|
54
50
|
maxAge?: number;
|
|
55
|
-
cookie?: Cookie;
|
|
56
51
|
providers?: any[];
|
|
52
|
+
domain?: (env: any) => string;
|
|
53
|
+
apiKey?: (env: any) => string;
|
|
54
|
+
secret?: (env: any) => string;
|
|
57
55
|
ui?: string[];
|
|
58
56
|
history?: object;
|
|
59
57
|
load?: (at: Saved) => Promise<any>;
|
|
@@ -96,4 +94,4 @@ type Ai<T extends object = {}> = T & {
|
|
|
96
94
|
snapshot(): Uint8Array;
|
|
97
95
|
};
|
|
98
96
|
//#endregion
|
|
99
|
-
export { ActionDef, Ai, Config,
|
|
97
|
+
export { ActionDef, Ai, Config, Define, Grant, Own, Peer, Route, Saved, Side };
|