@johpaz/hive-agents 1.1.5 → 1.1.11
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 +4 -10
- package/dist/hive.js +218257 -148718
- package/dist/tool-worker.js +68422 -1622
- package/dist/ui/assets/{A2UIPage-Dr3p75oE.js → A2UIPage-v-VggXW3.js} +4 -4
- package/dist/ui/assets/{AgentCreateForm-DqYhH_gm.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
- package/dist/ui/assets/{AgentNewPage-BRpFxJIT.js → AgentNewPage-D7557C0J.js} +1 -1
- package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
- package/dist/ui/assets/{ApiClientPage-R9UDWfR2.js → ApiClientPage-uuBnrh0y.js} +1 -1
- package/dist/ui/assets/ChannelsPage-BI4mAgRU.js +8 -0
- package/dist/ui/assets/DashboardPage-BjAxvzYP.js +6 -0
- package/dist/ui/assets/LoginPage-D7IZKON0.js +1 -0
- package/dist/ui/assets/{LogsPage-DICMU_7m.js → LogsPage-mcqOYvGw.js} +1 -1
- package/dist/ui/assets/MeetingPage-qPJ1z5HA.js +1 -0
- package/dist/ui/assets/ModelSelector-njfNhkng.js +1 -0
- package/dist/ui/assets/{NotFound-D4ZlDVg9.js → NotFound-DY8e1RKh.js} +1 -1
- package/dist/ui/assets/{Office3DPage-31AMJ-LN.css → Office3DPage-C3SIzd2H.css} +1 -1
- package/dist/ui/assets/Office3DPage-Du42LRwi.js +319 -0
- package/dist/ui/assets/ProvidersPage-GDCJs8Zb.js +1 -0
- package/dist/ui/assets/{RecoverPage-Blms3NBa.js → RecoverPage-B6qvBBIl.js} +1 -1
- package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
- package/dist/ui/assets/{SetupPage-CAjLseE_.js → SetupPage-OaouFLGD.js} +1 -1
- package/dist/ui/assets/{Vignette-DrI2yK2m.js → Vignette-GSZ-owcN.js} +17 -17
- package/dist/ui/assets/VoicePage-DRQZBl3j.js +307 -0
- package/dist/ui/assets/WebChatPage-Cypq-SYi.js +29 -0
- package/dist/ui/assets/{agentCapabilities-CDSfJWhw.js → agentCapabilities-Bf71Gir4.js} +1 -1
- package/dist/ui/assets/{alert-CjiX20jI.js → alert-Dn604uVs.js} +1 -1
- package/dist/ui/assets/{badge-B5AKge1b.js → badge-C6H33ePv.js} +1 -1
- package/dist/ui/assets/{card-mTJ4oZbL.js → card-D0qneq1i.js} +1 -1
- package/dist/ui/assets/{conversationsStore-DhM07qYi.js → conversationsStore-D6XgjMr1.js} +1 -1
- package/dist/ui/assets/{dialog-BP3GTCPn.js → dialog-DO1fQCF7.js} +1 -1
- package/dist/ui/assets/dist-js-C2MfmbEW.js +1 -0
- package/dist/ui/assets/{dist-js-CkNhvsFc.js → dist-js-Djxbxbst.js} +1 -1
- package/dist/ui/assets/google-external-e9lvWjy4.js +1 -0
- package/dist/ui/assets/index-BKNFH2al.css +2 -0
- package/dist/ui/assets/index-U0e4e5mL.js +156 -0
- package/dist/ui/assets/{key-DPkOY-J0.js → key-round-Ca0Ns34v.js} +1 -1
- package/dist/ui/assets/{label-D_fvqJyD.js → label-CvAtVE-v.js} +1 -1
- package/dist/ui/assets/{scroll-area-CbH8FOo8.js → scroll-area-CYMu7sU0.js} +1 -1
- package/dist/ui/assets/select-BjBXxyxL.js +1 -0
- package/dist/ui/assets/{slider-DXS4h1LB.js → slider-DR31eN3r.js} +1 -1
- package/dist/ui/assets/{switch-ndx8VCpm.js → switch-B5dAwb54.js} +1 -1
- package/dist/ui/assets/{tabs-epu-3Tl4.js → tabs-Ct92cLXr.js} +1 -1
- package/dist/ui/assets/{earth-BJRGJbVn.js → terminal-CpBDERBE.js} +1 -1
- package/dist/ui/assets/{textarea-BgZJFZTX.js → textarea-xtFAVuPf.js} +1 -1
- package/dist/ui/assets/{useAudioDevices-zj0fuGwZ.js → useAudioDevices-wZArmV3m.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-Cd9p-bjs.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
- package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
- package/dist/ui/assets/{useProviders-Dj1k5PCk.js → useProviders-CeSzDnx-.js} +1 -1
- package/dist/ui/assets/vendor-router-DxU0Uf4R.js +3 -0
- package/dist/ui/index.html +5 -5
- package/package.json +1 -3
- package/packages/cli/src/commands/onboard.ts +3 -2
- package/packages/core/src/agent/agent-catalog.ts +98 -1
- package/packages/core/src/agent/agent-loop.ts +5 -44
- package/packages/core/src/agent/context-compiler.ts +6 -94
- package/packages/core/src/agent/conversation-store.ts +23 -1
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
- package/packages/core/src/agent/minimal-loadout.ts +1 -0
- package/packages/core/src/agent/prompt-builder.ts +17 -1
- package/packages/core/src/agent/tool-selector.ts +12 -0
- package/packages/core/src/artifacts/store.ts +73 -9
- package/packages/core/src/canvas/emitter.ts +0 -19
- package/packages/core/src/channels/base.ts +26 -0
- package/packages/core/src/channels/discord.ts +18 -2
- package/packages/core/src/channels/slack.ts +37 -7
- package/packages/core/src/channels/telegram.ts +39 -11
- package/packages/core/src/channels/whatsapp.ts +16 -1
- package/packages/core/src/gateway/channel-notify.ts +42 -0
- package/packages/core/src/gateway/google-host.ts +228 -0
- package/packages/core/src/gateway/initializer.ts +8 -0
- package/packages/core/src/gateway/routes/agents.ts +14 -0
- package/packages/core/src/gateway/routes/artifacts.ts +4 -0
- package/packages/core/src/gateway/routes/auth.ts +25 -3
- package/packages/core/src/gateway/routes/chat.ts +14 -1
- package/packages/core/src/gateway/routes/google.ts +252 -0
- package/packages/core/src/gateway/routes/meeting.ts +11 -3
- package/packages/core/src/gateway/routes/models.ts +27 -11
- package/packages/core/src/gateway/routes/multimodal.ts +38 -0
- package/packages/core/src/gateway/routes/providers.ts +19 -18
- package/packages/core/src/gateway/routes/system.ts +1 -3
- package/packages/core/src/gateway/routes/tts-local.ts +20 -374
- package/packages/core/src/gateway/routes/voice.ts +29 -35
- package/packages/core/src/gateway/server.ts +97 -48
- package/packages/core/src/gateway/tts/README.md +7 -86
- package/packages/core/src/gateway/tts/build.py +105 -0
- package/packages/core/src/gateway/tts/kitten.ts +282 -0
- package/packages/core/src/gateway/tts/python.d.ts +4 -0
- package/packages/core/src/gateway/tts/src/detect.ts +33 -39
- package/packages/core/src/gateway/tts/worker.py +80 -0
- package/packages/core/src/gateway/webchat-turn.ts +15 -13
- package/packages/core/src/google/client.ts +123 -0
- package/packages/core/src/google/config.ts +60 -0
- package/packages/core/src/google/google.test.ts +287 -0
- package/packages/core/src/google/index.ts +5 -0
- package/packages/core/src/google/oauth.ts +144 -0
- package/packages/core/src/google/scopes.ts +41 -0
- package/packages/core/src/google/token-store.ts +33 -0
- package/packages/core/src/multimodal/attachment-ingest.ts +190 -0
- package/packages/core/src/multimodal/image-generation.ts +244 -0
- package/packages/core/src/multimodal/vision-analyzer.ts +94 -0
- package/packages/core/src/multimodal/vision-service.ts +25 -0
- package/packages/core/src/storage/collections.ts +8 -8
- package/packages/core/src/storage/google-capabilities.ts +91 -0
- package/packages/core/src/storage/model-activation.ts +18 -0
- package/packages/core/src/storage/model-sync.ts +66 -14
- package/packages/core/src/storage/onboarding.ts +10 -2
- package/packages/core/src/storage/seed.ts +107 -24
- package/packages/core/src/storage/usage.ts +0 -52
- package/packages/core/src/tool-runtime/index.ts +2 -0
- package/packages/core/src/tools/agents/get-available-models.ts +1 -3
- package/packages/core/src/tools/core/index.ts +80 -2
- package/packages/core/src/tools/google/calendar.ts +204 -0
- package/packages/core/src/tools/google/drive.ts +160 -0
- package/packages/core/src/tools/google/gmail.ts +579 -0
- package/packages/core/src/tools/google/index.ts +18 -0
- package/packages/core/src/tools/google/shared.ts +80 -0
- package/packages/core/src/tools/image/image-generate.ts +90 -0
- package/packages/core/src/tools/image/index.ts +13 -0
- package/packages/core/src/tools/image/office-leer-imagenes.ts +198 -0
- package/packages/core/src/tools/index.ts +27 -0
- package/packages/core/src/tools/office/index.ts +9 -0
- package/packages/core/src/tools/office/office-editar-docx.ts +184 -0
- package/packages/core/src/tools/office/office-editar-pptx.ts +126 -0
- package/packages/core/src/tools/office/office-editar-xlsx.ts +122 -0
- package/packages/core/src/tools/office/office-escribir-docx.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-pdf.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-pptx.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-xlsx.ts +3 -2
- package/packages/core/src/tools/office/office-images.ts +137 -0
- package/packages/core/src/tools/office/office-leer-docx.ts +16 -3
- package/packages/core/src/tools/office/office-leer-pdf.ts +41 -57
- package/packages/core/src/tools/office/office-leer-pptx.ts +54 -88
- package/packages/core/src/tools/office/office-leer-xlsx.ts +6 -2
- package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
- package/packages/core/src/tools/office/pdf-text.ts +186 -0
- package/packages/core/src/tools/office/pptx-slides.ts +83 -0
- package/packages/core/src/tools/office/resolve-input.ts +49 -0
- package/packages/core/src/tools/web/browser-screenshot.ts +7 -0
- package/packages/core/src/voice/index.ts +123 -155
- package/packages/core/src/voice/local-model.ts +8 -0
- package/packages/core/src/voice/stt-models.ts +39 -0
- package/packages/skills/src/bundled/google/google_calendar/SKILL.md +51 -0
- package/packages/skills/src/bundled/google/google_drive/SKILL.md +50 -0
- package/packages/skills/src/bundled/google/google_gmail/SKILL.md +61 -0
- package/packages/skills/src/bundled-data.generated.ts +45 -0
- package/dist/ui/assets/AgentDetailPage-BVtE88U5.js +0 -1
- package/dist/ui/assets/AgentsPage-BOIJ55cj.js +0 -10
- package/dist/ui/assets/ChannelsPage-C5V2BmjL.js +0 -8
- package/dist/ui/assets/DashboardPage-B18gMzNj.js +0 -6
- package/dist/ui/assets/LoginPage-nrsYF9AY.js +0 -1
- package/dist/ui/assets/MeetingPage-xslJGfIz.js +0 -1
- package/dist/ui/assets/ModelSelector-BX4IvuYY.js +0 -1
- package/dist/ui/assets/Office3DPage-a6cuzt5X.js +0 -727
- package/dist/ui/assets/ProvidersPage-C8-xGoeh.js +0 -1
- package/dist/ui/assets/SettingsPage-BBeeq_QS.js +0 -9
- package/dist/ui/assets/VoicePage-BeSSYstD.js +0 -307
- package/dist/ui/assets/WebChatPage-Bat7uUfd.js +0 -29
- package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
- package/dist/ui/assets/index-BG3nUPKq.js +0 -156
- package/dist/ui/assets/index-DmFPF9xQ.css +0 -2
- package/dist/ui/assets/lock-open-v0EphssG.js +0 -1
- package/dist/ui/assets/select-v_3QBYrD.js +0 -1
- package/dist/ui/assets/terminal-BEcTK780.js +0 -1
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +0 -1
- package/dist/ui/assets/vendor-router-DSMCk-Ka.js +0 -3
- package/packages/core/src/agent/jev-decisions.ts +0 -242
- package/packages/core/src/agent/jev-planner.ts +0 -293
- package/packages/core/src/gateway/tts/package.json +0 -25
- package/packages/core/src/gateway/tts/src/client.ts +0 -59
- package/packages/core/src/gateway/tts/src/index.ts +0 -15
- package/packages/core/src/gateway/tts/src/install.ts +0 -137
- package/packages/core/src/gateway/tts/src/models.ts +0 -50
- package/packages/core/src/gateway/tts/src/server.ts +0 -253
- /package/dist/ui/assets/{core-p4c5dns5.js → core-npANj14X.js} +0 -0
- /package/dist/ui/assets/{download-BQXrpH0m.js → download-D0aDV8Y_.js} +0 -0
- /package/dist/ui/assets/{ellipsis-vertical-D7uFJLGh.js → ellipsis-vertical-BOW_iEOO.js} +0 -0
- /package/dist/ui/assets/{external-link-6oTH9pUM.js → external-link-DNJH7epD.js} +0 -0
- /package/dist/ui/assets/{eye-CxvxtQT5.js → eye-BVfTWOME.js} +0 -0
- /package/dist/ui/assets/{file-text-D5ZJEx3E.js → file-text-ByqNMpXm.js} +0 -0
- /package/dist/ui/assets/{gateway-url-BALS_wVh.js → gateway-url-BzQV75Ig.js} +0 -0
- /package/dist/ui/assets/{gauge-CEu7PhTW.js → gauge-CB4np0Vz.js} +0 -0
- /package/dist/ui/assets/{history-DLK5rTlP.js → history-CbhJX41s.js} +0 -0
- /package/dist/ui/assets/{info-8ReWzubE.js → info-BCD3-QX9.js} +0 -0
- /package/dist/ui/assets/{lock-3IApZyVy.js → lock-DpBean4K.js} +0 -0
- /package/dist/ui/assets/{mail-vwCEHyhQ.js → mail-Biwn8WrV.js} +0 -0
- /package/dist/ui/assets/{mic-CpDU_2as.js → mic-Rq4BxU1R.js} +0 -0
- /package/dist/ui/assets/{pause-BAMsNQkh.js → pause-87NGXbsz.js} +0 -0
- /package/dist/ui/assets/{pencil-CKritjT_.js → pencil-BG8EFaS3.js} +0 -0
- /package/dist/ui/assets/{play-Cwpe4tp6.js → play-D3De6YsQ.js} +0 -0
- /package/dist/ui/assets/{plus-RD44ce15.js → plus-Bp8-V68t.js} +0 -0
- /package/dist/ui/assets/{radio-lFPMHi6-.js → radio-m7rzuDKK.js} +0 -0
- /package/dist/ui/assets/{refresh-cw-DtJMHRHO.js → refresh-cw-D6F1zoC6.js} +0 -0
- /package/dist/ui/assets/{rotate-ccw-b3E_4PoX.js → rotate-ccw-DUlEC1_D.js} +0 -0
- /package/dist/ui/assets/{search-z2oZt00P.js → search-CfNwwpMW.js} +0 -0
- /package/dist/ui/assets/{send-CpoY_2F-.js → send-CI868CBV.js} +0 -0
- /package/dist/ui/assets/{settings-qV3kVkeG.js → settings-AEM2uWiD.js} +0 -0
- /package/dist/ui/assets/{shield-CIarwBvx.js → shield-DvVIcbzd.js} +0 -0
- /package/dist/ui/assets/{sparkles-DVvY6jDT.js → sparkles-DRe4GbSH.js} +0 -0
- /package/dist/ui/assets/{square-D5zdNkAY.js → square-DTWkjTT3.js} +0 -0
- /package/dist/ui/assets/{trash-2-D6oziYAK.js → trash-2-BZsMCfso.js} +0 -0
- /package/dist/ui/assets/{utils-DEmd_M8c.js → utils-lc8H6VGT.js} +0 -0
- /package/dist/ui/assets/{volume-2-EaA0JRvD.js → volume-2-CBMYsuF3.js} +0 -0
- /package/dist/ui/assets/{volume-x-CROXNMGT.js → volume-x-vNFf2e4-.js} +0 -0
- /package/dist/ui/assets/{wifi-BUJuOcgP.js → wifi-DNv53AfN.js} +0 -0
- /package/dist/ui/assets/{zap-DSoX9NDk.js → zap-Yed86Sh8.js} +0 -0
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-S-ySWqyJ.js";import{f as t}from"./vendor-charts-K3xcRl0X.js";var n=e(t(),1),r=`modulepreload`,i=function(e){return`/`+e},a={},o=function(e,t,n){let o=Promise.resolve();if(t&&t.length>0){let e=function(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))},s=document.getElementsByTagName(`link`),c=document.querySelector(`meta[property=csp-nonce]`),l=c?.nonce||c?.getAttribute(`nonce`);o=e(t.map(e=>{if(e=i(e,n),e in a)return;a[e]=!0;let t=e.endsWith(`.css`),o=t?`[rel="stylesheet"]`:``;if(n)for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.href===e&&(!t||r.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${e}"]${o}`))return;let c=document.createElement(`link`);if(c.rel=t?`stylesheet`:r,t||(c.as=`script`),c.crossOrigin=``,c.href=e,l&&c.setAttribute(`nonce`,l),document.head.appendChild(c),t)return new Promise((t,n)=>{c.addEventListener(`load`,t),c.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${e}`)))})}))}function s(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return o.then(t=>{for(let e of t||[])e.status===`rejected`&&s(e.reason);return e().catch(s)})},s=`popstate`;function c(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function l(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return m(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:h(t)}return _(t,n,null,e)}function u(e,t){if(e===!1||e==null)throw Error(t)}function d(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function f(){return Math.random().toString(36).substring(2,10)}function p(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function m(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?g(t):t,state:n,key:t&&t.key||r||f(),mask:i}}function h({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function g(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function _(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,l=`POP`,u=null,d=f();d??(d=0,o.replaceState({...o.state,idx:d},``));function f(){return(o.state||{idx:null}).idx}function h(){l=`POP`;let e=f(),t=e==null?null:e-d;d=e,u&&u({action:l,location:b.location,delta:t})}function g(e,t){l=`PUSH`;let r=c(e)?e:m(b.location,e,t);n&&n(r,e),d=f()+1;let s=p(r,d),h=b.createHref(r.mask||r);try{o.pushState(s,``,h)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(h)}a&&u&&u({action:l,location:b.location,delta:1})}function _(e,t){l=`REPLACE`;let r=c(e)?e:m(b.location,e,t);n&&n(r,e),d=f();let i=p(r,d),s=b.createHref(r.mask||r);o.replaceState(i,``,s),a&&u&&u({action:l,location:b.location,delta:0})}function y(e){return v(e)}let b={get action(){return l},get location(){return e(i,o)},listen(e){if(u)throw Error(`A history only accepts one active listener`);return i.addEventListener(s,h),u=e,()=>{i.removeEventListener(s,h),u=null}},createHref(e){return t(i,e)},createURL:y,encodeLocation(e){let t=y(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:g,replace:_,go(e){return o.go(e)}};return b}function v(e,t=!1){let n=`http://localhost`;typeof window<`u`&&(n=window.location.origin===`null`?window.location.href:window.location.origin),u(n,`No window.location.(origin|href) available to create URL`);let r=typeof e==`string`?e:h(e);return r=r.replace(/ $/,`%20`),!t&&r.startsWith(`//`)&&(r=n+r),new URL(r,n)}function y(e,t,n=`/`){return b(e,t,n,!1)}function b(e,t,n,r,i){let a=k((typeof t==`string`?g(t):t).pathname||`/`,n);if(a==null)return null;let o=i??S(e),s=null,c=le(a);for(let e=0;s==null&&e<o.length;++e)s=se(o[e],c,r);return s}function x(e,t){let{route:n,pathname:r,params:i}=e;return{id:n.id,pathname:r,params:i,data:t[n.id],loaderData:t[n.id],handle:n.handle}}function S(e){let t=C(e);return T(t),t}function C(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;u(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=j([r,c.relativePath]),d=n.concat(c);e.children&&e.children.length>0&&(u(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),C(e.children,t,d,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:ae(l,e.index),routesMeta:d})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of w(e.path))a(e,t,!0,n)}),t}function w(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=w(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function T(e){e.sort((e,t)=>e.score===t.score?oe(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var E=/^:[\w-]+$/,ee=3,te=2,ne=1,D=10,re=-2,ie=e=>e===`*`;function ae(e,t){let n=e.split(`/`),r=n.length;return n.some(ie)&&(r+=re),t&&(r+=te),n.filter(e=>!ie(e)).reduce((e,t)=>e+(E.test(t)?ee:t===``?ne:D),r)}function oe(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function se(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u=O({path:s.relativePath,caseSensitive:s.caseSensitive,end:c},l),d=s.route;if(!u&&c&&n&&!r[r.length-1].route.index&&(u=O({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!u)return null;Object.assign(i,u.params),o.push({params:i,pathname:j([a,u.pathname]),pathnameBase:_e(j([a,u.pathnameBase])),route:d}),u.pathnameBase!==`/`&&(a=j([a,u.pathnameBase]))}return o}function O(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=ce(e.path,e.caseSensitive,e.end),i=t.match(n);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,`$1`),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return n&&!i?e[t]=void 0:e[t]=(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function ce(e,t=!1,n=!0){d(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function le(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return d(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function k(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}var ue=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function de(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?g(e):e,a;return n?(n=ge(n),a=n.startsWith(`/`)?fe(n.substring(1),`/`):fe(n,t)):a=t,{pathname:a,search:ve(r),hash:ye(i)}}function fe(e,t){let n=M(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function pe(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function me(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function he(e){let t=me(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function A(e,t,n,r=!1){let i;typeof e==`string`?i=g(e):(i={...e},u(!i.pathname||!i.pathname.includes(`?`),pe(`?`,`pathname`,`search`,i)),u(!i.pathname||!i.pathname.includes(`#`),pe(`#`,`pathname`,`hash`,i)),u(!i.search||!i.search.includes(`#`),pe(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=de(i,s),l=o&&o!==`/`&&o.endsWith(`/`),d=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||d)&&(c.pathname+=`/`),c}var ge=e=>e.replace(/\/\/+/g,`/`),j=e=>ge(e.join(`/`)),M=e=>e.replace(/\/+$/,``),_e=e=>M(e).replace(/^\/*/,`/`),ve=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,ye=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,be=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function xe(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Se(e){return j(e.map(e=>e.route.path).filter(Boolean))||`/`}var Ce=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function we(e,t){let n=e;if(typeof n!=`string`||!ue.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(Ce)try{let e=new URL(window.location.href),r=n.startsWith(`//`)?new URL(e.protocol+n):new URL(n),a=k(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{d(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var Te=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Te);var Ee=[`GET`,...Te];new Set(Ee);var N=n.createContext(null);N.displayName=`DataRouter`;var P=n.createContext(null);P.displayName=`DataRouterState`;var De=n.createContext(!1);function Oe(){return n.useContext(De)}var ke=n.createContext({isTransitioning:!1});ke.displayName=`ViewTransition`;var Ae=n.createContext(new Map);Ae.displayName=`Fetchers`;var je=n.createContext(null);je.displayName=`Await`;var F=n.createContext(null);F.displayName=`Navigation`;var I=n.createContext(null);I.displayName=`Location`;var L=n.createContext({outlet:null,matches:[],isDataRoute:!1});L.displayName=`Route`;var R=n.createContext(null);R.displayName=`RouteError`;var Me=`REACT_ROUTER_ERROR`,Ne=`REDIRECT`,Pe=`ROUTE_ERROR_RESPONSE`;function Fe(e){if(e.startsWith(`${Me}:${Ne}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function Ie(e){if(e.startsWith(`${Me}:${Pe}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new be(t.status,t.statusText,t.data)}catch{}}function Le(e,{relative:t}={}){u(z(),`useHref() may be used only in the context of a <Router> component.`);let{basename:r,navigator:i}=n.useContext(F),{hash:a,pathname:o,search:s}=H(e,{relative:t}),c=o;return r!==`/`&&(c=o===`/`?r:j([r,o])),i.createHref({pathname:c,search:s,hash:a})}function z(){return n.useContext(I)!=null}function B(){return u(z(),`useLocation() may be used only in the context of a <Router> component.`),n.useContext(I).location}var Re=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function ze(e){n.useContext(F).static||n.useLayoutEffect(e)}function V(){let{isDataRoute:e}=n.useContext(L);return e?it():Be()}function Be(){u(z(),`useNavigate() may be used only in the context of a <Router> component.`);let e=n.useContext(N),{basename:t,navigator:r}=n.useContext(F),{matches:i}=n.useContext(L),{pathname:a}=B(),o=JSON.stringify(he(i)),s=n.useRef(!1);return ze(()=>{s.current=!0}),n.useCallback((n,i={})=>{if(d(s.current,Re),!s.current)return;if(typeof n==`number`){r.go(n);return}let c=A(n,JSON.parse(o),a,i.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:j([t,c.pathname])),(i.replace?r.replace:r.push)(c,i.state,i)},[t,r,o,a,e])}var Ve=n.createContext(null);function He(e){let t=n.useContext(L).outlet;return n.useMemo(()=>t&&n.createElement(Ve.Provider,{value:e},t),[t,e])}function Ue(){let{matches:e}=n.useContext(L);return e[e.length-1]?.params??{}}function H(e,{relative:t}={}){let{matches:r}=n.useContext(L),{pathname:i}=B(),a=JSON.stringify(he(r));return n.useMemo(()=>A(e,JSON.parse(a),i,t===`path`),[e,a,i,t])}function We(e,t){return Ge(e,t)}function Ge(e,t,r){u(z(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:i}=n.useContext(F),{matches:a}=n.useContext(L),o=a[a.length-1],s=o?o.params:{},c=o?o.pathname:`/`,l=o?o.pathnameBase:`/`,f=o&&o.route;{let e=f&&f.path||``;ot(c,!f||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${c}" (under <Route path="${e}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
2
|
-
|
|
3
|
-
Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let p=B(),m;if(t){let e=typeof t==`string`?g(t):t;u(l===`/`||e.pathname?.startsWith(l),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${l}" but pathname "${e.pathname}" was given in the \`location\` prop.`),m=e}else m=p;let h=m.pathname||`/`,_=h;if(l!==`/`){let e=l.replace(/^\//,``).split(`/`);_=`/`+h.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let v=r&&r.state.matches.length?r.state.matches.map(e=>Object.assign(e,{route:r.manifest[e.route.id]||e.route})):y(e,{pathname:_});d(f||v!=null,`No routes matched location "${m.pathname}${m.search}${m.hash}" `),d(v==null||v[v.length-1].route.element!==void 0||v[v.length-1].route.Component!==void 0||v[v.length-1].route.lazy!==void 0,`Matched leaf route at location "${m.pathname}${m.search}${m.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let b=Ze(v&&v.map(e=>Object.assign({},e,{params:Object.assign({},s,e.params),pathname:j([l,i.encodeLocation?i.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?l:j([l,i.encodeLocation?i.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),a,r);return t&&b?n.createElement(I.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...m},navigationType:`POP`}},b):b}function Ke(){let e=rt(),t=xe(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,i=`rgba(200,200,200, 0.5)`,a={padding:`0.5rem`,backgroundColor:i},o={padding:`2px 4px`,backgroundColor:i},s=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),s=n.createElement(n.Fragment,null,n.createElement(`p`,null,`💿 Hey developer 👋`),n.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,n.createElement(`code`,{style:o},`ErrorBoundary`),` or`,` `,n.createElement(`code`,{style:o},`errorElement`),` prop on your route.`)),n.createElement(n.Fragment,null,n.createElement(`h2`,null,`Unexpected Application Error!`),n.createElement(`h3`,{style:{fontStyle:`italic`}},t),r?n.createElement(`pre`,{style:a},r):null,s)}var qe=n.createElement(Ke,null),Je=class extends n.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=Ie(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:n.createElement(L.Provider,{value:this.props.routeContext},n.createElement(R.Provider,{value:e,children:this.props.component}));return this.context?n.createElement(Ye,{error:e},t):t}};Je.contextType=De;var U=new WeakMap;function Ye({children:e,error:t}){let{basename:r}=n.useContext(F);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Fe(t.digest);if(e){let i=U.get(t);if(i)throw i;let a=we(e.location,r);if(Ce&&!U.get(t))if(a.isExternal||e.reloadDocument)window.location.href=a.absoluteURL||a.to;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:e.replace}));throw U.set(t,n),n}return n.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a.absoluteURL||a.to}`})}}return e}function Xe({routeContext:e,match:t,children:r}){let i=n.useContext(N);return i&&i.static&&i.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=t.route.id),n.createElement(L.Provider,{value:e},r)}function Ze(e,t=[],r){let i=r?.state;if(e==null){if(!i)return null;if(i.errors)e=i.matches;else if(t.length===0&&!i.initialized&&i.matches.length>0)e=i.matches;else return null}let a=e,o=i?.errors;if(o!=null){let e=a.findIndex(e=>e.route.id&&o?.[e.route.id]!==void 0);u(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(`,`)}`),a=a.slice(0,Math.min(a.length,e+1))}let s=!1,c=-1;if(r&&i){s=i.renderFallback;for(let e=0;e<a.length;e++){let t=a[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(c=e),t.route.id){let{loaderData:e,errors:n}=i,o=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!n||n[t.route.id]===void 0);if(t.route.lazy||o){r.isStatic&&(s=!0),a=c>=0?a.slice(0,c+1):[a[0]];break}}}}let l=r?.onError,d=i&&l?(e,t)=>{l(e,{location:i.location,params:i.matches?.[0]?.params??{},pattern:Se(i.matches),errorInfo:t})}:void 0;return a.reduceRight((e,r,l)=>{let u,f=!1,p=null,m=null;i&&(u=o&&r.route.id?o[r.route.id]:void 0,p=r.route.errorElement||qe,s&&(c<0&&l===0?(ot(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),f=!0,m=null):c===l&&(f=!0,m=r.route.hydrateFallbackElement||null)));let h=t.concat(a.slice(0,l+1)),g=()=>{let t;return t=u?p:f?m:r.route.Component?n.createElement(r.route.Component,null):r.route.element?r.route.element:e,n.createElement(Xe,{match:r,routeContext:{outlet:e,matches:h,isDataRoute:i!=null},children:t})};return i&&(r.route.ErrorBoundary||r.route.errorElement||l===0)?n.createElement(Je,{location:i.location,revalidation:i.revalidation,component:p,error:u,children:g(),routeContext:{outlet:null,matches:h,isDataRoute:!0},onError:d}):g()},null)}function W(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Qe(e){let t=n.useContext(N);return u(t,W(e)),t}function G(e){let t=n.useContext(P);return u(t,W(e)),t}function $e(e){let t=n.useContext(L);return u(t,W(e)),t}function K(e){let t=$e(e),n=t.matches[t.matches.length-1];return u(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function et(){return K(`useRouteId`)}function tt(){return G(`useNavigation`).navigation}function nt(){let{matches:e,loaderData:t}=G(`useMatches`);return n.useMemo(()=>e.map(e=>x(e,t)),[e,t])}function rt(){let e=n.useContext(R),t=G(`useRouteError`),r=K(`useRouteError`);return e===void 0?t.errors?.[r]:e}function it(){let{router:e}=Qe(`useNavigate`),t=K(`useNavigate`),r=n.useRef(!1);return ze(()=>{r.current=!0}),n.useCallback(async(n,i={})=>{d(r.current,Re),r.current&&(typeof n==`number`?await e.navigate(n):await e.navigate(n,{fromRouteId:t,...i}))},[e,t])}var at={};function ot(e,t,n){!t&&!at[e]&&(at[e]=!0,d(!1,n))}n.memo(st);function st({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return Ge(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function ct({to:e,replace:t,state:r,relative:i}){u(z(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:a}=n.useContext(F);d(!a,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:o}=n.useContext(L),{pathname:s}=B(),c=V(),l=A(e,he(o),s,i===`path`),f=JSON.stringify(l);return n.useEffect(()=>{c(JSON.parse(f),{replace:t,state:r,relative:i})},[c,f,i,t,r]),null}function lt(e){return He(e.context)}function ut(e){u(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function dt({basename:e=`/`,children:t=null,location:r,navigationType:i=`POP`,navigator:a,static:o=!1,useTransitions:s}){u(!z(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let c=e.replace(/^\/*/,`/`),l=n.useMemo(()=>({basename:c,navigator:a,static:o,useTransitions:s,future:{}}),[c,a,o,s]);typeof r==`string`&&(r=g(r));let{pathname:f=`/`,search:p=``,hash:m=``,state:h=null,key:_=`default`,mask:v}=r,y=n.useMemo(()=>{let e=k(f,c);return e==null?null:{location:{pathname:e,search:p,hash:m,state:h,key:_,mask:v},navigationType:i}},[c,f,p,m,h,_,i,v]);return d(y!=null,`<Router basename="${c}"> is not able to match the URL "${f}${p}${m}" because it does not start with the basename, so the <Router> won't render anything.`),y==null?null:n.createElement(F.Provider,{value:l},n.createElement(I.Provider,{children:t,value:y}))}function ft({children:e,location:t}){return We(pt(e),t)}n.Component;function pt(e,t=[]){let r=[];return n.Children.forEach(e,(e,i)=>{if(!n.isValidElement(e))return;let a=[...t,i];if(e.type===n.Fragment){r.push.apply(r,pt(e.props.children,a));return}u(e.type===ut,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),u(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let o={id:e.props.id||a.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(o.children=pt(e.props.children,a)),r.push(o)}),r}var q=`get`,J=`application/x-www-form-urlencoded`;function Y(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function mt(e){return Y(e)&&e.tagName.toLowerCase()===`button`}function ht(e){return Y(e)&&e.tagName.toLowerCase()===`form`}function gt(e){return Y(e)&&e.tagName.toLowerCase()===`input`}function _t(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function vt(e,t){return e.button===0&&(!t||t===`_self`)&&!_t(e)}var X=null;function yt(){if(X===null)try{new FormData(document.createElement(`form`),0),X=!1}catch{X=!0}return X}var bt=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function xt(e){return e!=null&&!bt.has(e)?(d(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${J}"`),null):e}function St(e,t){let n,r,i,a,o;if(ht(e)){let o=e.getAttribute(`action`);r=o?k(o,t):null,n=e.getAttribute(`method`)||q,i=xt(e.getAttribute(`enctype`))||J,a=new FormData(e)}else if(mt(e)||gt(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?k(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||q,i=xt(e.getAttribute(`formenctype`))||xt(o.getAttribute(`enctype`))||J,a=new FormData(o,e),!yt()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(Y(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=q,r=null,i=J,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var Ct={"&":`\\u0026`,">":`\\u003e`,"<":`\\u003c`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},wt=/[&><\u2028\u2029]/g;function Tt(e){return e.replace(wt,e=>Ct[e])}function Et(e,t){if(e===!1||e==null)throw Error(t)}function Dt(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return n?i.pathname.endsWith(`/`)?i.pathname=`${i.pathname}_.${r}`:i.pathname=`${i.pathname}.${r}`:i.pathname===`/`?i.pathname=`_root.${r}`:t&&k(i.pathname,t)===`/`?i.pathname=`${M(t)}/_root.${r}`:i.pathname=`${M(i.pathname)}.${r}`,i}async function Ot(e,t){if(e.id in t)return t[e.id];try{let n=await o(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function kt(e){return e!=null&&typeof e.page==`string`}function At(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function jt(e,t,n){return It((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await Ot(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(At).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Mt(e,t,n,r,i,a){let o=(e,t)=>n[t]?e.route.id!==n[t].route.id:!0,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function Nt(e,t,{includeHydrateFallback:n}={}){return Pt(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function Pt(e){return[...new Set(e)]}function Ft(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function It(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!kt(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(Ft(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function Lt(){let e=n.useContext(N);return Et(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function Rt(){let e=n.useContext(P);return Et(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Z=n.createContext(void 0);Z.displayName=`FrameworkContext`;function zt(){let e=n.useContext(Z);return Et(e,`You must render this element inside a <HydratedRouter> element`),e}function Bt(e,t){let r=n.useContext(Z),[i,a]=n.useState(!1),[o,s]=n.useState(!1),{onFocus:c,onBlur:l,onMouseEnter:u,onMouseLeave:d,onTouchStart:f}=t,p=n.useRef(null);n.useEffect(()=>{if(e===`render`&&s(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{s(e.isIntersecting)})},{threshold:.5});return p.current&&e.observe(p.current),()=>{e.disconnect()}}},[e]),n.useEffect(()=>{if(i){let e=setTimeout(()=>{s(!0)},100);return()=>{clearTimeout(e)}}},[i]);let m=()=>{a(!0)},h=()=>{a(!1),s(!1)};return r?e===`intent`?[o,p,{onFocus:Q(c,m),onBlur:Q(l,h),onMouseEnter:Q(u,m),onMouseLeave:Q(d,h),onTouchStart:Q(f,m)}]:[o,p,{}]:[!1,p,{}]}function Q(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Vt({page:e,...t}){let r=Oe(),{router:i}=Lt(),a=n.useMemo(()=>y(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?r?n.createElement(Ut,{page:e,matches:a,...t}):n.createElement(Wt,{page:e,matches:a,...t}):null}function Ht(e){let{manifest:t,routeModules:r}=zt(),[i,a]=n.useState([]);return n.useEffect(()=>{let n=!1;return jt(e,t,r).then(e=>{n||a(e)}),()=>{n=!0}},[e,t,r]),i}function Ut({page:e,matches:t,...r}){let i=B(),{future:a}=zt(),{basename:o}=Lt(),s=n.useMemo(()=>{if(e===i.pathname+i.search+i.hash)return[];let n=Dt(e,o,a.unstable_trailingSlashAwareDataRequests,`rsc`),r=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?r=!0:s.push(e.route.id);return r&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[o,a.unstable_trailingSlashAwareDataRequests,e,i,t]);return n.createElement(n.Fragment,null,s.map(e=>n.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...r})))}function Wt({page:e,matches:t,...r}){let i=B(),{future:a,manifest:o,routeModules:s}=zt(),{basename:c}=Lt(),{loaderData:l,matches:u}=Rt(),d=n.useMemo(()=>Mt(e,t,u,o,i,`data`),[e,t,u,o,i]),f=n.useMemo(()=>Mt(e,t,u,o,i,`assets`),[e,t,u,o,i]),p=n.useMemo(()=>{if(e===i.pathname+i.search+i.hash)return[];let n=new Set,r=!1;if(t.forEach(e=>{let t=o.routes[e.route.id];!t||!t.hasLoader||(!d.some(t=>t.route.id===e.route.id)&&e.route.id in l&&s[e.route.id]?.shouldRevalidate||t.hasClientLoader?r=!0:n.add(e.route.id))}),n.size===0)return[];let u=Dt(e,c,a.unstable_trailingSlashAwareDataRequests,`data`);return r&&n.size>0&&u.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[u.pathname+u.search]},[c,a.unstable_trailingSlashAwareDataRequests,l,i,o,d,t,e,s]),m=n.useMemo(()=>Nt(f,o),[f,o]),h=Ht(f);return n.createElement(n.Fragment,null,p.map(e=>n.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...r})),m.map(e=>n.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...r})),h.map(({key:e,link:t})=>n.createElement(`link`,{key:e,nonce:r.nonce,...t,crossOrigin:t.crossOrigin??r.crossOrigin})))}function Gt(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}n.Component;var Kt=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Kt&&(window.__reactRouterVersion=`7.15.0`)}catch{}function qt({basename:e,children:t,useTransitions:r,window:i}){let a=n.useRef();a.current??=l({window:i,v5Compat:!0});let o=a.current,[s,c]=n.useState({action:o.action,location:o.location}),u=n.useCallback(e=>{r===!1?c(e):n.startTransition(()=>c(e))},[r]);return n.useLayoutEffect(()=>o.listen(u),[o,u]),n.createElement(dt,{basename:e,children:t,location:s.location,navigationType:s.action,navigator:o,useTransitions:r})}function Jt({basename:e,children:t,history:r,useTransitions:i}){let[a,o]=n.useState({action:r.action,location:r.location}),s=n.useCallback(e=>{i===!1?o(e):n.startTransition(()=>o(e))},[i]);return n.useLayoutEffect(()=>r.listen(s),[r,s]),n.createElement(dt,{basename:e,children:t,location:a.location,navigationType:a.action,navigator:r,useTransitions:i})}Jt.displayName=`unstable_HistoryRouter`;var Yt=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Xt=n.forwardRef(function({onClick:e,discover:t=`render`,prefetch:r=`none`,relative:i,reloadDocument:a,replace:o,mask:s,state:c,target:l,to:u,preventScrollReset:d,viewTransition:f,defaultShouldRevalidate:p,...m},h){let{basename:g,navigator:_,useTransitions:v}=n.useContext(F),y=typeof u==`string`&&Yt.test(u),b=we(u,g);u=b.to;let x=Le(u,{relative:i}),S=B(),C=null;if(s){let e=A(s,[],S.mask?S.mask.pathname:`/`,!0);g!==`/`&&(e.pathname=e.pathname===`/`?g:j([g,e.pathname])),C=_.createHref(e)}let[w,T,E]=Bt(r,m),ee=rn(u,{replace:o,mask:s,state:c,target:l,preventScrollReset:d,relative:i,viewTransition:f,defaultShouldRevalidate:p,useTransitions:v});function te(t){e&&e(t),t.defaultPrevented||ee(t)}let ne=!(b.isExternal||a),D=n.createElement(`a`,{...m,...E,href:(ne?C:void 0)||b.absoluteURL||x,onClick:ne?te:e,ref:Gt(h,T),target:l,"data-discover":!y&&t===`render`?`true`:void 0});return w&&!y?n.createElement(n.Fragment,null,D,n.createElement(Vt,{page:x})):D});Xt.displayName=`Link`;var Zt=n.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:r=``,end:i=!1,style:a,to:o,viewTransition:s,children:c,...l},u){let d=H(o,{relative:l.relative}),f=B(),p=n.useContext(P),{navigator:m,basename:h}=n.useContext(F),g=p!=null&&pn(d)&&s===!0,_=m.encodeLocation?m.encodeLocation(d).pathname:d.pathname,v=f.pathname,y=p&&p.navigation&&p.navigation.location?p.navigation.location.pathname:null;t||(v=v.toLowerCase(),y=y?y.toLowerCase():null,_=_.toLowerCase()),y&&h&&(y=k(y,h)||y);let b=_!==`/`&&_.endsWith(`/`)?_.length-1:_.length,x=v===_||!i&&v.startsWith(_)&&v.charAt(b)===`/`,S=y!=null&&(y===_||!i&&y.startsWith(_)&&y.charAt(_.length)===`/`),C={isActive:x,isPending:S,isTransitioning:g},w=x?e:void 0,T;T=typeof r==`function`?r(C):[r,x?`active`:null,S?`pending`:null,g?`transitioning`:null].filter(Boolean).join(` `);let E=typeof a==`function`?a(C):a;return n.createElement(Xt,{...l,"aria-current":w,className:T,ref:u,style:E,to:o,viewTransition:s},typeof c==`function`?c(C):c)});Zt.displayName=`NavLink`;var Qt=n.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:r,reloadDocument:i,replace:a,state:o,method:s=q,action:c,onSubmit:l,relative:u,preventScrollReset:d,viewTransition:f,defaultShouldRevalidate:p,...m},h)=>{let{useTransitions:g}=n.useContext(F),_=sn(),v=cn(c,{relative:u}),y=s.toLowerCase()===`get`?`get`:`post`,b=typeof c==`string`&&Yt.test(c);return n.createElement(`form`,{ref:h,method:y,action:v,onSubmit:i?l:e=>{if(l&&l(e),e.defaultPrevented)return;e.preventDefault();let i=e.nativeEvent.submitter,c=i?.getAttribute(`formmethod`)||s,m=()=>_(i||e.currentTarget,{fetcherKey:t,method:c,navigate:r,replace:a,state:o,relative:u,preventScrollReset:d,viewTransition:f,defaultShouldRevalidate:p});g&&r!==!1?n.startTransition(()=>m()):m()},...m,"data-discover":!b&&e===`render`?`true`:void 0})});Qt.displayName=`Form`;function $t({getKey:e,storageKey:t,...r}){let i=n.useContext(Z),{basename:a}=n.useContext(F),o=B(),s=nt();dn({getKey:e,storageKey:t});let c=n.useMemo(()=>{if(!i||!e)return null;let t=un(o,s,a,e);return t===o.key?null:t},[]);if(!i||i.isSpaMode)return null;let l=((e,t)=>{if(!window.history.state||!window.history.state.key){let e=Math.random().toString(32).slice(2);window.history.replaceState({key:e},``)}try{let n=JSON.parse(sessionStorage.getItem(e)||`{}`)[t||window.history.state.key];typeof n==`number`&&window.scrollTo(0,n)}catch(t){console.error(t),sessionStorage.removeItem(e)}}).toString();return n.createElement(`script`,{...r,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`(${l})(${Tt(JSON.stringify(t||ln))}, ${Tt(JSON.stringify(c))})`}})}$t.displayName=`ScrollRestoration`;function en(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function tn(e){let t=n.useContext(N);return u(t,en(e)),t}function nn(e){let t=n.useContext(P);return u(t,en(e)),t}function rn(e,{target:t,replace:r,mask:i,state:a,preventScrollReset:o,relative:s,viewTransition:c,defaultShouldRevalidate:l,useTransitions:u}={}){let d=V(),f=B(),p=H(e,{relative:s});return n.useCallback(m=>{if(vt(m,t)){m.preventDefault();let t=r===void 0?h(f)===h(p):r,g=()=>d(e,{replace:t,mask:i,state:a,preventScrollReset:o,relative:s,viewTransition:c,defaultShouldRevalidate:l});u?n.startTransition(()=>g()):g()}},[f,d,p,r,i,a,t,e,o,s,c,l,u])}var an=0,on=()=>`__${String(++an)}__`;function sn(){let{router:e}=tn(`useSubmit`),{basename:t}=n.useContext(F),r=et(),i=e.fetch,a=e.navigate;return n.useCallback(async(e,n={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=St(e,t);n.navigate===!1?await i(n.fetcherKey||on(),r,n.action||o,{defaultShouldRevalidate:n.defaultShouldRevalidate,preventScrollReset:n.preventScrollReset,formData:l,body:u,formMethod:n.method||s,formEncType:n.encType||c,flushSync:n.flushSync}):await a(n.action||o,{defaultShouldRevalidate:n.defaultShouldRevalidate,preventScrollReset:n.preventScrollReset,formData:l,body:u,formMethod:n.method||s,formEncType:n.encType||c,replace:n.replace,state:n.state,fromRouteId:r,flushSync:n.flushSync,viewTransition:n.viewTransition})},[i,a,t,r])}function cn(e,{relative:t}={}){let{basename:r}=n.useContext(F),i=n.useContext(L);u(i,`useFormAction must be used inside a RouteContext`);let[a]=i.matches.slice(-1),o={...H(e||`.`,{relative:t})},s=B();if(e==null){o.search=s.search;let e=new URLSearchParams(o.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();o.search=n?`?${n}`:``}}return(!e||e===`.`)&&a.route.index&&(o.search=o.search?o.search.replace(/^\?/,`?index&`):`?index`),r!==`/`&&(o.pathname=o.pathname===`/`?r:j([r,o.pathname])),h(o)}var ln=`react-router-scroll-positions`,$={};function un(e,t,n,r){let i=null;return r&&(i=r(n===`/`?e:{...e,pathname:k(e.pathname,n)||e.pathname},t)),i??=e.key,i}function dn({getKey:e,storageKey:t}={}){let{router:r}=tn(`useScrollRestoration`),{restoreScrollPosition:i,preventScrollReset:a}=nn(`useScrollRestoration`),{basename:o}=n.useContext(F),s=B(),c=nt(),l=tt();n.useEffect(()=>(window.history.scrollRestoration=`manual`,()=>{window.history.scrollRestoration=`auto`}),[]),fn(n.useCallback(()=>{if(l.state===`idle`){let t=un(s,c,o,e);$[t]=window.scrollY}try{sessionStorage.setItem(t||ln,JSON.stringify($))}catch(e){d(!1,`Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${e}).`)}window.history.scrollRestoration=`auto`},[l.state,e,o,s,c,t])),typeof document<`u`&&(n.useLayoutEffect(()=>{try{let e=sessionStorage.getItem(t||ln);e&&($=JSON.parse(e))}catch{}},[t]),n.useLayoutEffect(()=>{let t=r?.enableScrollRestoration($,()=>window.scrollY,e?(t,n)=>un(t,n,o,e):void 0);return()=>t&&t()},[r,o,e]),n.useLayoutEffect(()=>{if(i!==!1){if(typeof i==`number`){window.scrollTo(0,i);return}try{if(s.hash){let e=document.getElementById(decodeURIComponent(s.hash.slice(1)));if(e){e.scrollIntoView();return}}}catch{d(!1,`"${s.hash.slice(1)}" is not a decodable element ID. The view will not scroll to it.`)}a!==!0&&window.scrollTo(0,0)}},[s,i,a]))}function fn(e,t){let{capture:r}=t||{};n.useEffect(()=>{let t=r==null?void 0:{capture:r};return window.addEventListener(`pagehide`,e,t),()=>{window.removeEventListener(`pagehide`,e,t)}},[e,r])}function pn(e,{relative:t}={}){let r=n.useContext(ke);u(r!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=tn(`useViewTransitionState`),a=H(e,{relative:t});if(!r.isTransitioning)return!1;let o=k(r.currentLocation.pathname,i)||r.currentLocation.pathname,s=k(r.nextLocation.pathname,i)||r.nextLocation.pathname;return O(a.pathname,s)!=null||O(a.pathname,o)!=null}export{ut as a,V as c,lt as i,Ue as l,Zt as n,ft as o,ct as r,B as s,qt as t,o as u};
|
|
@@ -1,242 +0,0 @@
|
|
|
1
|
-
/** Optional decision plane. Jev is never used through the chat completions API. */
|
|
2
|
-
import { col } from "../storage/hive"
|
|
3
|
-
import type { ProviderDoc } from "../storage/collections"
|
|
4
|
-
import { loadProviderApiKey } from "../storage/crypto"
|
|
5
|
-
import { recordJevDecision, recordUsage } from "../storage/usage"
|
|
6
|
-
import { catalogModelKey } from "../storage/model-id"
|
|
7
|
-
import { logger } from "../utils/logger"
|
|
8
|
-
import { emitCanvas, type CanvasJevDecision } from "../canvas/emitter"
|
|
9
|
-
|
|
10
|
-
const log = logger.child("jev-decisions")
|
|
11
|
-
export const JEV_MODEL = "typesafe/jev-1.13"
|
|
12
|
-
const ENDPOINT = "https://openrouter.ai/api/alpha/decisions"
|
|
13
|
-
const TIMEOUT_MS = 3000
|
|
14
|
-
const COOLDOWN_MS = 60_000
|
|
15
|
-
/** Kev: same oracle served from the HiveAgents LLM host (llm.hiveagents.io), tried before Jev. */
|
|
16
|
-
export const KEV_MODEL = "Kev-9B-Q8_0.gguf"
|
|
17
|
-
const KEV_DEFAULT_BASE = "https://llm.hiveagents.io"
|
|
18
|
-
const KEV_READY_TTL_MS = 30_000
|
|
19
|
-
const KEV_STATUS_TIMEOUT_MS = 2000
|
|
20
|
-
export type DecisionBackend = "kev" | "jev"
|
|
21
|
-
let failures = 0
|
|
22
|
-
let cooldownUntil = 0
|
|
23
|
-
let lastError: string | null = null
|
|
24
|
-
let lastSuccessAt: number | null = null
|
|
25
|
-
let kevFailures = 0
|
|
26
|
-
let kevCooldownUntil = 0
|
|
27
|
-
let kevReadyCache: { at: number; ready: boolean } | null = null
|
|
28
|
-
let lastBackend: DecisionBackend | null = null
|
|
29
|
-
let decisionSequence = 0
|
|
30
|
-
/** Since gateway boot; the office shows them as the oracle's running contribution. */
|
|
31
|
-
const totals = { decisions: 0, savedTokens: 0, costUsd: 0 }
|
|
32
|
-
|
|
33
|
-
export type JevQuestion =
|
|
34
|
-
| { type: "choice"; instructions: string; criteria: Record<string, string> }
|
|
35
|
-
| { type: "noul"; instructions: string; criteria?: { true: string; false: string } }
|
|
36
|
-
| { type: "score"; instructions: string; criteria?: Record<string, string> }
|
|
37
|
-
|
|
38
|
-
export type JevAnswer =
|
|
39
|
-
| { type: "choice"; choice: string; confidence: number; probabilities: Record<string, number> }
|
|
40
|
-
| { type: "noul"; noul: number }
|
|
41
|
-
| { type: "score"; score: number }
|
|
42
|
-
|
|
43
|
-
export interface JevResult {
|
|
44
|
-
answers: Record<string, JevAnswer>
|
|
45
|
-
inputTokens: number
|
|
46
|
-
costUsd: number
|
|
47
|
-
latencyMs: number
|
|
48
|
-
backend: DecisionBackend
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export async function getJevKey(): Promise<string | null> {
|
|
52
|
-
const provider = await (await col<ProviderDoc>("providers")).get("openrouter")
|
|
53
|
-
if (!provider?.doc.enabled || !provider.doc.active) return null
|
|
54
|
-
return (await loadProviderApiKey("openrouter")) || process.env.OPENROUTER_API_KEY || null
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** Kev is available when the HiveAgents LLM provider is on and has a key; readiness is checked separately. */
|
|
58
|
-
async function getKevConfig(): Promise<{ key: string; base: string } | null> {
|
|
59
|
-
const provider = await (await col<ProviderDoc>("providers")).get("hiveagents")
|
|
60
|
-
if (!provider?.doc.enabled || !provider.doc.active) return null
|
|
61
|
-
const key = (await loadProviderApiKey("hiveagents")) || process.env.HIVEAGENTS_API_KEY || null
|
|
62
|
-
if (!key) return null
|
|
63
|
-
return { key, base: provider.doc.base_url?.replace(/\/v1\/?$/, "").replace(/\/$/, "") || KEV_DEFAULT_BASE }
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/** `kev-decision.service` is toggled with systemd on the lab PC, so ask the host; cached to spare every turn a request. */
|
|
67
|
-
async function isKevReady(cfg: { key: string; base: string }, fetcher: typeof fetch): Promise<boolean> {
|
|
68
|
-
if (Date.now() < kevCooldownUntil) return false
|
|
69
|
-
if (kevReadyCache && Date.now() - kevReadyCache.at < KEV_READY_TTL_MS) return kevReadyCache.ready
|
|
70
|
-
let ready = false
|
|
71
|
-
try {
|
|
72
|
-
const response = await fetcher(`${cfg.base}/api/decisions/status`, {
|
|
73
|
-
headers: { Authorization: `Bearer ${cfg.key}` },
|
|
74
|
-
signal: AbortSignal.timeout(KEV_STATUS_TIMEOUT_MS),
|
|
75
|
-
})
|
|
76
|
-
if (response.status === 401 || response.status === 403) kevCooldownUntil = Date.now() + COOLDOWN_MS
|
|
77
|
-
else if (response.ok) {
|
|
78
|
-
const data = await response.json().catch(() => null) as { ready?: unknown } | null
|
|
79
|
-
ready = data?.ready === true
|
|
80
|
-
}
|
|
81
|
-
} catch { /* host unreachable: Kev is simply off */ }
|
|
82
|
-
kevReadyCache = { at: Date.now(), ready }
|
|
83
|
-
return ready
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** True when any decision backend could answer; callers use it to skip building questions. */
|
|
87
|
-
export async function hasDecisionBackend(): Promise<boolean> {
|
|
88
|
-
if (await getJevKey().catch(() => null)) return true
|
|
89
|
-
const kev = await getKevConfig().catch(() => null)
|
|
90
|
-
return !!kev && Date.now() >= kevCooldownUntil
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export interface JevStatus {
|
|
94
|
-
state: "off" | "ready" | "fallback"
|
|
95
|
-
backend: DecisionBackend | null
|
|
96
|
-
lastError: string | null
|
|
97
|
-
lastSuccessAt: number | null
|
|
98
|
-
totals: { decisions: number; savedTokens: number; costUsd: number }
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export async function getJevStatus(): Promise<JevStatus> {
|
|
102
|
-
const key = await getJevKey().catch(() => null)
|
|
103
|
-
const kev = await getKevConfig().catch(() => null)
|
|
104
|
-
const jevOk = !!key && Date.now() >= cooldownUntil && !lastError
|
|
105
|
-
const kevOk = !!kev && Date.now() >= kevCooldownUntil && kevFailures === 0
|
|
106
|
-
// Before any decision has been served, report who would answer: Kev only when its host says ready.
|
|
107
|
-
const kevReady = kevOk && kev ? await isKevReady(kev, fetch).catch(() => false) : false
|
|
108
|
-
return {
|
|
109
|
-
state: !key && !kev ? "off" : jevOk || kevReady ? "ready" : "fallback",
|
|
110
|
-
backend: kevReady ? "kev" : lastBackend ?? (jevOk ? "jev" : null),
|
|
111
|
-
lastError: key || kev ? lastError : null,
|
|
112
|
-
lastSuccessAt: key || kev ? lastSuccessAt : null,
|
|
113
|
-
totals: { ...totals },
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
function broadcastStatus(): void {
|
|
118
|
-
getJevStatus().then(status => emitCanvas("canvas:jev_status", status)).catch(() => { /* best effort */ })
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* Publishes a served decision to the office and persists it for the dashboard.
|
|
123
|
-
* Callers estimate savings; Jev itself only answers questions. `provider`/`model`
|
|
124
|
-
* are the advised agent's main model, used to price the avoided tokens.
|
|
125
|
-
*/
|
|
126
|
-
export function emitJevDecision({ provider, model, ...decision }: Omit<CanvasJevDecision, "eventId" | "totals"> & { provider: string; model: string }): void {
|
|
127
|
-
recordJevDecision({ agentId: decision.agentId, provider, model, savedTokens: decision.savedTokens, costUsd: decision.costUsd })
|
|
128
|
-
totals.decisions++
|
|
129
|
-
totals.savedTokens += decision.savedTokens
|
|
130
|
-
totals.costUsd += decision.costUsd
|
|
131
|
-
emitCanvas("canvas:jev_decision", {
|
|
132
|
-
...decision,
|
|
133
|
-
eventId: `jev:${Date.now().toString(36)}:${++decisionSequence}`,
|
|
134
|
-
summary: decision.summary.slice(0, 160),
|
|
135
|
-
totals: { ...totals },
|
|
136
|
-
} satisfies CanvasJevDecision)
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
export function resetJevStatus(): void {
|
|
140
|
-
failures = 0
|
|
141
|
-
cooldownUntil = 0
|
|
142
|
-
lastError = null
|
|
143
|
-
lastSuccessAt = null
|
|
144
|
-
kevFailures = 0
|
|
145
|
-
kevCooldownUntil = 0
|
|
146
|
-
kevReadyCache = null
|
|
147
|
-
lastBackend = null
|
|
148
|
-
broadcastStatus()
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function validateAnswers(questions: Record<string, JevQuestion>, data: { answers?: Record<string, JevAnswer> }): Record<string, JevAnswer> {
|
|
152
|
-
const answers: Record<string, JevAnswer> = {}
|
|
153
|
-
const unit = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1
|
|
154
|
-
for (const [name, question] of Object.entries(questions)) {
|
|
155
|
-
const answer = data.answers?.[name]
|
|
156
|
-
if (question.type === "choice") {
|
|
157
|
-
if (answer?.type !== "choice" || !Object.hasOwn(question.criteria, answer.choice) || !unit(answer.confidence)) {
|
|
158
|
-
throw new Error(`Invalid choice answer: ${name}`)
|
|
159
|
-
}
|
|
160
|
-
} else if (question.type === "score") {
|
|
161
|
-
if (answer?.type !== "score" || !unit(answer.score)) throw new Error(`Invalid score answer: ${name}`)
|
|
162
|
-
} else if (answer?.type !== "noul" || !unit(answer.noul)) {
|
|
163
|
-
throw new Error(`Invalid noul answer: ${name}`)
|
|
164
|
-
}
|
|
165
|
-
answers[name] = answer
|
|
166
|
-
}
|
|
167
|
-
return answers
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
export async function askJev(
|
|
171
|
-
state: unknown,
|
|
172
|
-
questions: Record<string, JevQuestion>,
|
|
173
|
-
options: { fetcher?: typeof fetch; signal?: AbortSignal } = {},
|
|
174
|
-
): Promise<JevResult | null> {
|
|
175
|
-
if (Object.keys(questions).length === 0) return null
|
|
176
|
-
const fetcher = options.fetcher ?? fetch
|
|
177
|
-
const kev = await getKevConfig().catch(() => null)
|
|
178
|
-
if (kev && await isKevReady(kev, fetcher)) {
|
|
179
|
-
const result = await requestDecision("kev", `${kev.base}/v1/systemone`, kev.key, KEV_MODEL, state, questions, options)
|
|
180
|
-
if (result || options.signal?.aborted) return result
|
|
181
|
-
}
|
|
182
|
-
const key = await getJevKey().catch(() => null)
|
|
183
|
-
if (!key || Date.now() < cooldownUntil) return null
|
|
184
|
-
return requestDecision("jev", ENDPOINT, key, JEV_MODEL, state, questions, options)
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
async function requestDecision(
|
|
188
|
-
backend: DecisionBackend,
|
|
189
|
-
endpoint: string,
|
|
190
|
-
key: string,
|
|
191
|
-
model: string,
|
|
192
|
-
state: unknown,
|
|
193
|
-
questions: Record<string, JevQuestion>,
|
|
194
|
-
options: { fetcher?: typeof fetch; signal?: AbortSignal },
|
|
195
|
-
): Promise<JevResult | null> {
|
|
196
|
-
const started = performance.now()
|
|
197
|
-
const label = backend === "kev" ? "Kev" : "OpenRouter"
|
|
198
|
-
try {
|
|
199
|
-
const response = await (options.fetcher ?? fetch)(endpoint, {
|
|
200
|
-
method: "POST",
|
|
201
|
-
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
|
|
202
|
-
body: JSON.stringify({ model, state, questions }),
|
|
203
|
-
signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(TIMEOUT_MS)]) : AbortSignal.timeout(TIMEOUT_MS),
|
|
204
|
-
})
|
|
205
|
-
if (!response.ok) {
|
|
206
|
-
if (response.status === 401 || response.status === 403) {
|
|
207
|
-
if (backend === "kev") kevCooldownUntil = Date.now() + COOLDOWN_MS
|
|
208
|
-
else cooldownUntil = Date.now() + COOLDOWN_MS
|
|
209
|
-
}
|
|
210
|
-
throw new Error(`${label} HTTP ${response.status}`)
|
|
211
|
-
}
|
|
212
|
-
const data = await response.json() as {
|
|
213
|
-
answers?: Record<string, JevAnswer>
|
|
214
|
-
usage?: { input_tokens?: number; output_tokens?: number; cost?: number }
|
|
215
|
-
}
|
|
216
|
-
const answers = validateAnswers(questions, data)
|
|
217
|
-
const recovered = lastError !== null
|
|
218
|
-
if (backend === "kev") kevFailures = 0
|
|
219
|
-
else failures = 0
|
|
220
|
-
lastError = null
|
|
221
|
-
lastSuccessAt = Date.now()
|
|
222
|
-
if (recovered || lastBackend !== backend) { lastBackend = backend; broadcastStatus() }
|
|
223
|
-
const inputTokens = data.usage?.input_tokens ?? 0
|
|
224
|
-
// Kev runs on our own hardware: no per-token cost.
|
|
225
|
-
const costUsd = backend === "kev" ? 0 : data.usage?.cost ?? inputTokens * 0.042 / 1_000_000
|
|
226
|
-
log.info(`Decision served: backend=${backend} questions=${Object.keys(questions).join(",")} latency_ms=${Math.round(performance.now() - started)} input_tokens=${inputTokens} cost_usd=${costUsd}`)
|
|
227
|
-
if (inputTokens > 0) {
|
|
228
|
-
const provider = backend === "kev" ? "hiveagents" : "openrouter"
|
|
229
|
-
recordUsage({ provider, model: catalogModelKey(provider, model), inputTokens, outputTokens: data.usage?.output_tokens ?? 0, latencyMs: Math.round(performance.now() - started) })
|
|
230
|
-
}
|
|
231
|
-
return { answers, inputTokens, costUsd, latencyMs: Math.round(performance.now() - started), backend }
|
|
232
|
-
} catch (error) {
|
|
233
|
-
if (options.signal?.aborted) return null
|
|
234
|
-
lastError = error instanceof Error ? error.message : `${label} unavailable`
|
|
235
|
-
if (backend === "kev") {
|
|
236
|
-
if (++kevFailures >= 3) { kevCooldownUntil = Date.now() + COOLDOWN_MS; kevReadyCache = null }
|
|
237
|
-
} else if (++failures >= 3) cooldownUntil = Date.now() + COOLDOWN_MS
|
|
238
|
-
log.warn(`Decision fallback (${backend}): ${lastError}`)
|
|
239
|
-
broadcastStatus()
|
|
240
|
-
return null
|
|
241
|
-
}
|
|
242
|
-
}
|
|
@@ -1,293 +0,0 @@
|
|
|
1
|
-
import type { LLMMessage, LLMToolDef } from "./llm-client"
|
|
2
|
-
import type { SkillDescriptor } from "./skill-selector"
|
|
3
|
-
import type { ContextTool } from "./context-compiler"
|
|
4
|
-
import type { PlaybookRule } from "./playbook-selector"
|
|
5
|
-
import { MINIMAL_TOOLS } from "./minimal-loadout"
|
|
6
|
-
import { searchCapabilities } from "./capability-search"
|
|
7
|
-
import { mcpToolFullName } from "./tool-selector"
|
|
8
|
-
import { askJev, hasDecisionBackend, type JevAnswer, type JevQuestion } from "./jev-decisions"
|
|
9
|
-
import { col } from "../storage/hive"
|
|
10
|
-
import type { AgentDoc, McpServerDoc, McpToolDoc } from "../storage/collections"
|
|
11
|
-
|
|
12
|
-
export interface JevDecisionMetrics {
|
|
13
|
-
latencyMs: number
|
|
14
|
-
costUsd: number
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/** "activo": connected now; "disponible": enabled, connects on first use; "apagado": disabled. */
|
|
18
|
-
export type JevMcpState = "activo" | "disponible" | "apagado"
|
|
19
|
-
|
|
20
|
-
export interface JevMcpServer {
|
|
21
|
-
id: string
|
|
22
|
-
name: string
|
|
23
|
-
state: JevMcpState
|
|
24
|
-
tools: number
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export interface JevSpecialist {
|
|
28
|
-
id: string
|
|
29
|
-
name: string
|
|
30
|
-
description: string
|
|
31
|
-
tools: string[]
|
|
32
|
-
mcp: Array<{ name: string; state: JevMcpState }>
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* What the swarm can do right now: every enabled worker (catalog and
|
|
37
|
-
* agent_create alike) with its tools, and every MCP server with its state.
|
|
38
|
-
* Jev routes and selects over this, so it never recommends a specialist whose
|
|
39
|
-
* MCP is off or proposes a tool that is not connected.
|
|
40
|
-
*/
|
|
41
|
-
export async function describeSwarmCapabilities(
|
|
42
|
-
mcpManager: { getServerTools(key: string): unknown[] | undefined } | null,
|
|
43
|
-
opts: { includeSpecialists: boolean },
|
|
44
|
-
): Promise<{ mcpServers: JevMcpServer[]; specialists: JevSpecialist[] }> {
|
|
45
|
-
const servers = (await (await col<McpServerDoc>("mcpServers")).scan({})).map(e => e.doc)
|
|
46
|
-
const mcpServers: JevMcpServer[] = servers.map(server => {
|
|
47
|
-
const tools = mcpManager?.getServerTools(server.id)?.length || mcpManager?.getServerTools(server.name)?.length || 0
|
|
48
|
-
return { id: server.id, name: server.name, tools, state: !server.enabled ? "apagado" : tools > 0 ? "activo" : "disponible" }
|
|
49
|
-
})
|
|
50
|
-
if (!opts.includeSpecialists) return { mcpServers, specialists: [] }
|
|
51
|
-
|
|
52
|
-
const byId = new Map(mcpServers.map(s => [s.id, s]))
|
|
53
|
-
const parse = (json: string | null | undefined): string[] => {
|
|
54
|
-
try { return json ? (JSON.parse(json) as unknown[]).map(String) : [] } catch { return [] }
|
|
55
|
-
}
|
|
56
|
-
const specialists = (await (await col<AgentDoc>("agents")).scan({}))
|
|
57
|
-
.map(e => e.doc)
|
|
58
|
-
.filter(a => a.role === "worker" && a.enabled && a.status !== "archived")
|
|
59
|
-
.map(a => ({
|
|
60
|
-
id: a.id,
|
|
61
|
-
name: a.name,
|
|
62
|
-
description: (a.description ?? a.name).slice(0, 200),
|
|
63
|
-
tools: parse(a.tool_allowlist_json).slice(0, 12),
|
|
64
|
-
mcp: parse(a.mcp_server_ids_json).map(id => byId.get(id)).filter((s): s is JevMcpServer => !!s)
|
|
65
|
-
.map(s => ({ name: s.name, state: s.state })),
|
|
66
|
-
}))
|
|
67
|
-
return { mcpServers, specialists }
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** One roster line: what the coordinator needs to pick a specialist without calling agent_find. */
|
|
71
|
-
export function renderSpecialistLine(s: JevSpecialist): string {
|
|
72
|
-
const mcp = s.mcp.length ? ` · MCP: ${s.mcp.map(m => `${m.name} (${m.state})`).join(", ")}` : ""
|
|
73
|
-
return `- ${s.id} (${s.name})${mcp}`
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export interface JevContextPlan {
|
|
77
|
-
messages: LLMMessage[]
|
|
78
|
-
tools: LLMToolDef[]
|
|
79
|
-
skills: SkillDescriptor[]
|
|
80
|
-
agentId: string | null
|
|
81
|
-
/**
|
|
82
|
-
* MCP servers the recommended specialist depends on that are off. Non-empty
|
|
83
|
-
* means "this is the right specialist, but the user must turn these on
|
|
84
|
-
* first" — delegating now would hand it a task it cannot do.
|
|
85
|
-
*/
|
|
86
|
-
agentMcpOff: string[]
|
|
87
|
-
selectedMessageIds: number[]
|
|
88
|
-
selectedToolNames: string[]
|
|
89
|
-
selectedSkillNames: string[]
|
|
90
|
-
selectedScratchpadKeys: string[]
|
|
91
|
-
selectedPlaybookIds: string[]
|
|
92
|
-
decision: JevDecisionMetrics
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const excerpt = (value: unknown, max = 450): string =>
|
|
96
|
-
(typeof value === "string" ? value : JSON.stringify(value) ?? "").slice(0, max)
|
|
97
|
-
const probability = (answer: JevAnswer | undefined): number | null => answer?.type === "noul" ? answer.noul : null
|
|
98
|
-
const MANDATORY_TAIL = 4
|
|
99
|
-
/** Below this many characters of prunable tool output, a decision costs more latency than it saves. */
|
|
100
|
-
const MIN_PRUNABLE_CHARS = 4000
|
|
101
|
-
|
|
102
|
-
/** Decisions select only from already authorized, discoverable candidates. */
|
|
103
|
-
export async function planJevContext(input: {
|
|
104
|
-
objective: string
|
|
105
|
-
messages: LLMMessage[]
|
|
106
|
-
tools: LLMToolDef[]
|
|
107
|
-
allTools: ContextTool[]
|
|
108
|
-
skills: SkillDescriptor[]
|
|
109
|
-
scratchpadNotes?: Array<{ key: string; value: string }>
|
|
110
|
-
playbookRules?: PlaybookRule[]
|
|
111
|
-
isWorker: boolean
|
|
112
|
-
/** From describeSwarmCapabilities; absent means "unknown", not "none". */
|
|
113
|
-
swarm?: { mcpServers: JevMcpServer[]; specialists: JevSpecialist[] }
|
|
114
|
-
}): Promise<JevContextPlan | null> {
|
|
115
|
-
if (!await hasDecisionBackend().catch(() => false)) return null
|
|
116
|
-
const { objective, messages, tools, allTools, skills, isWorker } = input
|
|
117
|
-
const mandatoryMessages = new Set<number>()
|
|
118
|
-
// The last two exchanges carry the thread's immediate referents ("hazlo otra
|
|
119
|
-
// vez", "el anterior"); dropping them sent the model into conversation_read loops.
|
|
120
|
-
for (let i = Math.max(0, messages.length - MANDATORY_TAIL); i < messages.length; i++) mandatoryMessages.add(i)
|
|
121
|
-
messages.forEach((message, i) => {
|
|
122
|
-
if (Array.isArray(message.content) || (typeof message.content === "string" && message.content.startsWith("<hive:internal_event"))) mandatoryMessages.add(i)
|
|
123
|
-
})
|
|
124
|
-
|
|
125
|
-
const candidateMessageIds = messages.map((_, i) => i).filter(i => !mandatoryMessages.has(i))
|
|
126
|
-
let candidateTools: ContextTool[] = tools.filter(t => !MINIMAL_TOOLS.has(t.function.name))
|
|
127
|
-
.map(t => allTools.find(a => a.name === t.function.name))
|
|
128
|
-
.filter((t): t is ContextTool => !!t)
|
|
129
|
-
try {
|
|
130
|
-
const hits = await searchCapabilities(objective, { types: ["tool", "mcp"], k: 12 })
|
|
131
|
-
// allTools only holds MCP tools of servers that are enabled, connected and
|
|
132
|
-
// allowed for this agent — resolving through it is what keeps a dormant or
|
|
133
|
-
// foreign server's tools out of the plan.
|
|
134
|
-
const available = new Map(allTools.map(t => [t.name, t]))
|
|
135
|
-
const mcpTools = await col<McpToolDoc>("mcpTools")
|
|
136
|
-
const names = await Promise.all(hits.map(async h => {
|
|
137
|
-
if (h.type !== "mcp") return h.rawId
|
|
138
|
-
const tool = (await mcpTools.get(h.rawId))?.doc
|
|
139
|
-
return tool ? mcpToolFullName(tool.server_name, tool.tool_name) : null
|
|
140
|
-
}))
|
|
141
|
-
const discovered = names.map(n => n ? available.get(n) : undefined).filter((t): t is ContextTool => !!t && !MINIMAL_TOOLS.has(t.name))
|
|
142
|
-
candidateTools = [...new Map([...candidateTools, ...discovered].map(t => [t.name, t])).values()].slice(0, 24)
|
|
143
|
-
} catch { /* index unavailable: retain the current loadout */ }
|
|
144
|
-
|
|
145
|
-
const optionalSkills = skills.filter(s => s.active && s.body).slice(0, 8)
|
|
146
|
-
const scratchpadNotes = (input.scratchpadNotes ?? []).slice(-16)
|
|
147
|
-
const playbookRules = (input.playbookRules ?? []).slice(0, 8)
|
|
148
|
-
// Specialists with an MCP off stay eligible: Jev still names the right one,
|
|
149
|
-
// and the coordinator asks the user to turn the server on instead of
|
|
150
|
-
// delegating a task the specialist cannot do yet.
|
|
151
|
-
const agents = isWorker ? [] : (input.swarm?.specialists ?? []).slice(0, 16)
|
|
152
|
-
const questions: Record<string, JevQuestion> = {}
|
|
153
|
-
for (const i of candidateMessageIds) questions[`history_${i}`] = { type: "noul", instructions: `Is earlier conversation item ${i} necessary to complete the current objective?` }
|
|
154
|
-
for (const tool of candidateTools) questions[`tool_${tool.name}`] = { type: "noul", instructions: `Will tool ${tool.name} likely be needed for the current objective?` }
|
|
155
|
-
for (const skill of optionalSkills) questions[`skill_${skill.id}`] = { type: "noul", instructions: `Are instructions from skill ${skill.name} needed for the current objective?` }
|
|
156
|
-
for (const note of scratchpadNotes) questions[`note_${note.key}`] = { type: "noul", instructions: `Is scratchpad note ${note.key} needed for the current objective?` }
|
|
157
|
-
for (const rule of playbookRules) questions[`rule_${rule.id}`] = { type: "noul", instructions: `Does playbook rule ${rule.id} apply to the current objective?` }
|
|
158
|
-
if (agents.length) questions.agent = {
|
|
159
|
-
type: "choice", instructions: "Which existing specialist should handle a bounded part of this objective, or should the coordinator handle it?",
|
|
160
|
-
criteria: {
|
|
161
|
-
coordinator: "No bounded specialist task is needed",
|
|
162
|
-
...Object.fromEntries(agents.map(a => [a.id, [
|
|
163
|
-
a.description,
|
|
164
|
-
a.tools.length ? `tools: ${a.tools.join(", ")}` : "",
|
|
165
|
-
a.mcp.length ? `MCP: ${a.mcp.map(m => `${m.name} (${m.state})`).join(", ")}` : "",
|
|
166
|
-
].filter(Boolean).join(" · ").slice(0, 400)])),
|
|
167
|
-
},
|
|
168
|
-
}
|
|
169
|
-
const decision = await askJev({
|
|
170
|
-
objective: objective.slice(0, 3500),
|
|
171
|
-
history: candidateMessageIds.map(i => ({ id: i, role: messages[i].role, content: excerpt(messages[i].content) })),
|
|
172
|
-
tools: candidateTools.map(t => ({ name: t.name, description: t.description.slice(0, 240) })),
|
|
173
|
-
skills: optionalSkills.map(s => ({ id: s.id, name: s.name, description: s.description.slice(0, 240) })),
|
|
174
|
-
notes: scratchpadNotes.map(n => ({ key: n.key, value: n.value.slice(0, 350) })),
|
|
175
|
-
rules: playbookRules.map(r => ({ id: r.id, rule: r.rule.slice(0, 350) })),
|
|
176
|
-
mcp_servers: (input.swarm?.mcpServers ?? []).map(s => ({ name: s.name, state: s.state, tools: s.tools })),
|
|
177
|
-
}, questions)
|
|
178
|
-
if (!decision) return null
|
|
179
|
-
|
|
180
|
-
const selected = new Set(messages.map((_, i) => i).filter(i => mandatoryMessages.has(i) ||
|
|
181
|
-
!candidateMessageIds.includes(i) || (probability(decision.answers[`history_${i}`]) ?? 1) >= 0.35))
|
|
182
|
-
// A reply travels with the user turn it answered: Gemini silently drops a
|
|
183
|
-
// model turn that has no preceding user turn.
|
|
184
|
-
for (const i of [...selected]) {
|
|
185
|
-
if (messages[i].role !== "assistant") continue
|
|
186
|
-
for (let j = i - 1; j >= 0; j--) if (messages[j].role === "user") { selected.add(j); break }
|
|
187
|
-
}
|
|
188
|
-
const selectedMessageIds = [...selected].sort((a, b) => a - b)
|
|
189
|
-
const selectedToolNames = candidateTools.filter(t => (probability(decision.answers[`tool_${t.name}`]) ?? 1) >= 0.35).map(t => t.name)
|
|
190
|
-
const selectedSkills = optionalSkills.filter(s => (probability(decision.answers[`skill_${s.id}`]) ?? 1) >= 0.35)
|
|
191
|
-
const toolMap = new Map(allTools.map(t => [t.name, t]))
|
|
192
|
-
const selectedNames = new Set(selectedToolNames)
|
|
193
|
-
const candidateNames = new Set(candidateTools.map(t => t.name))
|
|
194
|
-
const combinedTools = tools.filter(t => !candidateNames.has(t.function.name) || selectedNames.has(t.function.name))
|
|
195
|
-
for (const name of selectedToolNames) {
|
|
196
|
-
const tool = toolMap.get(name)
|
|
197
|
-
if (tool && !combinedTools.some(t => t.function.name === name)) combinedTools.push({
|
|
198
|
-
type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters },
|
|
199
|
-
})
|
|
200
|
-
}
|
|
201
|
-
const agentAnswer = decision.answers.agent
|
|
202
|
-
const agentId = agentAnswer?.type === "choice" && agentAnswer.confidence >= 0.7 && agentAnswer.choice !== "coordinator"
|
|
203
|
-
? agentAnswer.choice : null
|
|
204
|
-
const agentMcpOff = agents.find(a => a.id === agentId)?.mcp.filter(m => m.state === "apagado").map(m => m.name) ?? []
|
|
205
|
-
return {
|
|
206
|
-
messages: selectedMessageIds.map(i => messages[i]), tools: combinedTools,
|
|
207
|
-
skills: selectedSkills, agentId, agentMcpOff, selectedMessageIds, selectedToolNames,
|
|
208
|
-
selectedSkillNames: selectedSkills.map(s => s.name),
|
|
209
|
-
selectedScratchpadKeys: scratchpadNotes.filter(n => (probability(decision.answers[`note_${n.key}`]) ?? 1) >= 0.35).map(n => n.key),
|
|
210
|
-
selectedPlaybookIds: playbookRules.filter(r => (probability(decision.answers[`rule_${r.id}`]) ?? 1) >= 0.35).map(r => r.id),
|
|
211
|
-
decision: { latencyMs: decision.latencyMs, costUsd: decision.costUsd },
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/**
|
|
216
|
-
* Only independent reads, or separate delegated tasks, may execute concurrently.
|
|
217
|
-
* null leaves the batch to the runtime default; `decision` is present only when Jev was asked.
|
|
218
|
-
*/
|
|
219
|
-
export async function jevWantsParallel(calls: Array<{ function: { name: string; arguments: unknown } }>): Promise<{ parallel: boolean; decision?: JevDecisionMetrics } | null> {
|
|
220
|
-
if (calls.length < 2) return null
|
|
221
|
-
if (!await hasDecisionBackend().catch(() => false)) return null
|
|
222
|
-
const names = calls.map(c => c.function.name)
|
|
223
|
-
const readOnly = names.every(n => /^(fs_read|fs_list|fs_glob|fs_exists|web_search|web_fetch|memory_read|memory_search|artifact_read|artifact_inspect|task_status|agent_find)$/.test(n))
|
|
224
|
-
const delegated = names.every(n => n === "task_delegate")
|
|
225
|
-
if (!readOnly && !delegated) return { parallel: false }
|
|
226
|
-
if (delegated) {
|
|
227
|
-
const ids = calls.map(call => {
|
|
228
|
-
try {
|
|
229
|
-
const args = typeof call.function.arguments === "string" ? JSON.parse(call.function.arguments) : call.function.arguments
|
|
230
|
-
return String(args?.worker_id ?? "")
|
|
231
|
-
} catch { return "" }
|
|
232
|
-
})
|
|
233
|
-
if (ids.some(id => !id) || new Set(ids).size !== ids.length) return { parallel: false }
|
|
234
|
-
const agentsCol = await col<AgentDoc>("agents")
|
|
235
|
-
const agents = await Promise.all(ids.map(id => agentsCol.get(id)))
|
|
236
|
-
const workspaces = agents.map(row => row?.doc.workspace)
|
|
237
|
-
if (workspaces.some(path => !path) || new Set(workspaces).size !== workspaces.length) return { parallel: false }
|
|
238
|
-
}
|
|
239
|
-
const result = await askJev({ calls: calls.map(c => ({ tool: c.function.name, arguments: excerpt(c.function.arguments, 700) })) }, {
|
|
240
|
-
independent: { type: "noul", instructions: "Can every listed operation run concurrently without needing the result of another listed operation?" },
|
|
241
|
-
})
|
|
242
|
-
const answer = result?.answers.independent
|
|
243
|
-
return result && answer?.type === "noul"
|
|
244
|
-
? { parallel: answer.noul >= 0.8, decision: { latencyMs: result.latencyMs, costUsd: result.costUsd } }
|
|
245
|
-
: null
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
export async function planJevIteration(input: {
|
|
249
|
-
objective: string
|
|
250
|
-
messages: LLMMessage[]
|
|
251
|
-
tools: LLMToolDef[]
|
|
252
|
-
}): Promise<{ messages: LLMMessage[]; tools: LLMToolDef[]; action: string; omittedResults: number; decision: JevDecisionMetrics } | null> {
|
|
253
|
-
const toolIndices = input.messages.map((m, i) => m.role === "tool" ? i : -1).filter(i => i >= 0)
|
|
254
|
-
if (!toolIndices.length) return null
|
|
255
|
-
const older = toolIndices.slice(0, -1).slice(-8)
|
|
256
|
-
const prunableChars = older.reduce((sum, i) => sum + excerpt(input.messages[i].content, Infinity).length, 0)
|
|
257
|
-
if (prunableChars < MIN_PRUNABLE_CHARS) return null
|
|
258
|
-
const questions: Record<string, JevQuestion> = {
|
|
259
|
-
action: {
|
|
260
|
-
type: "choice",
|
|
261
|
-
instructions: "What capability should the text model use next to complete the current objective?",
|
|
262
|
-
criteria: {
|
|
263
|
-
continue: "Continue reasoning with currently available tools",
|
|
264
|
-
delegate: "Formulate a bounded task for an existing specialist",
|
|
265
|
-
discover: "Discover another tool or skill before continuing",
|
|
266
|
-
finish: "The evidence is sufficient to compose the final answer without more tools",
|
|
267
|
-
},
|
|
268
|
-
},
|
|
269
|
-
}
|
|
270
|
-
for (const i of older) questions[`result_${i}`] = {
|
|
271
|
-
type: "noul", instructions: `Is result ${i} still needed to complete the current objective?`,
|
|
272
|
-
}
|
|
273
|
-
const result = await askJev({
|
|
274
|
-
objective: input.objective.slice(0, 2800),
|
|
275
|
-
results: toolIndices.slice(-9).map(i => ({ id: i, tool: input.messages[i].name, content: excerpt(input.messages[i].content, 650) })),
|
|
276
|
-
}, questions)
|
|
277
|
-
if (!result) return null
|
|
278
|
-
const omitted = new Set(older.filter(i => (probability(result.answers[`result_${i}`]) ?? 1) < 0.35))
|
|
279
|
-
const projected = input.messages.map((m, i) => omitted.has(i)
|
|
280
|
-
? { ...m, content: "[Previous tool result omitted from this call]" } : m)
|
|
281
|
-
const answer = result.answers.action
|
|
282
|
-
const latestResult = input.messages[toolIndices[toolIndices.length - 1]]
|
|
283
|
-
const resultFailed = typeof latestResult.content === "string" && (latestResult.content.startsWith("[Tool Error]") || latestResult.content.includes('"error":true'))
|
|
284
|
-
const proposedAction = answer?.type === "choice" && answer.confidence >= (answer.choice === "finish" ? 0.85 : 0.7) ? answer.choice : "continue"
|
|
285
|
-
const action = proposedAction === "finish" && resultFailed ? "continue" : proposedAction
|
|
286
|
-
let tools = input.tools
|
|
287
|
-
if (action === "finish") tools = []
|
|
288
|
-
else if (action === "delegate") tools = tools.filter(t => ["task_delegate", "agent_find", "search_knowledge"].includes(t.function.name))
|
|
289
|
-
else if (action === "discover") tools = tools.filter(t => t.function.name === "search_knowledge")
|
|
290
|
-
const decision = { latencyMs: result.latencyMs, costUsd: result.costUsd }
|
|
291
|
-
if (action !== "finish" && tools.length === 0) return { messages: projected, tools: input.tools, action: "continue", omittedResults: omitted.size, decision }
|
|
292
|
-
return { messages: projected, tools, action, omittedResults: omitted.size, decision }
|
|
293
|
-
}
|