@datalayer/agent-runtimes 1.5.114 → 1.5.115

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.
@@ -3725,7 +3725,7 @@ ${Du}`:ju,inputs:Du,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
3725
3725
 
3726
3726
  ${$u}`:Au.prompt}function modeDefaults(Au){return Object.fromEntries((Au.interface.modes??[]).filter(lo=>lo.options.length>0).map(lo=>[lo.id,lo.default||lo.options[0].id]))}function modeChoice(Au,lo={}){const $u=Au.interface.modes??[];for(const[Ru,Iu]of Object.entries(lo)){const Pu=$u.find(Ou=>Ou.id===Ru);if(!Pu)throw new Error(`${Au.name} has no mode “${Ru}”.`);if(!Pu.options.some(Ou=>Ou.id===Iu))throw new Error(`The mode ${Pu.label} has no option “${Iu}”.`)}return{...modeDefaults(Au),...lo}}function profileChoice(Au,lo){const $u=Au.interface.profiles??[];if(lo){const Ru=$u.find(Iu=>Iu.id===lo);if(!Ru)throw new Error($u.length===0?`${Au.name} has no profiles: “${lo}” cannot be chosen.`:`${Au.name} has no profile “${lo}”.`);return Ru}return $u[0]}function startersFor(Au,lo){const $u=profileChoice(Au,lo);return $u&&$u.starters.length>0?$u.starters:Au.interface.starters}function modeEffect(Au,lo={},$u){const Ru=modeChoice(Au,lo),Iu=profileChoice(Au,$u),Pu=(Au.interface.modes??[]).flatMap(Mu=>Mu.options.filter(Lu=>Lu.id===Ru[Mu.id])),Ou=[Iu?.instructions??"",...Pu.map(Mu=>Mu.instructions??"")].map(Mu=>Mu.trim()).filter(Boolean).join(`
3727
3727
 
3728
- `),Du=Pu.find(Mu=>Mu.model)?.model??Iu?.model??void 0;return Du?{instructions:Ou,model:Du}:{instructions:Ou}}async function holdUploads(Au,lo,$u,Ru=readFile){const Iu=uploadsRefusal(Au,[...lo,...$u.map(Pu=>({name:Pu.name,type:Pu.type,size:Pu.size}))]);return Iu?{files:[...lo],refused:Iu}:{files:[...lo,...await Promise.all($u.map(Ru))],refused:null}}const APP_COMPOSER_PLUGIN_NAME="@datalayer/loop-plugin-app-composer";function startersAsOpeners(Au){return Au.map(lo=>({text:lo.label,message:lo.message,...lo.category?{group:lo.category}:{}}))}const needsAppComposer=Au=>(Au.interface.commands??[]).length>0||(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0||!!Au.interface.uploads;function defineAppComposerPlugin(Au){const lo=Au.interface.profiles??[],$u=signal$2(profileChoice(Au)?.id),Ru=signal$2(!1),Iu=computed$1(()=>({openers:startersAsOpeners(startersFor(Au,$u.value))}));function Pu(){const Fu=interfaceWords(useChatLanguage()),zu=profileChoice(Au,useSignalValue$1($u)),Uu=useSignalValue$1(Ru);if(!zu)return null;const Hu=`${Fu.profile}: ${zu.label}`;return Uu?jsxRuntimeExports.jsx(Text$3,{title:`${Hu} (${Fu.profileKept})`,sx:{fontSize:0,color:"fg.muted",px:2},children:Hu}):jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsx(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":Hu,children:Hu}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Fu.profile}),lo.map(Vu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Vu.id===zu.id,onSelect:()=>{$u.value=profileChoice(Au,Vu.id)?.id},children:[Vu.label,Vu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Vu.description}):null]},Vu.id))]})})})]})}const Ou=Au.interface.modes??[],Du=signal$2(modeDefaults(Au));function Mu(){const Fu=useSignalValue$1(Du);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Ou.map(zu=>{const Uu=zu.options.find(Hu=>Hu.id===Fu[zu.id])??zu.options[0];return jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":`${zu.label}: ${Uu.label}`,children:[zu.label,": ",Uu.label]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:zu.label}),zu.options.map(Hu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Hu.id===Uu.id,onSelect:()=>{Du.value=modeChoice(Au,{...Du.peek(),[zu.id]:Hu.id})},children:[Hu.label,Hu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Hu.description}):null]},Hu.id))]})})})]},zu.id)})})}const Lu=Au.interface.uploads,Bu=signal$2({files:[],refused:null});function ju(){const Fu=interfaceWords(useChatLanguage()),zu=useSignalValue$1(Bu),Uu=reactExports.useRef(null);return Lu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(IconButton,{icon:PaperclipIcon,size:"small",variant:"invisible","aria-label":`${Fu.attach}. ${uploadsInWords(Lu)}`,onClick:()=>Uu.current?.click()}),jsxRuntimeExports.jsx("input",{ref:Uu,type:"file",hidden:!0,multiple:Lu.maxFiles>1,accept:uploadsAccept(Lu),"aria-label":Fu.attach,onChange:Hu=>{const Vu=Array.from(Hu.target.files??[]);Hu.target.value="",holdUploads(Au,Bu.peek().files,Vu).then(Gu=>{Bu.value=Gu})}}),zu.files.map(Hu=>jsxRuntimeExports.jsx(Token$3,{text:Hu.name,size:"small",onRemove:()=>{Bu.value={files:Bu.peek().files.filter(Vu=>Vu!==Hu),refused:null}}},Hu.name)),zu.refused?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:0,color:"danger.fg"},children:zu.refused}):null]}):null}return{name:`${APP_COMPOSER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: commands, modes, profiles and uploads`,description:`The commands, modes, profiles and files ${Au.name} takes in its composer.`,octicon:"command-palette",emoji:"⌘",contributes:[...lo.length>0?[contribution(LoopRunProps,{id:"app-profile",props:()=>(Ru.value=!0,{loop:{profile:$u.peek()}})},{id:"app-profile"}),contribution(LoopChatExtras,{id:"app-profile-starters",extras:Iu},{id:"app-profile-starters"})]:[],...(Au.interface.commands??[]).map(Fu=>contribution(LoopCommand,{name:Fu.name,description:Fu.description,group:Au.name,composer:!0,run:async({argv:zu})=>({prompt:commandPrompt(Fu,zu)})},{id:`app-command-${Fu.name}`})),...Ou.length>0?[contribution(LoopRunProps,{id:"app-modes",props:()=>({loop:{modes:{...Du.peek()}}})},{id:"app-modes"})]:[],...Lu?[contribution(LoopRunProps,{id:"app-uploads",props:()=>{const Fu=Bu.peek().files;return Fu.length===0?{}:(Bu.value={files:[],refused:null},{loop:{files:Fu}})}},{id:"app-uploads"})]:[]],build:()=>({components:[...lo.length>0?[{id:"app-profile",slot:LoopSlots.promptAction,order:3,Component:Pu}]:[],...Ou.length>0?[{id:"app-modes",slot:LoopSlots.promptAction,order:5,Component:Mu}]:[],...Lu?[{id:"app-uploads",slot:LoopSlots.promptAction,order:4,Component:ju}]:[]]})}}const FEEDBACK_COMMENT_LIMIT=2e3,answerIdOf=Au=>Au>0?`answer-${Au}`:void 0,FEEDBACK_WORDS={ask:"Was this answer useful?",liked:"This answer was useful",disliked:"This answer was not useful",comment:"Anything to add? (optional)",send:"Send",kept:Au=>`Thank you. Kept in ${Au}’s record.`,where:Au=>`What you say is kept with this conversation in ${Au}’s record, for its builder to read.`,tooLong:`A comment is at most ${FEEDBACK_COMMENT_LIMIT} characters.`,noRuntime:"No runtime is assigned to this conversation, so nothing can be sent.",noSession:"This conversation has no name the application knows yet: send a message first."},keepsFeedback=Au=>(Au.record?.include??[]).includes("feedback"),feedbackEndpoint=Au=>`${Au.replace(/\/+$/,"")}/api/v1/apps/feedback`;function feedbackProblems(Au){const lo=[];return Au.session.trim()||lo.push(FEEDBACK_WORDS.noSession),Au.comment.trim().length>FEEDBACK_COMMENT_LIMIT&&lo.push(FEEDBACK_WORDS.tooLong),lo}async function sendFeedback(Au,{agentBaseUrl:lo,token:$u,fetcher:Ru=fetch}){const Iu=feedbackProblems(Au);if(Iu.length)throw new Error(Iu.join(" "));const Pu=await Ru(feedbackEndpoint(lo),{method:"POST",headers:{"Content-Type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({session:Au.session,liked:Au.liked,comment:Au.comment.trim(),...Au.message?{message:Au.message}:{}})}),Ou=await Pu.json().catch(()=>({}));if(!Pu.ok){const Du=typeof Ou.detail=="string"?Ou.detail:`${Pu.status}`;throw new Error(`The feedback was not kept: ${Du}`)}return String(Ou.summary??"")}const APP_FEEDBACK_PLUGIN_NAME="@datalayer/loop-plugin-app-feedback",NO_TURN$1=signal$2({id:0,status:"idle"}),NO_CONVERSATION=signal$2([]);function AppFeedback({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$1),Pu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION).filter(Wu=>Wu.role==="assistant").length,Ou=useIAMStore(Wu=>Wu.token),[Du,Mu]=reactExports.useState(null),[Lu,Bu]=reactExports.useState(""),[ju,Fu]=reactExports.useState(null);if(Ru.status!=="done"||!Ru.assistant||!Ru.thread)return null;const zu=Ru.thread,Uu=Du?.turn===Ru.id?Du.liked:null,Hu=ju?.turn===Ru.id?ju:null,Vu=agentServerOf(lo.sandbox,lo.serverUrl),Gu=async()=>{if(Uu!==null){if(Vu===void 0){Fu({turn:Ru.id,state:"refused",says:FEEDBACK_WORDS.noRuntime});return}Fu({turn:Ru.id,state:"sending",says:""});try{await sendFeedback({session:zu,liked:Uu,comment:Lu,message:answerIdOf(Pu)},{agentBaseUrl:Vu,token:Ou}),Fu({turn:Ru.id,state:"kept",says:FEEDBACK_WORDS.kept(Au.name)}),Bu("")}catch(Wu){Fu({turn:Ru.id,state:"refused",says:Wu instanceof Error?Wu.message:String(Wu)})}}};return Hu?.state==="kept"?jsxRuntimeExports.jsx("div",{style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Hu.says})}):jsxRuntimeExports.jsxs("div",{role:"group","aria-label":FEEDBACK_WORDS.ask,style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 8px"},children:[jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.ask}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!0?"default":"invisible",icon:ThumbsupIcon,"aria-label":FEEDBACK_WORDS.liked,"aria-pressed":Uu===!0,unsafeDisableTooltip:!0,onClick:()=>Mu({turn:Ru.id,liked:!0})}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!1?"default":"invisible",icon:ThumbsdownIcon,"aria-label":FEEDBACK_WORDS.disliked,"aria-pressed":Uu===!1,unsafeDisableTooltip:!0,onClick:()=>Mu({turn:Ru.id,liked:!1})})]}),Uu!==null?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Textarea,{"aria-label":FEEDBACK_WORDS.comment,placeholder:FEEDBACK_WORDS.comment,value:Lu,rows:2,resize:"vertical",block:!0,onChange:Wu=>Bu(Wu.target.value)}),jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",disabled:Hu?.state==="sending",onClick:()=>{Gu()},children:FEEDBACK_WORDS.send}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.where(Au.name)})]})]}):null,Hu?.state==="refused"?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:0,color:"fg.default"},children:Hu.says}):null]})}function defineAppFeedbackPlugin(Au){function lo({workspace:$u}){return jsxRuntimeExports.jsx(AppFeedback,{app:Au,workspace:$u})}return{name:`${APP_FEEDBACK_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: feedback`,description:`A thumb and a comment on each answer of ${Au.name}, kept in its record.`,octicon:"thumbsup",emoji:"👍",contributes:[contribution(LoopPromptPanel,{id:"app-feedback",placement:"above",order:20,Component:lo},{id:"app-feedback"})]}}const KEPT_ITEMS={conversations:"this conversation",actions:"what it does",decisions:"how its rules decided",approvals:"what is approved",checks:"what its checks stopped",outputs:"its answers",feedback:"what you say of its answers"},RETENTION=/^([1-9]\d*)_(day|days|month|months|year|years)$/;function keptForWords(Au){const lo=RETENTION.exec(Au.trim());if(!lo)throw new Error(`Cannot read the retention \`${Au}\`: write 90_days, 18_months or 1_years.`);const $u=Number(lo[1]),Ru=lo[2].replace(/s$/,"");return $u===1?`a ${Ru}`:`${$u} ${Ru}s`}function inWords(Au){return Au.length<2?Au[0]??"":`${Au.slice(0,-1).join(", ")} and ${Au[Au.length-1]}`}function keptBeforeFirstMessage(Au,{visitor:lo=!1}={}){if(lo)return"Nothing of this conversation is kept: you are not signed in.";const $u=Au.name||"This application",Ru=keptForWords(Au.record.keepFor),Iu=Au.record.include.map(Pu=>KEPT_ITEMS[Pu]).filter(Pu=>!!Pu);return Iu.length?`${$u} keeps ${inWords(Iu)} for ${Ru}, then deletes it.`:`${$u} keeps only that this conversation took place, for ${Ru}.`}const beforeFirstMessage=Au=>Au.id===0&&!Au.user,APP_KEPT_PLUGIN_NAME="@datalayer/loop-plugin-app-kept",NO_TURN=signal$2({id:0,status:"idle"});function AppKept({says:Au}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN);return beforeFirstMessage($u)?jsxRuntimeExports.jsx("div",{role:"note",style:{padding:`4px var(${ASSISTANT_CLEARANCE_VAR}, 8px) 4px 8px`},children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Au})}):null}function defineAppKeptPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppKept,{says:lo})}return{name:`${APP_KEPT_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: what it keeps`,description:`What ${Au.name} keeps of a conversation, and for how long, said before the first message.`,octicon:"archive",emoji:"🗄",contributes:[contribution(LoopPromptPanel,{id:"app-kept",placement:"below",order:30,Component:$u},{id:"app-kept"})]}}const appPluginName=Au=>`loop-app-${Au}`;function appPluginPair(Au){const lo=appPluginName(Au);return{page:{name:lo,requiredBackendPlugins:[lo]},server:{name:lo,frontendDependencies:[lo]},extension:lo}}const appPluginsBase=(Au,lo)=>`${Au.replace(/\/+$/,"")}/api/v1/apps/${encodeURIComponent(lo)}`;function appRuntimeOf({target:Au,snapshot:lo,serverUrl:$u}){if(!(!Au||Au==="browser")){if(lo.agentBaseUrl)return lo.agentBaseUrl;if(Au!=="datalayer")return lo.state==="running"&&$u?$u:void 0}}const APP_RUNTIME_PLUGIN_NAME="@datalayer/loop-plugin-app-runtime",runningOf=Au=>lo=>Au.includes(lo);function AppRuntimePlugins({appId:Au,pageSide:lo=!1}){const $u=useReactorPlatform(),Ru=useOptionalSandboxService(),Iu=useSignalValue$1(Ru?.target??IDLE_SANDBOX_TARGET_SIGNAL),Pu=useSignalValue$1(Ru?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ou=appRuntimeOf({target:Iu,snapshot:Pu,serverUrl:Ru?.serverUrl}),Du=appPluginName(Au);reactExports.useEffect(()=>{Ou||(registerReactor($u,runningOf([Du])),$u.setBackendPlugins([Du]))},[$u,Ou,Du]);const Mu=reactExports.useCallback(Lu=>registerReactor($u,runningOf(Lu.plugins.filter(Bu=>Bu.enabled).map(Bu=>Bu.name))),[$u]);return useBackendPluginStream(Ou?appPluginsBase(Ou,Au):void 0,{onState:Mu}),reactExports.useEffect(()=>{if(!Ou||!lo)return;let Lu=!0;return bootstrapExtensions(appPluginsBase(Ou,Au)).then(Bu=>{for(const ju of Bu.filter(Fu=>Fu.name===Du))Lu&&$u.install(ju)}),()=>{Lu=!1}},[$u,Ou,Au,Du,lo]),null}function defineAppRuntimePlugin(Au,{pageSide:lo=!1}={}){const $u=()=>jsxRuntimeExports.jsx(AppRuntimePlugins,{appId:Au,pageSide:lo});return{name:APP_RUNTIME_PLUGIN_NAME,displayName:"Its runtime",description:"Tells the application’s page which of its plugins its runtime holds.",octicon:"server",build:()=>({components:[{slot:LoopSlots.status,id:"app-runtime-plugins",Component:$u}]})}}const VISITOR_KEY="datalayer-loop-visitor",MARGIN_MS=3e4;function isVisitorId(Au){return typeof Au=="string"&&/^[A-Za-z0-9-]{8,64}$/.test(Au)}function keptVisitorId(){try{const Au=window.sessionStorage.getItem(VISITOR_KEY);return isVisitorId(Au)?Au:""}catch{return""}}function keepVisitorId(Au){try{window.sessionStorage.setItem(VISITOR_KEY,Au)}catch{}}function visitorTokenRequest(Au,lo){return isVisitorId(lo)?{app:Au,visitor:lo}:{app:Au}}async function fetchVisitorToken(Au,lo,$u=keptVisitorId(),Ru=fetch){const Iu=Au.replace(/\/+$/,""),Pu=await Ru(`${Iu}/api/ai-inference/v1/anonymous/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(visitorTokenRequest(lo,$u))}),Ou=await Pu.json().catch(()=>({}));if(!Pu.ok||!Ou.token)throw new Error(Ou.detail||`A visitor's token was refused by ${Iu} (HTTP ${Pu.status}).`);isVisitorId(Ou.visitor)&&keepVisitorId(Ou.visitor);const Du=Math.max(6e4,(Ou.expires_in??300)*1e3);return{token:Ou.token,visitor:Ou.visitor??$u,renewAt:Date.now()+Du-MARGIN_MS}}function useVisitorToken(Au){const[lo,$u]=reactExports.useState({}),Ru=Au?.app,Iu=Au?.inferenceUrl;return reactExports.useEffect(()=>{if(!Ru||!Iu){$u({});return}let Pu=!1,Ou;const Du=()=>{fetchVisitorToken(Iu,Ru).then(Mu=>{Pu||($u({token:Mu.token}),Ou=setTimeout(Du,Math.max(5e3,Mu.renewAt-Date.now())))}).catch(Mu=>{Pu||$u({error:Mu instanceof Error?Mu.message:String(Mu)})})};return Du(),()=>{Pu=!0,Ou&&clearTimeout(Ou)}},[Ru,Iu]),lo}const AT_PREFIX$1="at:",SLUG$1=/^[a-z0-9][a-z0-9-]{0,99}$/;function visitorAgentOf(Au){if(!Au.startsWith(AT_PREFIX$1))return Au;const lo=Au.slice(AT_PREFIX$1.length);if(!SLUG$1.test(lo))throw new Error(`“${Au}” is no application’s address.`);return`at-${lo}`}async function fetchVisitorAgent(Au,lo,$u=fetch){const Ru=Au.replace(/\/+$/,""),Iu=await $u(`${Ru}/api/v1/apps/visitors/agent`,{method:"POST",headers:{Authorization:`Bearer ${lo}`}}),Pu=await Iu.json().catch(()=>({}));if(!Iu.ok||!Pu.agent||!Pu.app_id)throw new Error(Pu.detail||`The visitors’ runtime at ${Ru} did not make the application’s agent (HTTP ${Iu.status}).`);return{agent:Pu.agent,appId:Pu.app_id}}async function ensureVisitorAgent(Au,lo,$u=fetch){const Ru=await fetchVisitorToken(Au.inferenceUrl,Au.app,keptVisitorId(),$u),Iu=await fetchVisitorAgent(Au.url,Ru.token,$u),Pu=visitorAgentOf(Au.app);if(Iu.agent!==Pu||Iu.appId!==lo)throw new Error(`The visitors’ runtime holds ${Iu.appId} as ${Iu.agent} for “${Au.app}”, not ${lo} as ${Pu}: reload the page.`);return Iu}function resolveAgentspec(Au){return getAgentspecs(Au)??getCog(Au)?.spec}function agentInstructions(Au,lo){const $u=[Au?.systemPrompt?.trim(),lo?.trim()].filter(Ru=>!!Ru);return $u.length>0?$u.join(`
3728
+ `),Du=Pu.find(Mu=>Mu.model)?.model??Iu?.model??void 0;return Du?{instructions:Ou,model:Du}:{instructions:Ou}}async function holdUploads(Au,lo,$u,Ru=readFile){const Iu=uploadsRefusal(Au,[...lo,...$u.map(Pu=>({name:Pu.name,type:Pu.type,size:Pu.size}))]);return Iu?{files:[...lo],refused:Iu}:{files:[...lo,...await Promise.all($u.map(Ru))],refused:null}}const APP_COMPOSER_PLUGIN_NAME="@datalayer/loop-plugin-app-composer";function startersAsOpeners(Au){return Au.map(lo=>({text:lo.label,message:lo.message,...lo.category?{group:lo.category}:{}}))}const needsAppComposer=Au=>(Au.interface.commands??[]).length>0||(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0||!!Au.interface.uploads;function defineAppComposerPlugin(Au){const lo=Au.interface.profiles??[],$u=signal$2(profileChoice(Au)?.id),Ru=signal$2(!1),Iu=computed$1(()=>({openers:startersAsOpeners(startersFor(Au,$u.value))}));function Pu(){const Fu=interfaceWords(useChatLanguage()),zu=profileChoice(Au,useSignalValue$1($u)),Uu=useSignalValue$1(Ru);if(!zu)return null;const Hu=`${Fu.profile}: ${zu.label}`;return Uu?jsxRuntimeExports.jsx(Text$3,{title:`${Hu} (${Fu.profileKept})`,sx:{fontSize:0,color:"fg.muted",px:2},children:Hu}):jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsx(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":Hu,children:Hu}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Fu.profile}),lo.map(Vu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Vu.id===zu.id,onSelect:()=>{$u.value=profileChoice(Au,Vu.id)?.id},children:[Vu.label,Vu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Vu.description}):null]},Vu.id))]})})})]})}const Ou=Au.interface.modes??[],Du=signal$2(modeDefaults(Au));function Mu(){const Fu=useSignalValue$1(Du);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Ou.map(zu=>{const Uu=zu.options.find(Hu=>Hu.id===Fu[zu.id])??zu.options[0];return jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":`${zu.label}: ${Uu.label}`,children:[zu.label,": ",Uu.label]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:zu.label}),zu.options.map(Hu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Hu.id===Uu.id,onSelect:()=>{Du.value=modeChoice(Au,{...Du.peek(),[zu.id]:Hu.id})},children:[Hu.label,Hu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Hu.description}):null]},Hu.id))]})})})]},zu.id)})})}const Lu=Au.interface.uploads,Bu=signal$2({files:[],refused:null});function ju(){const Fu=interfaceWords(useChatLanguage()),zu=useSignalValue$1(Bu),Uu=reactExports.useRef(null);return Lu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(IconButton,{icon:PaperclipIcon,size:"small",variant:"invisible","aria-label":`${Fu.attach}. ${uploadsInWords(Lu)}`,onClick:()=>Uu.current?.click()}),jsxRuntimeExports.jsx("input",{ref:Uu,type:"file",hidden:!0,multiple:Lu.maxFiles>1,accept:uploadsAccept(Lu),"aria-label":Fu.attach,onChange:Hu=>{const Vu=Array.from(Hu.target.files??[]);Hu.target.value="",holdUploads(Au,Bu.peek().files,Vu).then(Gu=>{Bu.value=Gu})}}),zu.files.map(Hu=>jsxRuntimeExports.jsx(Token$3,{text:Hu.name,size:"small",onRemove:()=>{Bu.value={files:Bu.peek().files.filter(Vu=>Vu!==Hu),refused:null}}},Hu.name)),zu.refused?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:0,color:"danger.fg"},children:zu.refused}):null]}):null}return{name:`${APP_COMPOSER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: commands, modes, profiles and uploads`,description:`The commands, modes, profiles and files ${Au.name} takes in its composer.`,octicon:"command-palette",emoji:"⌘",contributes:[...lo.length>0?[contribution(LoopRunProps,{id:"app-profile",props:()=>(Ru.value=!0,{loop:{profile:$u.peek()}})},{id:"app-profile"}),contribution(LoopChatExtras,{id:"app-profile-starters",extras:Iu},{id:"app-profile-starters"})]:[],...(Au.interface.commands??[]).map(Fu=>contribution(LoopCommand,{name:Fu.name,description:Fu.description,group:Au.name,composer:!0,run:async({argv:zu})=>({prompt:commandPrompt(Fu,zu)})},{id:`app-command-${Fu.name}`})),...Ou.length>0?[contribution(LoopRunProps,{id:"app-modes",props:()=>({loop:{modes:{...Du.peek()}}})},{id:"app-modes"})]:[],...Lu?[contribution(LoopRunProps,{id:"app-uploads",props:()=>{const Fu=Bu.peek().files;return Fu.length===0?{}:(Bu.value={files:[],refused:null},{loop:{files:Fu}})}},{id:"app-uploads"})]:[]],build:()=>({components:[...lo.length>0?[{id:"app-profile",slot:LoopSlots.promptAction,order:3,Component:Pu}]:[],...Ou.length>0?[{id:"app-modes",slot:LoopSlots.promptAction,order:5,Component:Mu}]:[],...Lu?[{id:"app-uploads",slot:LoopSlots.promptAction,order:4,Component:ju}]:[]]})}}const FEEDBACK_COMMENT_LIMIT=2e3,answerIdOf=Au=>Au>0?`answer-${Au}`:void 0,FEEDBACK_WORDS={ask:"Was this answer useful?",liked:"This answer was useful",disliked:"This answer was not useful",comment:"Anything to add? (optional)",send:"Send",kept:Au=>`Thank you. Kept in ${Au}’s record.`,where:Au=>`What you say is kept with this conversation in ${Au}’s record, for its builder to read.`,tooLong:`A comment is at most ${FEEDBACK_COMMENT_LIMIT} characters.`,noRuntime:"No runtime is assigned to this conversation, so nothing can be sent.",noSession:"This conversation has no name the application knows yet: send a message first."},keepsFeedback=Au=>(Au.record?.include??[]).includes("feedback"),feedbackEndpoint=Au=>`${Au.replace(/\/+$/,"")}/api/v1/apps/feedback`;function feedbackProblems(Au){const lo=[];return Au.session.trim()||lo.push(FEEDBACK_WORDS.noSession),Au.comment.trim().length>FEEDBACK_COMMENT_LIMIT&&lo.push(FEEDBACK_WORDS.tooLong),lo}async function sendFeedback(Au,{agentBaseUrl:lo,token:$u,fetcher:Ru=fetch}){const Iu=feedbackProblems(Au);if(Iu.length)throw new Error(Iu.join(" "));const Pu=await Ru(feedbackEndpoint(lo),{method:"POST",headers:{"Content-Type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({session:Au.session,liked:Au.liked,comment:Au.comment.trim(),...Au.message?{message:Au.message}:{}})}),Ou=await Pu.json().catch(()=>({}));if(!Pu.ok){const Du=typeof Ou.detail=="string"?Ou.detail:`${Pu.status}`;throw new Error(`The feedback was not kept: ${Du}`)}return String(Ou.summary??"")}const APP_FEEDBACK_PLUGIN_NAME="@datalayer/loop-plugin-app-feedback",NO_TURN$1=signal$2({id:0,status:"idle"}),NO_CONVERSATION=signal$2([]);function AppFeedback({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$1),Pu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION).filter(Wu=>Wu.role==="assistant").length,Ou=useIAMStore(Wu=>Wu.token),[Du,Mu]=reactExports.useState(null),[Lu,Bu]=reactExports.useState(""),[ju,Fu]=reactExports.useState(null);if(Ru.status!=="done"||!Ru.assistant||!Ru.thread)return null;const zu=Ru.thread,Uu=Du?.turn===Ru.id?Du.liked:null,Hu=ju?.turn===Ru.id?ju:null,Vu=agentServerOf(lo.sandbox,lo.serverUrl),Gu=async()=>{if(Uu!==null){if(Vu===void 0){Fu({turn:Ru.id,state:"refused",says:FEEDBACK_WORDS.noRuntime});return}Fu({turn:Ru.id,state:"sending",says:""});try{await sendFeedback({session:zu,liked:Uu,comment:Lu,message:answerIdOf(Pu)},{agentBaseUrl:Vu,token:Ou}),Fu({turn:Ru.id,state:"kept",says:FEEDBACK_WORDS.kept(Au.name)}),Bu("")}catch(Wu){Fu({turn:Ru.id,state:"refused",says:Wu instanceof Error?Wu.message:String(Wu)})}}};return Hu?.state==="kept"?jsxRuntimeExports.jsx("div",{style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Hu.says})}):jsxRuntimeExports.jsxs("div",{role:"group","aria-label":FEEDBACK_WORDS.ask,style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 8px"},children:[jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.ask}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!0?"default":"invisible",icon:ThumbsupIcon,"aria-label":FEEDBACK_WORDS.liked,"aria-pressed":Uu===!0,unsafeDisableTooltip:!0,onClick:()=>Mu({turn:Ru.id,liked:!0})}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!1?"default":"invisible",icon:ThumbsdownIcon,"aria-label":FEEDBACK_WORDS.disliked,"aria-pressed":Uu===!1,unsafeDisableTooltip:!0,onClick:()=>Mu({turn:Ru.id,liked:!1})})]}),Uu!==null?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Textarea,{"aria-label":FEEDBACK_WORDS.comment,placeholder:FEEDBACK_WORDS.comment,value:Lu,rows:2,resize:"vertical",block:!0,onChange:Wu=>Bu(Wu.target.value)}),jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",disabled:Hu?.state==="sending",onClick:()=>{Gu()},children:FEEDBACK_WORDS.send}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.where(Au.name)})]})]}):null,Hu?.state==="refused"?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:0,color:"fg.default"},children:Hu.says}):null]})}function defineAppFeedbackPlugin(Au){function lo({workspace:$u}){return jsxRuntimeExports.jsx(AppFeedback,{app:Au,workspace:$u})}return{name:`${APP_FEEDBACK_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: feedback`,description:`A thumb and a comment on each answer of ${Au.name}, kept in its record.`,octicon:"thumbsup",emoji:"👍",contributes:[contribution(LoopPromptPanel,{id:"app-feedback",placement:"above",order:20,Component:lo},{id:"app-feedback"})]}}const KEPT_ITEMS={conversations:"this conversation",actions:"what it does",decisions:"how its rules decided",approvals:"what is approved",checks:"what its checks stopped",outputs:"its answers",feedback:"what you say of its answers"},RETENTION=/^([1-9]\d*)_(day|days|month|months|year|years)$/;function keptForWords(Au){const lo=RETENTION.exec(Au.trim());if(!lo)throw new Error(`Cannot read the retention \`${Au}\`: write 90_days, 18_months or 1_years.`);const $u=Number(lo[1]),Ru=lo[2].replace(/s$/,"");return $u===1?`a ${Ru}`:`${$u} ${Ru}s`}function inWords(Au){return Au.length<2?Au[0]??"":`${Au.slice(0,-1).join(", ")} and ${Au[Au.length-1]}`}function keptBeforeFirstMessage(Au,{visitor:lo=!1}={}){if(lo)return"Nothing of this conversation is kept: you are not signed in.";const $u=Au.name||"This application",Ru=keptForWords(Au.record.keepFor),Iu=Au.record.include.map(Pu=>KEPT_ITEMS[Pu]).filter(Pu=>!!Pu);return Iu.length?`${$u} keeps ${inWords(Iu)} for ${Ru}, then deletes it.`:`${$u} keeps only that this conversation took place, for ${Ru}.`}const beforeFirstMessage=Au=>Au.id===0&&!Au.user,APP_KEPT_PLUGIN_NAME="@datalayer/loop-plugin-app-kept",NO_TURN=signal$2({id:0,status:"idle"});function AppKept({says:Au}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN);return beforeFirstMessage($u)?jsxRuntimeExports.jsx("div",{role:"note",style:{padding:`4px var(${ASSISTANT_CLEARANCE_VAR}, 8px) 4px 8px`},children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Au})}):null}function defineAppKeptPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppKept,{says:lo})}return{name:`${APP_KEPT_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: what it keeps`,description:`What ${Au.name} keeps of a conversation, and for how long, said before the first message.`,octicon:"archive",emoji:"🗄",contributes:[contribution(LoopPromptPanel,{id:"app-kept",placement:"below",order:30,Component:$u},{id:"app-kept"})]}}const appPluginName=Au=>`loop-app-${Au}`;function appPluginPair(Au){const lo=appPluginName(Au);return{page:{name:lo,requiredBackendPlugins:[lo]},server:{name:lo,frontendDependencies:[lo]},extension:lo}}const appPluginsBase=(Au,lo)=>`${Au.replace(/\/+$/,"")}/api/v1/apps/${encodeURIComponent(lo)}`;function appRuntimeOf({target:Au,snapshot:lo,serverUrl:$u}){if(!(!Au||Au==="browser")){if(lo.agentBaseUrl)return lo.agentBaseUrl;if(Au!=="datalayer")return lo.state==="running"&&$u?$u:void 0}}const APP_RUNTIME_PLUGIN_NAME="@datalayer/loop-plugin-app-runtime",runningOf=Au=>lo=>Au.includes(lo);function AppRuntimePlugins({appId:Au,pageSide:lo=!1}){const $u=useReactorPlatform(),Ru=useOptionalSandboxService(),Iu=useSignalValue$1(Ru?.target??IDLE_SANDBOX_TARGET_SIGNAL),Pu=useSignalValue$1(Ru?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ou=appRuntimeOf({target:Iu,snapshot:Pu,serverUrl:Ru?.serverUrl}),Du=appPluginName(Au);reactExports.useEffect(()=>{Ou||(registerReactor($u,runningOf([Du])),$u.setBackendPlugins([Du]))},[$u,Ou,Du]);const Mu=reactExports.useCallback(Lu=>registerReactor($u,runningOf(Lu.plugins.filter(Bu=>Bu.enabled).map(Bu=>Bu.name))),[$u]);return useBackendPluginStream(Ou?appPluginsBase(Ou,Au):void 0,{onState:Mu}),reactExports.useEffect(()=>{if(!Ou||!lo)return;let Lu=!0;return bootstrapExtensions(appPluginsBase(Ou,Au)).then(Bu=>{for(const ju of Bu.filter(Fu=>Fu.name===Du))Lu&&$u.install(ju)}),()=>{Lu=!1}},[$u,Ou,Au,Du,lo]),null}function defineAppRuntimePlugin(Au,{pageSide:lo=!1}={}){const $u=()=>jsxRuntimeExports.jsx(AppRuntimePlugins,{appId:Au,pageSide:lo});return{name:APP_RUNTIME_PLUGIN_NAME,displayName:"Its runtime",description:"Tells the application’s page which of its plugins its runtime holds.",octicon:"server",build:()=>({components:[{slot:LoopSlots.status,id:"app-runtime-plugins",Component:$u}]})}}const VISITOR_KEY="datalayer-loop-visitor",MARGIN_MS=3e4;function isVisitorId(Au){return typeof Au=="string"&&/^[A-Za-z0-9-]{8,64}$/.test(Au)}function keptVisitorId(){try{const Au=window.sessionStorage.getItem(VISITOR_KEY);return isVisitorId(Au)?Au:""}catch{return""}}function keepVisitorId(Au){try{window.sessionStorage.setItem(VISITOR_KEY,Au)}catch{}}function visitorTokenRequest(Au,lo,$u=""){return{...Au?{app:Au}:{},...isVisitorId(lo)?{visitor:lo}:{},...$u?{battle:$u}:{}}}async function mintVisitorToken(Au,lo,$u){const Ru=Au.replace(/\/+$/,""),Iu=await $u(`${Ru}/api/ai-inference/v1/anonymous/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(lo)}),Pu=await Iu.json().catch(()=>({}));if(!Iu.ok||!Pu.token)throw new Error(Pu.detail||`A visitor's token was refused by ${Ru} (HTTP ${Iu.status}).`);return isVisitorId(Pu.visitor)&&keepVisitorId(Pu.visitor),{token:Pu.token,visitor:Pu.visitor,expires_in:Pu.expires_in}}async function fetchVisitorToken(Au,lo,$u=keptVisitorId(),Ru=fetch,Iu=""){const Pu=await mintVisitorToken(Au,visitorTokenRequest(lo,$u,Iu),Ru),Ou=Math.max(6e4,(Pu.expires_in??300)*1e3);return{token:Pu.token,visitor:Pu.visitor??$u,renewAt:Date.now()+Ou-MARGIN_MS}}function useVisitorToken(Au){const[lo,$u]=reactExports.useState({}),Ru=Au?.app,Iu=Au?.inferenceUrl,Pu=Au?.battle??"";return reactExports.useEffect(()=>{if(!Ru||!Iu){$u({});return}let Ou=!1,Du;const Mu=()=>{fetchVisitorToken(Iu,Ru,keptVisitorId(),fetch,Pu).then(Lu=>{Ou||($u({token:Lu.token}),Du=setTimeout(Mu,Math.max(5e3,Lu.renewAt-Date.now())))}).catch(Lu=>{Ou||$u({error:Lu instanceof Error?Lu.message:String(Lu)})})};return Mu(),()=>{Ou=!0,Du&&clearTimeout(Du)}},[Ru,Iu,Pu]),lo}const AT_PREFIX$1="at:",SLUG$1=/^[a-z0-9][a-z0-9-]{0,99}$/;function visitorAgentOf(Au){if(!Au.startsWith(AT_PREFIX$1))return Au;const lo=Au.slice(AT_PREFIX$1.length);if(!SLUG$1.test(lo))throw new Error(`“${Au}” is no application’s address.`);return`at-${lo}`}async function fetchVisitorAgent(Au,lo,$u=fetch){const Ru=Au.replace(/\/+$/,""),Iu=await $u(`${Ru}/api/v1/apps/visitors/agent`,{method:"POST",headers:{Authorization:`Bearer ${lo}`}}),Pu=await Iu.json().catch(()=>({}));if(!Iu.ok||!Pu.agent||!Pu.app_id)throw new Error(Pu.detail||`The visitors’ runtime at ${Ru} did not make the application’s agent (HTTP ${Iu.status}).`);return{agent:Pu.agent,appId:Pu.app_id}}async function ensureVisitorAgent(Au,lo,$u=fetch){const Ru=await fetchVisitorToken(Au.inferenceUrl,Au.app,keptVisitorId(),$u),Iu=await fetchVisitorAgent(Au.url,Ru.token,$u),Pu=visitorAgentOf(Au.app);if(Iu.agent!==Pu||Iu.appId!==lo)throw new Error(`The visitors’ runtime holds ${Iu.appId} as ${Iu.agent} for “${Au.app}”, not ${lo} as ${Pu}: reload the page.`);return Iu}function resolveAgentspec(Au){return getAgentspecs(Au)??getCog(Au)?.spec}function agentInstructions(Au,lo){const $u=[Au?.systemPrompt?.trim(),lo?.trim()].filter(Ru=>!!Ru);return $u.length>0?$u.join(`
3729
3729
 
3730
3730
  `):void 0}function inPageAgentRefusal(Au,lo){return Au&&!lo?`There is no agent or Cog named “${Au}” in this page, so it cannot answer here.`:void 0}const BROWSER_CODE_TOOL="execute_code",SANDBOX_INPUTS="/tmp/inputs";function runsCodeInSandbox(Au){return!!(Au.agent&&resolveAgentspec(Au.agent)?.sandboxVariant)}const sandboxPath=Au=>`${SANDBOX_INPUTS}/${Au}`;function sandboxFileName(Au){return(Au.split(/[\\/]/).pop()??"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[.-]+/,"")||"file"}function textAsBase64(Au){const lo=new TextEncoder().encode(Au);let $u="";for(const Ru of lo)$u+=String.fromCharCode(Ru);return btoa($u)}function dataUrlBase64(Au){const lo=Au.indexOf(",");if(!Au.startsWith("data:")||lo<0||!/;base64$/.test(Au.slice(0,lo)))throw new Error("A file given on the page is not a base64 data URL.");return Au.slice(lo+1)}function sampleFiles(Au){return(Au.samples?.documents??[]).map(lo=>({file:lo.file,base64:textAsBase64(lo.text)}))}function writeFilesCode(Au){const lo=Au.map(({file:$u,base64:Ru})=>` (${JSON.stringify($u)}, ${JSON.stringify(Ru)}),`).join(`
3731
3731
  `);return["import base64 as _b64, pathlib as _pl",`_inputs = _pl.Path(${JSON.stringify(SANDBOX_INPUTS)})`,"_inputs.mkdir(parents=True, exist_ok=True)","for _name, _data in [",lo,"]:"," (_inputs / _name).write_bytes(_b64.b64decode(_data))","del _b64, _pl, _inputs"].join(`
@@ -6,6 +6,8 @@ export type DatalayerVisitors = {
6
6
  app: string;
7
7
  /** ai-inference, which mints the visitor's token. */
8
8
  inferenceUrl: string;
9
+ /** The catalogue Battle the token is played for, when it is (B4-01). */
10
+ battle?: string;
9
11
  };
10
12
  /** A visitor's id: what ai-inference accepts (8 to 64 letters, digits or dashes). */
11
13
  export declare function isVisitorId(value: string | null | undefined): value is string;
@@ -18,13 +20,30 @@ export type VisitorToken = {
18
20
  /** Epoch milliseconds: the token's own lifetime from now. */
19
21
  renewAt: number;
20
22
  };
21
- /** The body ai-inference is asked with. */
22
- export declare function visitorTokenRequest(app: string, visitor: string): {
23
- app: string;
23
+ /** The body ai-inference is asked with: the application, the visitor once there is one, the Battle when it is played for one. */
24
+ export declare function visitorTokenRequest(app: string, visitor: string, battle?: string): {
25
+ app?: string;
24
26
  visitor?: string;
27
+ battle?: string;
25
28
  };
26
- /** Mint a visitor's token for an application; throws with ai-inference's sentence. */
27
- export declare function fetchVisitorToken(inferenceUrl: string, app: string, visitor?: string, fetcher?: typeof fetch): Promise<VisitorToken>;
29
+ /** Mint a visitor's token for an application — played for a Battle when `battle` names one; throws with ai-inference's sentence. */
30
+ export declare function fetchVisitorToken(inferenceUrl: string, app: string, visitor?: string, fetcher?: typeof fetch, battle?: string): Promise<VisitorToken>;
31
+ /** A Battle's token for the page's players: its own budget at ai-inference, for one play. */
32
+ export type BattleToken = {
33
+ token: string;
34
+ visitor: string;
35
+ /** Epoch milliseconds: the token's own lifetime from now. */
36
+ expiresAt: number;
37
+ /** How long it was signed for, as the token declares. */
38
+ lifetimeMs: number;
39
+ };
40
+ /**
41
+ * Mint the token one play of a catalogue Battle is played with, by the
42
+ * visitor this tab keeps (B4-01): the players in the page call their models
43
+ * with it, its calls counted against the play's budget. Never renewed: a play
44
+ * is minutes, and the next play mints its own.
45
+ */
46
+ export declare function fetchBattleToken(inferenceUrl: string, battle: string, visitor?: string, fetcher?: typeof fetch): Promise<BattleToken>;
28
47
  /**
29
48
  * The visitor's token for an application while `visitors` is set: minted at
30
49
  * once and again before it runs out. `error` says why none could be had.
@@ -14,9 +14,16 @@
14
14
  * visitor is on the servers (turns a day, a session's minutes, a rate and a
15
15
  * ceiling for the day), not the life of a key.
16
16
  *
17
+ * A token may also name the catalogue Battle it is played for (B4-01): its
18
+ * model calls then count against that play's own budget at ai-inference,
19
+ * instead of the visitor's rate, and the runtime that plays a member of the
20
+ * Battle's scene reads the Battle from it (`fetchBattleToken`, and
21
+ * `DatalayerVisitors.battle` for the members).
22
+ *
17
23
  * @module apps/apps/visitorToken
18
24
  */
19
25
  import { useEffect, useState } from 'react';
26
+ import { tokenLifetimeMs } from '../../runtimes/browser/anonymousToken.js';
20
27
  /** The id this tab keeps for its visitor. */
21
28
  const VISITOR_KEY = 'datalayer-loop-visitor';
22
29
  /** Minted again this long before the token runs out. */
@@ -43,17 +50,21 @@ function keepVisitorId(visitor) {
43
50
  // A tab that keeps nothing is a new visitor at each token.
44
51
  }
45
52
  }
46
- /** The body ai-inference is asked with. */
47
- export function visitorTokenRequest(app, visitor) {
48
- return isVisitorId(visitor) ? { app, visitor } : { app };
53
+ /** The body ai-inference is asked with: the application, the visitor once there is one, the Battle when it is played for one. */
54
+ export function visitorTokenRequest(app, visitor, battle = '') {
55
+ return {
56
+ ...(app ? { app } : {}),
57
+ ...(isVisitorId(visitor) ? { visitor } : {}),
58
+ ...(battle ? { battle } : {}),
59
+ };
49
60
  }
50
- /** Mint a visitor's token for an application; throws with ai-inference's sentence. */
51
- export async function fetchVisitorToken(inferenceUrl, app, visitor = keptVisitorId(), fetcher = fetch) {
61
+ /** Ask ai-inference for a token; throws with its sentence. The visitor it names is kept for the next one. */
62
+ async function mintVisitorToken(inferenceUrl, request, fetcher) {
52
63
  const base = inferenceUrl.replace(/\/+$/, '');
53
64
  const response = await fetcher(`${base}/api/ai-inference/v1/anonymous/token`, {
54
65
  method: 'POST',
55
66
  headers: { 'Content-Type': 'application/json' },
56
- body: JSON.stringify(visitorTokenRequest(app, visitor)),
67
+ body: JSON.stringify(request),
57
68
  });
58
69
  const body = (await response.json().catch(() => ({})));
59
70
  if (!response.ok || !body.token) {
@@ -63,6 +74,15 @@ export async function fetchVisitorToken(inferenceUrl, app, visitor = keptVisitor
63
74
  if (isVisitorId(body.visitor)) {
64
75
  keepVisitorId(body.visitor);
65
76
  }
77
+ return {
78
+ token: body.token,
79
+ visitor: body.visitor,
80
+ expires_in: body.expires_in,
81
+ };
82
+ }
83
+ /** Mint a visitor's token for an application — played for a Battle when `battle` names one; throws with ai-inference's sentence. */
84
+ export async function fetchVisitorToken(inferenceUrl, app, visitor = keptVisitorId(), fetcher = fetch, battle = '') {
85
+ const body = await mintVisitorToken(inferenceUrl, visitorTokenRequest(app, visitor, battle), fetcher);
66
86
  const lifetimeMs = Math.max(60_000, (body.expires_in ?? 300) * 1000);
67
87
  return {
68
88
  token: body.token,
@@ -70,6 +90,25 @@ export async function fetchVisitorToken(inferenceUrl, app, visitor = keptVisitor
70
90
  renewAt: Date.now() + lifetimeMs - MARGIN_MS,
71
91
  };
72
92
  }
93
+ /**
94
+ * Mint the token one play of a catalogue Battle is played with, by the
95
+ * visitor this tab keeps (B4-01): the players in the page call their models
96
+ * with it, its calls counted against the play's budget. Never renewed: a play
97
+ * is minutes, and the next play mints its own.
98
+ */
99
+ export async function fetchBattleToken(inferenceUrl, battle, visitor = keptVisitorId(), fetcher = fetch) {
100
+ if (!battle) {
101
+ throw new Error('A Battle token is minted for a Battle.');
102
+ }
103
+ const body = await mintVisitorToken(inferenceUrl, visitorTokenRequest('', visitor, battle), fetcher);
104
+ const lifetimeMs = tokenLifetimeMs(body.token, body.expires_in);
105
+ return {
106
+ token: body.token,
107
+ visitor: body.visitor ?? visitor,
108
+ expiresAt: Date.now() + lifetimeMs,
109
+ lifetimeMs,
110
+ };
111
+ }
73
112
  /**
74
113
  * The visitor's token for an application while `visitors` is set: minted at
75
114
  * once and again before it runs out. `error` says why none could be had.
@@ -78,6 +117,7 @@ export function useVisitorToken(visitors) {
78
117
  const [state, setState] = useState({});
79
118
  const app = visitors?.app;
80
119
  const inferenceUrl = visitors?.inferenceUrl;
120
+ const battle = visitors?.battle ?? '';
81
121
  useEffect(() => {
82
122
  if (!app || !inferenceUrl) {
83
123
  setState({});
@@ -86,7 +126,7 @@ export function useVisitorToken(visitors) {
86
126
  let cancelled = false;
87
127
  let timer;
88
128
  const mint = () => {
89
- fetchVisitorToken(inferenceUrl, app)
129
+ fetchVisitorToken(inferenceUrl, app, keptVisitorId(), fetch, battle)
90
130
  .then(minted => {
91
131
  if (cancelled) {
92
132
  return;
@@ -109,7 +149,7 @@ export function useVisitorToken(visitors) {
109
149
  clearTimeout(timer);
110
150
  }
111
151
  };
112
- }, [app, inferenceUrl]);
152
+ }, [app, inferenceUrl, battle]);
113
153
  return state;
114
154
  }
115
155
  /** What a token for an application at its address names: `at:<slug>`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datalayer/agent-runtimes",
3
- "version": "1.5.114",
3
+ "version": "1.5.115",
4
4
  "type": "module",
5
5
  "workspaces": [
6
6
  ".",