Files
hermes-canopy/plugin.js
T

285 lines
16 KiB
JavaScript

import {host, useQuery, useQueryClient, useValue} from '@hermes/plugin-sdk'
import {useEffect, useId, useState} from 'react'
import {jsx as h} from 'react/jsx-runtime'
const ID = 'hermes-canopy'
const PAGE_SIZE = 200
const PERSISTED_LIMIT = 500
const HIDDEN_SOURCES = new Set(['bot_room', 'kanban', 'tool', 'oneshot'])
const idText = v => typeof v === 'string' && v.trim() === v && v ? v : null
const text = v => typeof v === 'string' ? v.trim() : ''
const activity = v => Number.isFinite(v) && v > 0 && v < 253402300800 ? v : 0
const identity = r => JSON.stringify([r.connectionId, r.profile, r.targetProfile, r.mode])
const collator = new Intl.Collator('de', {numeric:true})
const timeFormat = new Intl.DateTimeFormat('de', {day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})
export async function routesFor(api, connection) {
if (!idText(connection)) throw Error('Keine eindeutige Gateway-Verbindung.')
const routes = await api.profileRoutes()
if (!Array.isArray(routes)) throw Error('Profilverzeichnis nicht verfügbar.')
const byProfile = new Map()
for (const r of routes) {
if (r?.connectionId !== connection) continue
if (!idText(r.profile) || !idText(r.targetProfile) || !['local','remote'].includes(r.mode)) {
throw Error('Ungültige Profilroute.')
}
if (byProfile.has(r.profile) && identity(byProfile.get(r.profile)) !== identity(r)) throw Error('Mehrdeutige Profilroute.')
byProfile.set(r.profile,r)
}
if (!byProfile.size) throw Error('Keine erreichbaren Profile auf diesem Gateway.')
return [...byProfile.values()].sort((a,b)=>collator.compare(a.profile,b.profile))
}
function parseList(res, scope) {
if (res?.scope !== scope || !Array.isArray(res.sessions) || res.sessions.length > PAGE_SIZE ||
(scope === 'stored' && res.next_cursor !== null && !idText(res.next_cursor))) {
throw Error('Dieses Gateway meldet keinen unterstützten Session-/Paginationsvertrag.')
}
return res.sessions
}
function normalized(r) {
if (r?.hidden || r?.archived || r?.auto_archived || r?.is_internal_child || HIDDEN_SOURCES.has(r?.source)) return null
if (!idText(r?.id) || !idText(r?.session_id)) {
throw Error('Unvollständige Session-Metadaten.')
}
const aliases = [...new Set([r.id,r.session_id,r.resolved_id,r._lineage_root_id,
...(Array.isArray(r._lineage_ids) ? r._lineage_ids : [])].filter(idText))]
return {id:r.session_id, aliases, title:text(r.title) || 'Unbenannte Unterhaltung',
lastActive:activity(r.last_active_at) || activity(r.last_active) || activity(r.started_at)}
}
function unsupportedList(error) {
return error?.code === -32601 || error?.code === -32602 ||
(error?.code === 4001 && error?.data?.reason === 'invalid_params')
}
async function loadPersisted(api, route, signal) {
signal?.throwIfAborted()
if (typeof api.listPersistedSessions !== 'function') {
throw Error('Dieses Gateway meldet keinen unterstützten Session-/Paginationsvertrag.')
}
const result = await api.listPersistedSessions(route,{profile:route.targetProfile,limit:PERSISTED_LIMIT})
signal?.throwIfAborted()
if (!Array.isArray(result?.sessions) || !Number.isSafeInteger(result.total) || result.total < 0 ||
result.offset !== 0 || !Number.isSafeInteger(result.limit) || result.limit < 1 || result.limit > PERSISTED_LIMIT ||
(result.errors !== undefined && !Array.isArray(result.errors))) {
throw Error('Die gespeicherte Sessionliste hat ein unbekanntes Format.')
}
if (result.errors?.length || result.storage?.[route.targetProfile] === 'corrupt') {
throw Error('Der Profilspeicher konnte nicht vollständig gelesen werden.')
}
if (result.sessions.some(row=>row?.profile !== route.targetProfile)) {
throw Error('Die gespeicherte Sessionliste enthält eine fremde Profilzuordnung.')
}
return {sessions:mergeRows(result.sessions.map(row=>({...row,session_id:row.id}))),liveAtLimit:false,
storedAtLimit:result.total > result.limit || result.sessions.length >= result.limit}
}
export async function loadBot(api, route, signal) {
const request = (scope, cursor) => {
signal?.throwIfAborted()
return api.requestProfile(route,'session.list',{profile:route.targetProfile,scope,
limit:PAGE_SIZE,include_hidden:false,picker:true,...(cursor ? {cursor} : {})},20000)
}
let first
try {first = await request('stored')} catch (error) {
if (!unsupportedList(error) || typeof api.listPersistedSessions !== 'function') throw error
return loadPersisted(api,route,signal)
}
if (Array.isArray(first?.sessions) && first.next_cursor === undefined &&
(first.scope === undefined || first.scope === 'stored')) return loadPersisted(api,route,signal)
const rows = [...parseList(first,'stored')]
const seen = new Set()
for (let cursor = first.next_cursor; cursor !== null;) {
if (seen.has(cursor)) throw Error('Wiederholter Cursor: Abruf wurde abgebrochen.')
seen.add(cursor)
const page = await request('stored',cursor)
rows.push(...parseList(page,'stored'))
cursor = page.next_cursor
}
const live = parseList(await request('live'),'live')
signal?.throwIfAborted()
return {sessions:mergeRows([...live,...rows]),liveAtLimit:live.length === PAGE_SIZE}
}
function mergeRows(rows) {
const identities = new Map()
// Live rows win on the navigation ID; stored rows may carry additional aliases.
for (const record of rows) {
const r = normalized(record)
if (!r) continue
const matches = [...new Set(r.aliases.map(a=>identities.get(a)).filter(Boolean))]
const merged = matches[0] ?? r
merged.aliases = [...new Set([...merged.aliases,...r.aliases,...matches.flatMap(m=>m.aliases)])]
merged.lastActive = Math.max(merged.lastActive,r.lastActive,...matches.map(m=>m.lastActive))
for (const alias of merged.aliases) identities.set(alias,merged)
}
return [...new Set(identities.values())].sort((a,b)=>collator.compare(a.title,b.title) || collator.compare(a.id,b.id))
}
export async function openExisting(api, connection, route, session, inventory) {
const stillConnected = () => api.state.connectionId.get() === connection && api.state.gateway.get() === 'open'
if (!stillConnected()) throw Error('Gateway ist nicht verbunden.')
const current = await routesFor(api,connection)
if (!stillConnected() || !current.some(r=>identity(r) === identity(route))) throw Error('Profilroute nicht mehr verfügbar.')
const has = entry => entry.sessions?.some(s=>s.id === session.id)
if (!inventory.some(entry=>identity(entry.route) === identity(route) && has(entry))) {
throw Error('Die Unterhaltung ist nicht mehr verfügbar.')
}
const aliases = new Set(session.aliases)
if (inventory.some(entry=>entry.route.connectionId === connection && identity(entry.route) !== identity(route) &&
entry.sessions?.some(other=>other.aliases.some(a=>aliases.has(a))))) {
throw Error('Die Session-ID ist nicht eindeutig. Bitte über „Sessions“ öffnen.')
}
const owner = api.state.focusedSessionOwner?.get()
const currentId = api.state.focusedStoredSessionId?.get()
if (aliases.has(currentId) && (!owner || owner.connectionId !== connection || owner.profile !== route.profile)) {
throw Error('Die aktive Session-ID ist nicht eindeutig.')
}
await api.openSession(session.id,{route,intent:'in-place',awaitHydration:true,keepAllProfilesScope:true})
}
export function avatarSource(value) {
return value?.found === true && typeof value.data === 'string' && value.data.length <= 3000000 &&
/^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/]+=*$/i.test(value.data) ? value.data : null
}
async function loadMetadata(api, route) {
const res = await api.requestProfile(route,'profiles.list',{profile:route.targetProfile,include_sessions:false},15000)
if (!Array.isArray(res?.profiles)) throw Error('Profilmetadaten nicht verfügbar.')
return Object.fromEntries(res.profiles.filter(p=>idText(p?.name)).map(p=>[p.name,{
name:text(p.ui_meta?.['hermes-bots']?.title) || text(p.display_name) || p.name, hasAvatar:p.has_avatar === true,
}]))
}
const el = (type, props, ...children) => h(type,children.length ? {
...props,children:children.length === 1 ? children[0] : children,
} : props)
const sr = {color:'var(--ui-text-secondary)',fontSize:'0.85em',margin:'6px 0'}
const clip = {minWidth:0,overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis'}
const line = {display:'flex',gap:6,alignItems:'center',textAlign:'start',width:'100%'}
const control = {padding:'5px 6px',borderRadius:5,color:'inherit',cursor:'pointer'}
const list = {margin:0,padding:0,listStyle:'none'}
const message = (value, error=false) => el('p',{role:error?'alert':'status',style:sr},value)
function Avatar({route, name, enabled}) {
const image = useQuery({queryKey:[ID,'avatar',identity(route)],enabled,
queryFn:async()=>avatarSource(await host.requestProfile(route,'profiles.get_asset',{
profile:route.targetProfile,name:route.targetProfile,asset:'avatar'},12000)),staleTime:300000,retry:false})
const src = image.data
const [failed,setFailed] = useState(null)
const style = {width:23,height:23,borderRadius:'50%',flex:'0 0 auto',display:'grid',placeItems:'center',
objectFit:'cover',background:'var(--ui-stroke-secondary)',fontSize:'0.7em'}
return src && failed !== src ? el('img',{src,alt:'',style,onError:()=>setFailed(src)}) :
el('span',{'aria-hidden':true,style},(name.match(/[\p{L}\p{N}]/gu) ?? ['?']).slice(0,2).join('').toUpperCase())
}
const botKey = r => [ID,'bot',r.connectionId,identity(r)]
function Bot({route, connection, meta, online, expanded, toggle, routes, setNotice, busy, setBusy, openLock}) {
const listId = useId()
const client = useQueryClient()
const [shown,setShown] = useState(25)
const focused = useValue(host.state.focusedStoredSessionId)
const owner = useValue(host.state.focusedSessionOwner)
const q = useQuery({queryKey:botKey(route),enabled:expanded && online,
queryFn:({signal})=>loadBot(host,route,signal),staleTime:20000,
refetchInterval:expanded && online ? 90000 : false,retry:false})
const botName = meta?.name || route.profile
const select = async (s) => {
if (openLock.current) return
openLock.current = true
setNotice('')
setBusy(true)
try {
const entries = routes.map(r=>({route:r,sessions: client.getQueryData(botKey(r))?.sessions}))
await openExisting(host,connection,route,s,entries)
} catch (error) {
setNotice(error.message?.startsWith('Die ') || error.message?.startsWith('Profilroute') || error.message?.startsWith('Gateway ist')
? error.message : 'Unterhaltung konnte nicht geöffnet werden.')
} finally {openLock.current = false; setBusy(false)}
}
return el('li',null,
el('button',{type:'button','aria-expanded':expanded,'aria-controls':listId,onClick:toggle,
title:botName,style:{...line,...control}},
el('span',{'aria-hidden':true},expanded?'▾':'▸'),h(Avatar,{route,name:botName,enabled:online && !!meta?.hasAvatar}),
el('strong',{style:clip},botName)),
el('div',{id:listId,hidden:!expanded,style:{marginInlineStart:12,paddingInlineStart:8,borderInlineStart:'1px solid var(--ui-stroke-secondary)'}},
!expanded ? null : [
q.isPending && online && message('Unterhaltungen werden geladen …'),
!online && message('Gateway nicht verbunden.'),
q.isError && el('div',null,
message('Unterhaltungen konnten für dieses Profil nicht geladen werden.',true),
el('button',{type:'button',style:control,disabled:!online,onClick:()=>q.refetch()},'Erneut versuchen')),
q.isSuccess && q.data.sessions.length === 0 && message('Keine sichtbaren Unterhaltungen.'),
q.data?.liveAtLimit && message('Das Gateway begrenzt seine Liste laufender Sessions. Weitere aktive Unterhaltungen können fehlen.',true),
q.data?.storedAtLimit && message('Das SDK begrenzt die Kompatibilitätsliste. Weitere Unterhaltungen findest du im Reiter „Sessions“.',true),
el('ul',{style:list},...(q.data?.sessions ?? []).slice(0,shown).map(s=>{
const active = owner?.connectionId === connection && owner.profile === route.profile && s.aliases.includes(focused)
const stamp = s.lastActive ? new Date(s.lastActive*1000) : null
return h('li',{children:el('button',{type:'button',title:s.title,disabled:!online || busy || q.isError,
'aria-current':active?'true':undefined,onClick:()=>select(s),style:{...line,...control,
...(active?{fontWeight:650,background:'var(--ui-stroke-secondary)'}:{})}},
el('span',{style:{...clip,flex:'1 1 auto'}},s.title),
stamp && el('time',{dateTime:stamp.toISOString(),style:{...sr,whiteSpace:'nowrap',margin:0}},timeFormat.format(stamp)))},s.id)
})),
(q.data?.sessions.length ?? 0)>shown && el('button',{type:'button',style:control,onClick:()=>setShown(n=>n+25)},'Weitere Sessions anzeigen'),
]))
}
function Overview({ctx}) {
const connection = useValue(host.state.connectionId)
const activeProfile = useValue(host.state.profile)
const online = useValue(host.state.gateway) === 'open'
const client = useQueryClient()
const [openLock] = useState(()=>({current:false}))
const [busy,setBusy] = useState(false)
const [notice,setNotice] = useState('')
const [open,setOpen] = useState(()=>{
try {const v = ctx.storage.get('expanded-v1'); return Array.isArray(v)?new Set(v.filter(idText)):new Set()} catch {return new Set()}
})
useEffect(()=>{
try {ctx.storage.set('expanded-v1',[...open])} catch {/* preferences are optional */}
},[ctx,open])
useEffect(()=>{
if (!connection || !online) return
let timer
const off = ctx.onEvent('sessions.changed',()=>{
if (timer !== undefined) return
timer = setTimeout(()=>{timer=undefined; void client.invalidateQueries({queryKey:[ID,'bot',connection]})},750)
})
return ()=>{off();clearTimeout(timer)}
},[ctx,client,connection,online])
const directory = useQuery({queryKey:[ID,'routes',connection],enabled:!!connection && online,
queryFn:()=>routesFor(host,connection),staleTime:30000,refetchInterval:online?90000:false,retry:false})
const routes = directory.data ?? []
const home = routes.find(r=>r.profile === activeProfile) ?? routes[0]
const meta = useQuery({queryKey:[ID,'profiles',home && identity(home)],enabled:!!home && online,
queryFn:()=>loadMetadata(host,home),staleTime:60000,refetchInterval:online?90000:false,retry:false})
const toggle = route => setOpen(previous=>{
const next = new Set(previous), key = identity(route)
if (next.has(key)) next.delete(key); else next.add(key)
return next
})
return el('section',{'aria-label':'Bot- und Sessionübersicht',style:{height:'100%',overflow:'auto',padding:'6px 8px'}},
message('Bot Chat bleibt im Reiter „Bots“.'),
!online && message('Gateway ist nicht verbunden.'),
online && directory.isPending && message('Profile werden geladen …'),
online && directory.isError && el('div',null,message('Profilverzeichnis nicht verfügbar.',true),
el('button',{type:'button',style:control,onClick:()=>directory.refetch()},'Erneut versuchen')),
online && meta.isError && message('Anzeigenamen und Avatare nicht verfügbar; Profilnamen werden verwendet.'),
notice && message(notice,true),
el('ul',{style:list},...routes.map(route=>h(Bot,{route,connection,meta:meta.data?.[route.targetProfile],online:online && !directory.isError,
expanded:open.has(identity(route)),toggle:()=>toggle(route),routes,setNotice,busy,setBusy,openLock},identity(route)))))
}
export default {
id:ID,name:'Hermes Canopy',version:'0.1.2',defaultEnabled:false,
description:'Ein Baum für Bots und ihre bestehenden Unterhaltungen auf einem Gateway.',
register(ctx) {
ctx.register({id:'overview',area:'panes',title:'Übersicht',order:900,
data:{placement:'left',collapsible:true,hideOnly:true,dock:{pane:'sessions',pos:'center'}},
render:()=>h(Overview,{ctx})})
},
}