@chatpanel/events 0.459.0 → 0.461.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/events",
3
- "version": "0.459.0",
3
+ "version": "0.461.0",
4
4
  "description": "The canonical ChatPanel event-log and capability contracts — typed durable facts, clock-free deterministic linearization, schema upcasting, and the invariants the replay harness asserts. Pure, dependency-free ESM shared by the ChatPanel extension, gateway and bridge.",
5
5
  "type": "module",
6
6
  "main": "index.js",
package/prefetch.js CHANGED
@@ -1,9 +1,9 @@
1
- import{researchAsk as P,runResearch as ce}from"./web-research.js";import{frontPagesAskedAbout as he}from"./site-pages.js";import{weatherFromSearch as le}from"./weather-tool.js";import{cardOf as T,CARD_SHOWN_NOTE as ue}from"./a2ui-tool-cards.js";import{PAGE_READ_ARGS as W}from"./page-context.js";const D=/(\bhow(?:'s| is| was|s) (?:the )?(?:weather|forecast|temperature)\b|\bwhat(?:'s| is|s) (?:the )?(?:weather|forecast|temperature)\b|\b(?:weather|forecast|temperature) (?:in|for|at|around|near)\b|\bis it (?:raining|snowing|hot|cold|warm|sunny|cloudy|windy)\b|\b(?:will|does) it (?:rain|snow)\b|\bhow (?:hot|cold|warm|humid|windy) is it\b|^\s*(?:weather|forecast)\b|\b(?:weather|forecast)\s*\??\s*$)/i,pe=/\b(right now|now|today|tonight|this (?:morning|afternoon|evening|weekend|week)|tomorrow|currently|at the moment|these days|later)\b/gi,j=new Set(["here","there","home","outside","my location","my area","my city","where i am","it","that"]),F=8,L="(?:page|tab|article|post|thread|discussion|story|site|website|doc|document|comments?|content|piece|blog(?: post)?|paper|video|readme|pdf)",de=new RegExp(`\\b(?:this|current|the current|the open|open|that)\\s+${L}\\b`,"i"),fe=new RegExp(`^\\s*(?:(?:can you |could you |please )?(?:summari[sz]e|tl;?\\s?dr|recap|give me the gist|what are the key (?:points|takeaways))(?:\\s+(?:it|this|that|here|(?:the|this)\\s+${L}(?:\\s+and\\s+(?:the\\s+)?${L})?))?|what(?:'s| is| are)? (?:people|they|folks|commenters) (?:saying|think(?:ing)?)(?: here| about (?:it|this))?)\\s*[?.!]*\\s*$`,"i"),we=/\b(?:my|our|your|the|this|that|last|today'?s|yesterday'?s)\s+(?:meeting|chat|conversation|call|standup|notes?|email|inbox|calendar|day|week|transcript|thread with)\b|https?:\/\//i,ge=/^\s*(?:(?:please|pls|can you|could you|just|ok,?|no,?|then|so|now)\s+)*(?:use (?:the )?(?:web|internet)(?: search)?|use web ?search|(?:do|run|perform|make|start|try)(?: an?| the)? (?:(?:web|internet|online|google) ?)?search|search for (?:it|that|this)|search (?:the )?(?:web|internet|online)|web ?search(?: it)?|google(?: it| that)?|look (?:it |that )?up(?: online| on the web)?|check (?:the web|online)|try (?:the )?(?:web|internet|a web search|web search)|search (?:it|that|again|online))\b(?:\s+(?:for|about)\s+(.+?))?(?:,?\s+(?:please|pls|thanks|instead|now|then))*\s*[?.!]*\s*$/i;function be(e){const t=ge.exec(String(e||""));if(!t)return null;const n=String(t[1]||"").trim();return n?{query:n}:{}}const me=/\b(?:weather|forecast|temperature|rain|snow)\b/i,ke=/\b(?:rest of (?:the|this) (?:week|weekend|month)|(?:this|next|coming) (?:week|weekend)|(?:the|this) weekend|week ahead|the week|next (?:few|several|couple of) days|coming days|(?:5|7|10|14)[- ]?days?|extended|long[- ]range|two[- ]weeks?)\b/i,ye=/\b(?:i|we) (?:asked|said|wrote|told|searched|talked|discussed|mentioned|looked up|checked)\b|\b(?:did|have|had) (?:i|we)\b|\bhow (?:many|often) (?:times )?(?:i|we|did|have)\b|\bhow many times\b|\bmy (?:chats?|notes?|history|meetings?|conversations?|questions?|searches)\b|\blast time (?:i|we)\b/i,$e=/\b(?:find out more|find (?:out )?more|more (?:info|information|details)|look into (?:it|that|this)|dig (?:deeper|into (?:it|that))|get more details?|find (?:it|that) out|check (?:on )?(?:it|that) (?:again|online)|search (?:for )?more|look (?:it|that) up|find (?:the )?(?:rest|full|whole)(?: of it| forecast)?)\b/i,Se=/^\s*(?:yes|yeah|yep|yup|sure|ok(?:ay)?|k|please(?: do)?|go ahead|go for it|do it|yes please|sure thing|absolutely|of course|ok look|look|search|please search|search it)(?:[\s,.!]+(?:please|thanks|thank you|go ahead|do it|look|search|yes))*[\s.!]*$/i,_e=/\b(?:search the web|web search|search online|search for|look (?:it|that|this) up|look up|check online|find (?:it|that|out|more))\b/i,Ee=/(?:web search for|search the web for|search (?:online )?for|look up|look for)\s+(?:the\s+)?(.{3,160}?)(?:\s*[?.!]|$)/i;function Ae(e){const t=String(e||"").split(/\n+/).map(s=>s.trim()).filter(Boolean).slice(-3).join(" ");if(_e.test(t)&&/\?/.test(t)){const s=(Ee.exec(t)?.[1]||"").replace(/\s+for me$/i,"").trim();if(s)return s}const n=/\b(?:searching(?: the web| online)? for|looking up|checking(?: the web| online)? for)\s+(?:the\s+)?(.{3,160}?)(?:\.\.\.|…|[.!?]|$)/i.exec(t);return n?n[1].trim():""}const O=/^\s*(?:(?:no|nope|actually|but|well|sorry)\b[,.!]?\s*)?(?:i|we) (?:asked|said|meant|wanted)\b/i,q=/\b(?:did|when|how (?:many|often)|earlier|before|yesterday|last (?:time|week|month)|ago|previously|other day)\b/i;function je(e){const t=String(e||"");if(!O.test(t)||q.test(t))return"";const n=t.replace(O,"").replace(/^\s*(?:for|about)\s+/i,"").replace(/[.;]\s+(?:and|also)\s+/gi," and ").replace(/,?\s+not\s+[^.?!]*/i,"").trim();return/^(?:the\s+)?(?:weather|forecast|temperature)\b/i.test(n)?`what is ${/^the\s/i.test(n)?"":"the "}${n}`:""}function Le(e){const t=String(e||"");return O.test(t)&&!q.test(t)?!1:ye.test(t)}const Oe=/^\s*(?:and|what about|how about|now|no,?|ok,?|same for)\b[^?.!]{0,30}[?.!]*\s*$/i,Re=/(?:published|posted|shared|discussed|trending|featured|submitted)\s+(?:on|in|to|at)\s+(?:the\s+)?([a-z0-9][\w.-]*(?:\s+[a-z0-9][\w.-]*)?)/i,R=e=>String(e||"").toLowerCase().replace(/[^a-z0-9]+/g,"");function xe(e,t){if(!t||!(t.title||t.url))return!1;const n=Re.exec(String(e||""));if(!n)return!1;let s="";try{s=new URL(String(t.url||"")).hostname}catch{}const o=R(`${t.title||""} ${s}`),r=n[1].split(/\s+/);return![r.join(""),r[0]].some(l=>R(l).length>=2&&o.includes(R(l)))}function v(e){const t=String(e||"").trim();return!t||t.length>300||we.test(t)?null:de.test(t)||fe.test(t)?{}:null}function b(e){return String(e||"").replace(pe," ").replace(/[?!.,;:]+$/g,"").replace(/^\s*(the|in|at|for|around|near|of)\s+/i,"").replace(/\s+/g," ").trim()}const B=/\b(how|what|what's|whats|is|are|was|will|do|does|can|should|why|when|the|a|an|tell|me|there|here|it|like|about)\b/i;function S(e){const t=e.toLowerCase();return t.length>=2&&t.length<=60&&!j.has(t)&&!B.test(t)&&!/^(weather|forecast|temperature)$/.test(t)&&/^[\p{L}]/u.test(t)&&t.split(/\s+/).length<=5}function U(e){const t=String(e||"").trim();return!D.test(t)||_(t)||/\b(?:love|like|hate|enjoy|miss|prefer)\s+(?:this|the|that|such|today's)?\s*(?:weather|forecast)\b/i.test(t)||/\b(?:api|app|apps|service|widget|feature|code|bug|model|tool|component|test|tests|data|endpoint|sdk|library|module|page|screen)\b/i.test(t)?!1:t.split(/\s+/).length<=12}const Ce=/\s+(?:for|over|during|through|in|this|next|and)?\s*(?:the\s+)?(?:rest of (?:the|this) (?:week|weekend|day|month)|next (?:few|several|couple of|\d+) days|(?:this|next|coming) (?:week|weekend|month|few days)|the (?:weekend|week(?: ahead)?|coming days)|week ahead|\d+[- ]days?(?: forecast)?)\b/gi;function _(e){const t=String(e||"").trim();if(!D.test(t))return"";const n=t.replace(Ce,"").trim();let s=/\b(?:in|at|for|around|near)\s+([^?!.;]+?)(?:\s+(?:right now|now|today|tonight|tomorrow|currently|this \w+))*\s*[?!.]*$/i.exec(n);if(s){const o=b(s[1].split(/\s+(?:and|&|vs\.?|versus|compared (?:to|with)|then|,)\s+/i)[0]);if(S(o))return o;if(S(b(s[1])))return b(s[1])}return s=/^(?:what(?:'s| is) the\s+)?([\p{L}][\p{L}\s,.'-]{1,60}?)\s+(?:weather|forecast|temperature)\b/iu.exec(n),s&&S(b(s[1]))&&!x.test(b(s[1]))||(s=/\b(?:weather|forecast|temperature)\s*[:\-]?\s+([\p{L}][\p{L}\s,.'-]{1,60}?)\s*[?!.]*$/iu.exec(n),s&&S(b(s[1])))?b(s[1]):""}const x=/\b(summari[sz]e|explain|try|again|retry|do|make|write|show|tell|open|read|find|search|help|stop|continue|go|list|give|send|run|check|fix|get|fetch|pull|grab|look ?up|display|compare|bring|thanks|thank|yes|no|please|this|that|my|page|note|file|meeting|chat|sounds?|good|great|nice|cool|fine|perfect|awesome|sure|nothing|else|ok|okay|yeah|yep|nope|bye|hello|hi|hey|time|traffic|news|story|joke|stock|price|you|yourself|him|her|them|us)\b/i,Ne=/^(?:(?:okay|ok|alright|all right|great|cool|thanks|thank you|fine|good|and|also|then|so|now|actually|well|um+|uh+|hmm+|oh|no|wait|sorry|oops)(?:[\s,.!—-]+|$))+/i,Pe=/^(?:(?:i(?: want| wanted| would like|'d like) to know|i'm wondering|i wonder|(?:can|could) you (?:tell|check) (?:me)?|tell me)\s+)/i,M=/^(?:(?:how|what) about|(?:how|what)(?:'s| is|s) it(?: like)?(?: in| at| for| around| near)?|i (?:meant|mean)(?: in)?|it(?:'s|’s| is|s)(?: in)?|(?:in|at|for|around|near))\b[\s,]*/i;function I(e,t){if(!t||t.kind!=="weather")return"";const n=String(e||"").trim().replace(/[?!.]+$/,"").trim(),s=n.replace(Ne,"").trim().replace(Pe,"").trim();if(!s||s.split(/\s+/).length>F)return"";const o=M.test(s)||s!==n&&/^(?:and|also)\b/i.test(n),r=b(s.replace(M,"").replace(/^(?:like\s+)?(?:in|at|for|around|near)\s+/i,""));return!r||/\d/.test(r)||!o&&r.split(/\s+/).length>2||!S(r)||x.test(r)?"":r}const k="([\\p{L}$][\\p{L}\\p{N}.&'-]*(?:\\s+[\\p{L}][\\p{L}\\p{N}.&'-]*){0,3})",Te=[new RegExp(`\\b(?:share price|stock price|stock quote|ticker)\\s+(?:of|for)\\s+${k}`,"iu"),{question:!0,re:new RegExp(`\\b(?:stock|stocks|shares?)\\s+(?:of|for|in)\\s+${k}`,"iu")},new RegExp(`\\b${k}(?:'s)?\\s+(?:stock|shares)\\s+(?:price|doing|trading|today|now|performance|performing|up|down|quote)\\b`,"iu"),new RegExp(`\\b${k}(?:'s)?\\s+(?:share price|stock price|stock quote)\\b`,"iu"),new RegExp(`^\\s*${k}(?:'s)?\\s+(?:stock|shares)\\s*\\??\\s*$`,"iu"),new RegExp(`\\b(?:how|where)(?:'s| is| are)\\s+${k}\\s+(?:stock\\s+|shares\\s+)?trading\\b`,"iu"),new RegExp(`\\bwhat(?:'s| is| are)\\s+${k}\\s+trading at\\b`,"iu"),/\$([A-Z]{1,5})\b/u],We=/^(?:the|a|an|my|our|your|this|that|it|its|their|market|stock market|markets|price|prices|today|now|company|companies|how|what|is|are|doing|of|for|in|weather|forecast|news|time|date|temperature|rain|you|me|us|them|those|these)$/i,De=/^(?:how|what|what's|whats|where|is|are|was|the|a|an|can|could|you|tell|me|about|of|for|in|and|also|so|now|then|please|check|show|give|get)$/i,Fe=/\s+(?:stock|stocks|shares?|price|prices|doing|trading|today|now|right now|currently|at the moment|this (?:morning|afternoon|week)|lately|so far)\b.*$/i;function G(e){const t=e.toLowerCase();return t.length>=1&&t.length<=40&&!We.test(t)&&!B.test(t)&&/^[\p{L}]/u.test(t)&&t.split(/\s+/).length<=4}function qe(e){const t=e.split(/\s+/).filter(Boolean);for(;t.length>1&&De.test(t[0]);)t.shift();return t.join(" ")}function H(e){return String(e||"").replace(/[?!.,;:]+$/g,"").replace(Fe,"").replace(/(?:\s+(?:at|on|up|down|for me|please))+$/i,"").replace(/^\s*(?:the|shares? of|stock of)\s+/i,"").replace(/'s$/i,"").replace(/\s+(?:corp(?:oration)?|inc|co|company|ltd)\.?$/i,t=>t).replace(/\s+/g," ").trim()}function J(e){const t=String(e||"").trim(),n=/\?\s*$/.test(t)||/^\s*(?:(?:hey|hi|ok|okay|so|and|now)[\s,]+)*(?:how|what|where|is|are|can|could|would|will|tell|check|show|give|get|find|look up|please)\b/i.test(t);for(const s of Te){const o=s instanceof RegExp?s:s.re;if(s.question&&!n)continue;const r=o.exec(t);if(!r)continue;const l=qe(H(r[1]));if(G(l))return l}return""}function z(e,t){if(!t||t.kind!=="stock")return"";let n=String(e||"").trim().replace(/[?!.]+$/,"").trim();if(!n||n.split(/\s+/).length>F)return"";n=n.replace(/^(?:(?:okay|ok|fine|good|great|thanks|thank you|cool|alright|all right|that'?s (?:fine|good|great|ok|okay))[\s,.!—-]*)+/i,"").trim();const s=/^(?:(?:and|also|then|so|now)[\s,]+)*(?:how about|what about)\b/i.test(n)||/^(?:and|also)[\s,]+/i.test(n);n=n.replace(/^(?:(?:and|also|then|so|now)[\s,]+)*(?:(?:how|what) about\b)?[\s,]*/i,"").trim();const o=H(n);return!o||!s&&(o.split(/\s+/).length>2||!/[?]\s*$/.test(String(e))&&o.split(/\s+/).length>1)||!G(o)||x.test(o)?"":o}const K=new RegExp("(?<![\\p{L}\\p{N}'])\\p{L}(?:[ \\t.,\\-–]{1,3}\\p{L}(?![\\p{L}\\p{N}'])){2,}","gu");function Y(e){return String(e||"").replace(K,t=>t.replace(/[^\p{L}]/gu,"").toLowerCase())}function ve(e){return[...String(e||"").matchAll(K)].map(t=>t[0].replace(/[^\p{L}]/gu,"").toLowerCase())}const Be=/\b(?:tell me (?:more |everything |all |something )?about|what do you know about|do you know (?:anything )?about|who(?:'s| is| was| are)|look up|lookup|search (?:the web |online |the internet |google )?for|search up|google|find (?:out )?(?:info(?:rmation)?|details|more|anything|something|everything) (?:on|about)|(?:info|information|background|details) (?:on|about)|research)\s+(.+)$/i,Ue=/[.?!;:,()](?=\s|$)|\s(?:uh|um|umm|er|erm|hmm|like|actually|i mean|sorry|the (?:first |last |sur|family )?name|his|her|their|its|it's|it is|spelled|spelt|and (?:tell|give|find|show|let|search|look)|then|please|for me|on the web|online|on google|from the web|if you can|thanks|thank you)\b/i,Me=/^(?:it|this|that|these|those|him|her|them|me|you|yourself|us|he|she|they|we|i|my|our|your|his|their|here|there|on|in|at|to|for|with|from|going|coming|speaking|talking|calling|joining|what|how|why|when|where|which|the weather|weather)\b/i,Ie=/^(?:my|our|your|this|that|today'?s|yesterday'?s|last|next|latest|recent)\b/i,Ge=/^(?:the|a|an)\b/i,He=6;function X(e){const n=(String(e||"").split(Ue)[0]||"").replace(/\s+/g," ").replace(/^["'“‘]+|["'”’]+$/g,"").trim(),s=n.split(" ").filter(Boolean);return!s.length||s.length>He||!new RegExp("\\p{L}","u").test(n)||Me.test(n)?"":n}function Je(e){const t=Be.exec(Y(e));return t?X(t[1]):""}const ze=[[/\b(?:last|sur|family|second) ?name\b|\bsurname\b/i,e=>e.length-1],[/\bfirst name\b|\bgiven name\b/i,()=>0]],Ke=/\b(?:it(?:'s| is)|spelled|spelt|should be|is actually|actually|but|name is)\s+["'“‘]?([\p{L}][\p{L}'-]{1,40})["'”’]?\s*[.!?]*\s*$/iu,Ye=/\b(?:no|nope|not|wrong|incorrect|misspel\w*|spell\w*|typo|name|actually|i meant|i mean)\b/i;function Xe(e,t){const n=e.toLowerCase(),s=t.toLowerCase(),o=Array.from({length:s.length+1},(r,l)=>l);for(let r=1;r<=n.length;r++){let l=o[0];o[0]=r;for(let c=1;c<=s.length;c++){const p=o[c];o[c]=Math.min(o[c]+1,o[c-1]+1,l+(n[r-1]===s[c-1]?0:1)),l=p}}return o[s.length]}function Qe(e,t){return new RegExp("^\\p{Lu}","u").test(t)?e.charAt(0).toUpperCase()+e.slice(1):e}function Q(e,t){const n=String(t||"").trim();if(!n)return null;const s=String(e||""),o=ve(s),r=Y(s);let l=o.at(-1)||"";if(!l&&Ye.test(r)&&(l=Ke.exec(r)?.[1]||""),!l||l.length<2)return null;const c=n.split(/\s+/);let p=-1;for(const[a,h]of ze)if(a.test(r)){p=h(c);break}if(p<0){let a=1/0;c.forEach((h,f)=>{const w=Xe(h,l)/Math.max(h.length,l.length);w<a&&(a=w,p=f)}),a>.6&&(p=c.length===1?0:-1)}if(p<0)return null;const u=c[p];return u.toLowerCase()===l.toLowerCase()?{subject:n,replaced:""}:(c[p]=Qe(l,c.find(a=>new RegExp("^\\p{Lu}","u").test(a))||u),{subject:c.join(" "),replaced:u})}const Ve=/\b(?:search|look|google|check|find|try)\b[^.?!]{0,30}\b(?:web|online|internet|google|up|again|it|him|her|them)\b|\blook(?:ing)? (?:it|that|him|her|them)? ?up\b/i,V=/\b(?:web|online|internet|google)\b/i;function Ze(e,t){if(!t||t.kind!=="lookup"||!t.subject)return null;const n=Q(e,t.subject),s=/\b(?:not|wrong|isn'?t|incorrect|nope)\b/i.test(e);return!n&&!s&&!Ve.test(e)?null:{subject:n?.subject||t.subject,replaced:n?.replaced||"",corrected:!!n||s,web:V.test(e)}}function Z(e,t){const n=Je(e);if(n){const o=Q(e.slice(e.toLowerCase().indexOf(n.toLowerCase())+n.length),n);return{kind:"lookup",subject:o?.subject||n,replaced:o?.replaced||"",corrected:!!o?.replaced,web:V.test(e)}}const s=Ze(e,t);return s?{kind:"lookup",...s}:null}function ee(e){return Ie.test(e)||/@|\d{5,}/.test(e)||!new RegExp("\\p{L}{2,}","u").test(e)?!1:!Ge.test(e)||new RegExp("\\s\\p{Lu}","u").test(e)}const et=/\b(?:news|headlines|stories)\s+(?:on|about|from|in|for|regarding|around)\s+(.+)$/i,tt=/\bwhat(?:'s| is| are)\s+(?:new|happening|going on|the latest|the news)\s+(?:with|in|on|at|around|from)\s+(.+)$/i,nt=/^(?:(?:can|could) you (?:tell|give) me |tell me |give me |show me )?(?:the |any |some )?(?:latest |recent |top |today'?s |breaking )?(.{2,60}?)\s+news(?:\s+(?:today|this (?:morning|week|evening)|right now|lately|these days))?\s*[?.!]*$/i,st=/^(?:(?:can|could) you (?:tell|give) me |tell me |give me |show me |what(?:'s| is| are) )?(?:the |any )?(?:latest |top |today'?s |breaking )?(?:news|headlines)(?:\s+(?:today|this (?:morning|week|evening)|right now))?\s*[?.!]*$/i,te=/\s+(?:today|tonight|this (?:morning|week|evening|year)|right now|lately|these days|recently|now)$/i;function ot(e){const t=String(e||"").trim();if(!t||he(t).length)return null;if(st.test(t))return{subject:""};const n=et.exec(t)||nt.exec(t),s=n?null:tt.exec(t),o=n||s;if(!o)return null;const r=X(o[1].replace(/[?.!]+$/,"").replace(te,"")).replace(te,"");return s&&r.split(/\s+/).length>4||!r||!ee(r)||/^(?:the )?(?:weather|stock|stocks|market)$/i.test(r)?null:{subject:r}}function bt(e){return/^\s*No (?:history matches|web results)\b/.test(String(e||""))}const ne=Object.freeze({page:15e3,web:12e3,lookup:12e3}),rt=6e3;function mt(e){return Object.hasOwn(ne,e?.kind)?ne[e.kind]:rt}const at=/^\s*(?:(?:and|also|ok(?:ay)?|so|then)[,\s]+)?(?:(?:what|how) about|how(?:'s|’s| is| will| does)?(?: it| the weather| things)?(?: be| look(?:ing)?)?|is it|and|for)?\s*(?:(?:right )?now|currently|today|tonight|tomorrow(?: morning| afternoon| evening| night)?|(?:a |the )?day after tomorrow|later(?: today| tonight)?|(?:this|next|the) (?:morning|afternoon|evening|night|weekend|week)|(?:the )?rest of (?:the|this) week|(?:on |this |next )?(?:mon|tues|wednes|thurs|fri|satur|sun)day|outside|out there)\s*[?!.]*\s*$/i;function se(e,t){if(!t||t.kind!=="weather")return"";const n=String(t.subject||"");if(!n||j.has(n.toLowerCase()))return"";const s=String(e||"").toLowerCase();return[...j].some(o=>o!=="it"&&o!=="that"&&new RegExp(`\\b${o}\\b`).test(s))?"":n}function oe(e,t){return!t||t.kind!=="weather"?"":at.test(String(e||""))?String(t.subject||"here"):""}function it(e,t){const n=_(e)||oe(e,t)||I(e,t);if(n)return{kind:"weather",subject:n};if(U(e))return{kind:"weather",subject:se(e,t)||"here"};const s=J(e)||z(e,t);if(s)return{kind:"stock",subject:s};const o=Z(String(e||""),t);if(o)return o;const r=P(e,{previous:t});return r?{kind:"research",subject:r.subject,research:r}:null}function kt(e){const t=(Array.isArray(e)?e:[]).filter(o=>o&&!o.pending&&(o.role==="user"||o.role==="assistant")),n=[];for(let o=0;o<t.length;o++)t[o].role==="user"&&n.push(o);if(n.length<2)return null;let s=null;for(let o=0;o<n.length-1;o++){const r=t[n[o]],l=t[n[o]+1]?.role==="assistant"?t[n[o]+1]:null,c=(r.attachments||[]).find(h=>h?.kind==="prefetch"),p=typeof r.content=="string"?r.content:"",u=it(p,s)||(c?{kind:c.prefetch,...c.research?{research:c.research}:{}}:null)||((l?.steps||[]).some(h=>h?.input?.action==="weather"||h?.tool==="weather")?{kind:"weather"}:null),a=ct(c?.text);s=u&&{...u,...a?{resolved:a}:s?.resolved&&s.kind===u.kind?{resolved:s.resolved}:{}}}return s}function ct(e){const t=/(?:^|\n)\w+ for ([^\n(]+?)\s*\(asked:/.exec(String(e||""));return t?t[1].trim():""}function ht(e,t,n){if(!e?.resolved||e.kind!==t||/,/.test(String(n||"")))return"";const s=String(e.resolved).split(",").map(o=>o.trim()).filter(Boolean);return s.length>1?s.slice(1).join(", "):""}function yt({text:e="",previous:t=null,previousText:n="",previousAnswer:s="",reach:o=new Set,lookup:r=!1,research:l=!1,page:c=!1,tab:p=null,now:u=Date.now()}={}){const a=o instanceof Set?o:new Set(Array.isArray(o)?o:[]),h=[];if(Le(e))return r?re(e,t,a):[];const f=Se.test(String(e||""))?Ae(s):"",w=String(e||"").trim().split(/\s+/).length,$=be(e)||(f?{query:f}:null)||($e.test(String(e||""))&&w<=14?{}:null);if($&&(a.has("find:web_search")||a.has("web_search"))){const i=$.query||String(n||"").trim();if(i){const d=a.has("find:web_search"),g=!$.query;return[{kind:"web",tool:d?"find":"web_search",input:d?{action:"web_search",args:{query:i}}:{query:i},label:`Web — ${i.slice(0,60)}`,subject:i,...me.test(i)?{weather:!0}:{},...g?{borrowed:!0}:{}}]}}if(c&&(a.has("page:read_page")||a.has("read_page"))&&v(e)&&!xe(e,p)){const i=a.has("page:read_page"),d=Oe.test(e)&&v(n)?String(n).trim():"";return[{kind:"page",tool:i?"page":"read_page",input:i?{action:"read_page",args:{...W}}:{...W},label:"This page",...d?{ask:d}:{}}]}const E=a.has("find:weather"),ie=a.has("weather");if(E||ie){e=je(e)||e;const i=_(e)?"":oe(e,t),d=_(e)||(i?i!=="here"?i:"":I(e,t)),g=d||(U(e)?se(e,t)||"here":i?"here":"");if(g){const A=g!=="here"?ht(t,"weather",g):"",C=y=>E?{action:"weather",args:{location:y}}:{location:y};if(h.push({kind:"weather",tool:E?"find":"weather",input:C(g),label:d?`Weather — ${d}`:"Weather — near you",...d?{about:d}:{},...A?{retry:{input:C(`${g}, ${A}`),context:A.split(",")[0].trim()}}:{}}),d&&ke.test(String(e||""))&&(a.has("find:web_search")||a.has("web_search"))){const y=`${d} 10 day weather forecast`,N=a.has("find:web_search");h.push({kind:"web",tool:N?"find":"web_search",input:N?{action:"web_search",args:{query:y}}:{query:y},label:`Web — ${d} extended forecast`,subject:y,weather:!0})}}}const m=a.has("find:web_search");if(!h.length&&(m||a.has("web_search"))){const i=J(e)||z(e,t);if(i){const d=`${i} stock price today`;h.push({kind:"stock",tool:m?"find":"web_search",input:m?{action:"web_search",args:{query:d}}:{query:d},label:`Stock — ${i}`,about:i})}}if(!h.length&&(m||a.has("web_search"))){const i=ot(e);if(i){const d=i.subject?`${i.subject} news today`:"top news today";h.push({kind:"news",tool:m?"find":"web_search",input:m?{action:"web_search",args:{query:d}}:{query:d},label:i.subject?`News — ${i.subject}`:"News — today",subject:i.subject,...i.subject?{about:i.subject}:{}})}}if(l&&!h.length&&(m||a.has("web_search"))){const i=P(e,{previous:t,now:u});if(i){const d=m?"find":"web_search";h.push({kind:"research",tool:d,input:d==="find"?{action:"web_search",args:{query:i.queries[0]}}:{query:i.queries[0]},label:`Research — ${i.subject}`,subject:i.subject,research:[...a].some(g=>/^(?:page:)?(?:open_tab|navigate)$/.test(g))?{...i,browse:!0}:i})}}return r&&!h.length&&h.push(...re(e,t,a)),h}function re(e,t,n){const s=Z(String(e||""),t);if(!s)return[];const{subject:o}=s,r=s.corrected?`The user corrected the name: it is "${o}"${s.replaced?`, not "${s.replaced}"`:""} — use this spelling; earlier answers in this chat were about the wrong name.`:"",l=a=>n.has(`find:${a}`)?{tool:"find",input:h=>({action:a,args:h})}:n.has(a)?{tool:a,input:h=>h}:null,c=[],p=l("history_search"),u=l("web_search");return p&&!s.web&&c.push({kind:"lookup",tool:p.tool,input:p.input({query:o}),label:`Library — ${o}`,subject:o,note:r}),u&&(s.web||ee(o))&&c.push({kind:"lookup",tool:u.tool,input:u.input({query:o}),label:`Web — ${o}`,subject:o,about:o,note:r,fallback:c.length>0}),c}function $t(e=[]){const t=Array.isArray(e)?e:[];for(let n=t.length-1;n>=0;n--)if(t[n]?.role==="user")return(t[n].attachments||[]).some(s=>s?.kind==="prefetch"&&String(s.text||"").trim());return!1}function St(e){const t=typeof e=="string"?e:e&&typeof e.text=="string"?e.text:JSON.stringify(e??""),n=e&&typeof e=="object"&&typeof e.note=="string"?e.note:"",s=T(e);return s?{text:t,note:n,card:s}:{text:t,note:n}}function lt(e,t=""){const n=String(t||"").replace(/^ChatPanel\s*·\s*/u,"").trim();return n&&n!=="ChatPanel"?`${e?.label||""} · ${n}`:e?.label||""}function ut(e){const t=String(e||"");if(!t.startsWith("{"))return t;try{const n=JSON.parse(t);return typeof n?.text!="string"?t:[typeof n.note=="string"?n.note:"",n.text,n.truncated?"(The page continues past what was read.)":""].filter(Boolean).join(`
1
+ import{researchAsk as T,runResearch as ce}from"./web-research.js";import{frontPagesAskedAbout as he}from"./site-pages.js";import{weatherFromSearch as le}from"./weather-tool.js";import{cardOf as P,CARD_SHOWN_NOTE as ue}from"./a2ui-tool-cards.js";import{PAGE_READ_ARGS as W}from"./page-context.js";const D=/(\bhow(?:'s| is| was|s) (?:the )?(?:weather|forecast|temperature)\b|\bwhat(?:'s| is|s) (?:the )?(?:weather|forecast|temperature)\b|\b(?:weather|forecast|temperature) (?:in|for|at|around|near)\b|\bis it (?:raining|snowing|hot|cold|warm|sunny|cloudy|windy)\b|\b(?:will|does) it (?:rain|snow)\b|\bhow (?:hot|cold|warm|humid|windy) is it\b|^\s*(?:weather|forecast)\b|\b(?:weather|forecast)\s*\??\s*$)/i,de=/\b(right now|now|today|tonight|this (?:morning|afternoon|evening|weekend|week)|tomorrow|currently|at the moment|these days|later)\b/gi,L=new Set(["here","there","home","outside","my location","my area","my city","where i am","it","that"]),F=8,j="(?:page|tab|article|post|thread|discussion|story|site|website|doc|document|comments?|content|piece|blog(?: post)?|paper|video|readme|pdf)",pe=new RegExp(`\\b(?:this|current|the current|the open|open|that)\\s+${j}\\b`,"i"),fe=new RegExp(`^\\s*(?:(?:can you |could you |please )?(?:summari[sz]e|tl;?\\s?dr|recap|give me the gist|what are the key (?:points|takeaways))(?:\\s+(?:it|this|that|here|(?:the|this)\\s+${j}(?:\\s+and\\s+(?:the\\s+)?${j})?))?|what(?:'s| is| are)? (?:people|they|folks|commenters) (?:saying|think(?:ing)?)(?: here| about (?:it|this))?)\\s*[?.!]*\\s*$`,"i"),we=/\b(?:my|our|your|the|this|that|last|today'?s|yesterday'?s)\s+(?:meeting|chat|conversation|call|standup|notes?|email|inbox|calendar|day|week|transcript|thread with)\b|https?:\/\//i,ge=/^\s*(?:(?:please|pls|can you|could you|just|ok,?|no,?|then|so|now)\s+)*(?:use (?:the )?(?:web|internet)(?: search)?|use web ?search|(?:do|run|perform|make|start|try)(?: an?| the)? (?:(?:web|internet|online|google) ?)?search|search for (?:it|that|this)|search (?:the )?(?:web|internet|online)|web ?search(?: it)?|google(?: it| that)?|look (?:it |that )?up(?: online| on the web)?|check (?:the web|online)|try (?:the )?(?:web|internet|a web search|web search)|search (?:it|that|again|online))\b(?:\s+(?:for|about)\s+(.+?))?(?:,?\s+(?:please|pls|thanks|instead|now|then))*\s*[?.!]*\s*$/i;function be(e){const t=ge.exec(String(e||""));if(!t)return null;const n=String(t[1]||"").trim();return n?{query:n}:{}}const me=/\b(?:weather|forecast|temperature|rain|snow)\b/i,ke=/\b(?:rest of (?:the|this) (?:week|weekend|month)|(?:this|next|coming) (?:week|weekend)|(?:the|this) weekend|week ahead|the week|next (?:few|several|couple of) days|coming days|(?:5|7|10|14)[- ]?days?|extended|long[- ]range|two[- ]weeks?)\b/i,ye=/\b(?:i|we) (?:asked|said|wrote|told|searched|talked|discussed|mentioned|looked up|checked)\b|\b(?:did|have|had) (?:i|we)\b|\bhow (?:many|often) (?:times )?(?:i|we|did|have)\b|\bhow many times\b|\bmy (?:chats?|notes?|history|meetings?|conversations?|questions?|searches)\b|\blast time (?:i|we)\b/i,$e=/\b(?:find out more|find (?:out )?more|more (?:info|information|details)|look into (?:it|that|this)|dig (?:deeper|into (?:it|that))|get more details?|find (?:it|that) out|check (?:on )?(?:it|that) (?:again|online)|search (?:for )?more|look (?:it|that) up|find (?:the )?(?:rest|full|whole)(?: of it| forecast)?)\b/i,Se=/^\s*(?:yes|yeah|yep|yup|sure|ok(?:ay)?|k|please(?: do)?|go ahead|go for it|do it|yes please|sure thing|absolutely|of course|ok look|look|search|please search|search it)(?:[\s,.!]+(?:please|thanks|thank you|go ahead|do it|look|search|yes))*[\s.!]*$/i,_e=/\b(?:search the web|web search|search online|search for|look (?:it|that|this) up|look up|check online|find (?:it|that|out|more))\b/i,Ee=/(?:web search for|search the web for|search (?:online )?for|look up|look for)\s+(?:the\s+)?(.{3,160}?)(?:\s*[?.!]|$)/i;function Ae(e){const t=String(e||"").split(/\n+/).map(s=>s.trim()).filter(Boolean).slice(-3).join(" ");if(_e.test(t)&&/\?/.test(t)){const s=(Ee.exec(t)?.[1]||"").replace(/\s+for me$/i,"").trim();if(s)return s}const n=/\b(?:searching(?: the web| online)? for|looking up|checking(?: the web| online)? for)\s+(?:the\s+)?(.{3,160}?)(?:\.\.\.|…|[.!?]|$)/i.exec(t);return n?n[1].trim():""}const O=/^\s*(?:(?:no|nope|actually|but|well|sorry)\b[,.!]?\s*)?(?:i|we) (?:asked|said|meant|wanted)\b/i,q=/\b(?:did|when|how (?:many|often)|earlier|before|yesterday|last (?:time|week|month)|ago|previously|other day)\b/i;function Le(e){const t=String(e||"");if(!O.test(t)||q.test(t))return"";const n=t.replace(O,"").replace(/^\s*(?:for|about)\s+/i,"").replace(/[.;]\s+(?:and|also)\s+/gi," and ").replace(/,?\s+not\s+[^.?!]*/i,"").trim();return/^(?:the\s+)?(?:weather|forecast|temperature)\b/i.test(n)?`what is ${/^the\s/i.test(n)?"":"the "}${n}`:""}function je(e){const t=String(e||"");return O.test(t)&&!q.test(t)?!1:ye.test(t)}const Oe=/^\s*(?:and|what about|how about|now|no,?|ok,?|same for)\b[^?.!]{0,30}[?.!]*\s*$/i,Re=/(?:published|posted|shared|discussed|trending|featured|submitted)\s+(?:on|in|to|at)\s+(?:the\s+)?([a-z0-9][\w.-]*(?:\s+[a-z0-9][\w.-]*)?)/i,R=e=>String(e||"").toLowerCase().replace(/[^a-z0-9]+/g,"");function xe(e,t){if(!t||!(t.title||t.url))return!1;const n=Re.exec(String(e||""));if(!n)return!1;let s="";try{s=new URL(String(t.url||"")).hostname}catch{}const o=R(`${t.title||""} ${s}`),r=n[1].split(/\s+/);return![r.join(""),r[0]].some(l=>R(l).length>=2&&o.includes(R(l)))}function v(e){const t=String(e||"").trim();return!t||t.length>300||we.test(t)?null:pe.test(t)||fe.test(t)?{}:null}function b(e){return String(e||"").replace(de," ").replace(/[?!.,;:]+$/g,"").replace(/^\s*(the|in|at|for|around|near|of)\s+/i,"").replace(/\s+/g," ").trim()}const B=/\b(how|what|what's|whats|is|are|was|will|do|does|can|should|why|when|the|a|an|tell|me|there|here|it|like|about)\b/i;function S(e){const t=e.toLowerCase();return t.length>=2&&t.length<=60&&!L.has(t)&&!B.test(t)&&!/^(weather|forecast|temperature)$/.test(t)&&/^[\p{L}]/u.test(t)&&t.split(/\s+/).length<=5}function U(e){const t=String(e||"").trim();return!D.test(t)||_(t)||/\b(?:love|like|hate|enjoy|miss|prefer)\s+(?:this|the|that|such|today's)?\s*(?:weather|forecast)\b/i.test(t)||/\b(?:api|app|apps|service|widget|feature|code|bug|model|tool|component|test|tests|data|endpoint|sdk|library|module|page|screen)\b/i.test(t)?!1:t.split(/\s+/).length<=12}const Ce=/\s+(?:for|over|during|through|in|this|next|and)?\s*(?:the\s+)?(?:rest of (?:the|this) (?:week|weekend|day|month)|next (?:few|several|couple of|\d+) days|(?:this|next|coming) (?:week|weekend|month|few days)|the (?:weekend|week(?: ahead)?|coming days)|week ahead|\d+[- ]days?(?: forecast)?)\b/gi;function _(e){const t=String(e||"").trim();if(!D.test(t))return"";const n=t.replace(Ce,"").trim();let s=/\b(?:in|at|for|around|near)\s+([^?!.;]+?)(?:\s+(?:right now|now|today|tonight|tomorrow|currently|this \w+))*\s*[?!.]*$/i.exec(n);if(s){const o=b(s[1].split(/\s+(?:and|&|vs\.?|versus|compared (?:to|with)|then|,)\s+/i)[0]);if(S(o))return o;if(S(b(s[1])))return b(s[1])}return s=/^(?:what(?:'s| is) the\s+)?([\p{L}][\p{L}\s,.'-]{1,60}?)\s+(?:weather|forecast|temperature)\b/iu.exec(n),s&&S(b(s[1]))&&!x.test(b(s[1]))||(s=/\b(?:weather|forecast|temperature)\s*[:\-]?\s+([\p{L}][\p{L}\s,.'-]{1,60}?)\s*[?!.]*$/iu.exec(n),s&&S(b(s[1])))?b(s[1]):""}const x=/\b(summari[sz]e|explain|try|again|retry|do|make|write|show|tell|open|read|find|search|help|stop|continue|go|list|give|send|run|check|fix|get|fetch|pull|grab|look ?up|display|compare|bring|thanks|thank|yes|no|please|this|that|my|page|note|file|meeting|chat|sounds?|good|great|nice|cool|fine|perfect|awesome|sure|nothing|else|ok|okay|yeah|yep|nope|bye|hello|hi|hey|time|traffic|news|story|joke|stock|price|you|yourself|him|her|them|us)\b/i,Ne=/^(?:(?:okay|ok|alright|all right|great|cool|thanks|thank you|fine|good|and|also|then|so|now|actually|well|um+|uh+|hmm+|oh|no|wait|sorry|oops)(?:[\s,.!—-]+|$))+/i,Te=/^(?:(?:i(?: want| wanted| would like|'d like) to know|i'm wondering|i wonder|(?:can|could) you (?:tell|check) (?:me)?|tell me)\s+)/i,I=/^(?:(?:how|what) about|(?:how|what)(?:'s| is|s) it(?: like)?(?: in| at| for| around| near)?|i (?:meant|mean)(?: in)?|it(?:'s|’s| is|s)(?: in)?|(?:in|at|for|around|near))\b[\s,]*/i;function M(e,t){if(!t||t.kind!=="weather")return"";const n=String(e||"").trim().replace(/[?!.]+$/,"").trim(),s=n.replace(Ne,"").trim().replace(Te,"").trim();if(!s||s.split(/\s+/).length>F)return"";const o=I.test(s)||s!==n&&/^(?:and|also)\b/i.test(n),r=b(s.replace(I,"").replace(/^(?:like\s+)?(?:in|at|for|around|near)\s+/i,""));return!r||/\d/.test(r)||!o&&r.split(/\s+/).length>2||!S(r)||x.test(r)?"":r}const k="([\\p{L}$][\\p{L}\\p{N}.&'-]*(?:\\s+[\\p{L}][\\p{L}\\p{N}.&'-]*){0,3})",Pe=[new RegExp(`\\b(?:share price|stock price|stock quote|ticker)\\s+(?:of|for)\\s+${k}`,"iu"),{question:!0,re:new RegExp(`\\b(?:stock|stocks|shares?)\\s+(?:of|for|in)\\s+${k}`,"iu")},new RegExp(`\\b${k}(?:'s)?\\s+(?:stock|shares)\\s+(?:price|doing|trading|today|now|performance|performing|up|down|quote)\\b`,"iu"),new RegExp(`\\b${k}(?:'s)?\\s+(?:share price|stock price|stock quote)\\b`,"iu"),new RegExp(`^\\s*${k}(?:'s)?\\s+(?:stock|shares)\\s*\\??\\s*$`,"iu"),new RegExp(`\\b(?:how|where)(?:'s| is| are)\\s+${k}\\s+(?:stock\\s+|shares\\s+)?trading\\b`,"iu"),new RegExp(`\\bwhat(?:'s| is| are)\\s+${k}\\s+trading at\\b`,"iu"),/\$([A-Z]{1,5})\b/u],We=/^(?:the|a|an|my|our|your|this|that|it|its|their|market|stock market|markets|price|prices|today|now|company|companies|how|what|is|are|doing|of|for|in|weather|forecast|news|time|date|temperature|rain|you|me|us|them|those|these)$/i,De=/^(?:how|what|what's|whats|where|is|are|was|the|a|an|can|could|you|tell|me|about|of|for|in|and|also|so|now|then|please|check|show|give|get)$/i,Fe=/\s+(?:stock|stocks|shares?|price|prices|doing|trading|today|now|right now|currently|at the moment|this (?:morning|afternoon|week)|lately|so far)\b.*$/i;function G(e){const t=e.toLowerCase();return t.length>=1&&t.length<=40&&!We.test(t)&&!B.test(t)&&/^[\p{L}]/u.test(t)&&t.split(/\s+/).length<=4}function qe(e){const t=e.split(/\s+/).filter(Boolean);for(;t.length>1&&De.test(t[0]);)t.shift();return t.join(" ")}function H(e){return String(e||"").replace(/[?!.,;:]+$/g,"").replace(Fe,"").replace(/(?:\s+(?:at|on|up|down|for me|please))+$/i,"").replace(/^\s*(?:the|shares? of|stock of)\s+/i,"").replace(/'s$/i,"").replace(/\s+(?:corp(?:oration)?|inc|co|company|ltd)\.?$/i,t=>t).replace(/\s+/g," ").trim()}function J(e){const t=String(e||"").trim(),n=/\?\s*$/.test(t)||/^\s*(?:(?:hey|hi|ok|okay|so|and|now)[\s,]+)*(?:how|what|where|is|are|can|could|would|will|tell|check|show|give|get|find|look up|please)\b/i.test(t);for(const s of Pe){const o=s instanceof RegExp?s:s.re;if(s.question&&!n)continue;const r=o.exec(t);if(!r)continue;const l=qe(H(r[1]));if(G(l))return l}return""}function K(e,t){if(!t||t.kind!=="stock")return"";let n=String(e||"").trim().replace(/[?!.]+$/,"").trim();if(!n||n.split(/\s+/).length>F)return"";n=n.replace(/^(?:(?:okay|ok|fine|good|great|thanks|thank you|cool|alright|all right|that'?s (?:fine|good|great|ok|okay))[\s,.!—-]*)+/i,"").trim();const s=/^(?:(?:and|also|then|so|now)[\s,]+)*(?:how about|what about)\b/i.test(n)||/^(?:and|also)[\s,]+/i.test(n);n=n.replace(/^(?:(?:and|also|then|so|now)[\s,]+)*(?:(?:how|what) about\b)?[\s,]*/i,"").trim();const o=H(n);return!o||!s&&(o.split(/\s+/).length>2||!/[?]\s*$/.test(String(e))&&o.split(/\s+/).length>1)||!G(o)||x.test(o)?"":o}const z=new RegExp("(?<![\\p{L}\\p{N}'])\\p{L}(?:[ \\t.,\\-–]{1,3}\\p{L}(?![\\p{L}\\p{N}'])){2,}","gu");function Y(e){return String(e||"").replace(z,t=>t.replace(/[^\p{L}]/gu,"").toLowerCase())}function ve(e){return[...String(e||"").matchAll(z)].map(t=>t[0].replace(/[^\p{L}]/gu,"").toLowerCase())}const Be=/\b(?:tell me (?:more |everything |all |something )?about|what do you know about|do you know (?:anything )?about|who(?:'s| is| was| are)|look up|lookup|search (?:the web |online |the internet |google )?for|search up|google|find (?:out )?(?:info(?:rmation)?|details|more|anything|something|everything) (?:on|about)|(?:info|information|background|details) (?:on|about)|research)\s+(.+)$/i,Ue=/[.?!;:,()](?=\s|$)|\s(?:uh|um|umm|er|erm|hmm|like|actually|i mean|sorry|the (?:first |last |sur|family )?name|his|her|their|its|it's|it is|spelled|spelt|and (?:tell|give|find|show|let|search|look)|then|please|for me|on the web|online|on google|from the web|if you can|thanks|thank you)\b/i,Ie=/^(?:(?:some |any |more |further |additional |extra |the )?(?:info(?:rmation)?|details?|data|context|sources?|references?|research|facts|more)\b|it|this|that|these|those|him|her|them|me|you|yourself|us|he|she|they|we|i|my|our|your|his|their|here|there|on|in|at|to|for|with|from|going|coming|speaking|talking|calling|joining|what|how|why|when|where|which|the weather|weather)\b/i,Me=/^(?:my|our|your|this|that|today'?s|yesterday'?s|last|next|latest|recent)\b/i,Ge=/^(?:the|a|an)\b/i,He=6;function X(e){const n=(String(e||"").split(Ue)[0]||"").replace(/\s+/g," ").replace(/^["'“‘]+|["'”’]+$/g,"").trim(),s=n.split(" ").filter(Boolean);return!s.length||s.length>He||!new RegExp("\\p{L}","u").test(n)||Ie.test(n)?"":n}function Je(e){const t=Be.exec(Y(e));return t?X(t[1]):""}const Ke=[[/\b(?:last|sur|family|second) ?name\b|\bsurname\b/i,e=>e.length-1],[/\bfirst name\b|\bgiven name\b/i,()=>0]],ze=/\b(?:it(?:'s| is)|spelled|spelt|should be|is actually|actually|but|name is)\s+["'“‘]?([\p{L}][\p{L}'-]{1,40})["'”’]?\s*[.!?]*\s*$/iu,Ye=/\b(?:no|nope|not|wrong|incorrect|misspel\w*|spell\w*|typo|name|actually|i meant|i mean)\b/i;function Xe(e,t){const n=e.toLowerCase(),s=t.toLowerCase(),o=Array.from({length:s.length+1},(r,l)=>l);for(let r=1;r<=n.length;r++){let l=o[0];o[0]=r;for(let c=1;c<=s.length;c++){const d=o[c];o[c]=Math.min(o[c]+1,o[c-1]+1,l+(n[r-1]===s[c-1]?0:1)),l=d}}return o[s.length]}function Qe(e,t){return new RegExp("^\\p{Lu}","u").test(t)?e.charAt(0).toUpperCase()+e.slice(1):e}function Q(e,t){const n=String(t||"").trim();if(!n)return null;const s=String(e||""),o=ve(s),r=Y(s);let l=o.at(-1)||"";if(!l&&Ye.test(r)&&(l=ze.exec(r)?.[1]||""),!l||l.length<2)return null;const c=n.split(/\s+/);let d=-1;for(const[a,h]of Ke)if(a.test(r)){d=h(c);break}if(d<0){let a=1/0;c.forEach((h,f)=>{const w=Xe(h,l)/Math.max(h.length,l.length);w<a&&(a=w,d=f)}),a>.6&&(d=c.length===1?0:-1)}if(d<0)return null;const u=c[d];return u.toLowerCase()===l.toLowerCase()?{subject:n,replaced:""}:(c[d]=Qe(l,c.find(a=>new RegExp("^\\p{Lu}","u").test(a))||u),{subject:c.join(" "),replaced:u})}const Ve=/\b(?:search|look|google|check|find|try)\b[^.?!]{0,30}\b(?:web|online|internet|google|up|again|it|him|her|them)\b|\blook(?:ing)? (?:it|that|him|her|them)? ?up\b/i,V=/\b(?:web|online|internet|google)\b/i;function Ze(e,t){if(!t||t.kind!=="lookup"||!t.subject)return null;const n=Q(e,t.subject),s=/\b(?:not|wrong|isn'?t|incorrect|nope)\b/i.test(e);return!n&&!s&&!Ve.test(e)?null:{subject:n?.subject||t.subject,replaced:n?.replaced||"",corrected:!!n||s,web:V.test(e)}}function Z(e,t){const n=Je(e);if(n){const r=Q(e.slice(e.toLowerCase().indexOf(n.toLowerCase())+n.length),n);return{kind:"lookup",subject:r?.subject||n,replaced:r?.replaced||"",corrected:!!r?.replaced,web:V.test(e)}}const s=Ze(e,t);if(s)return{kind:"lookup",...s};const o=nt(e);return o?{kind:"lookup",subject:o,replaced:"",corrected:!1,web:!0}:null}const et=/[,;]?\s*(?:(?:and|so|now|please|pls|just|can you|could you|would you|will you|can u)\s+)*(?:look (?:it |that |this |them )?up|look into (?:it|that|this)|search (?:the web|online|the internet|for (?:it|that|this))|google (?:it|that|this)|find out(?: more)?|research (?:it|that|this))(?:\s+(?:some |any |more |further |additional |extra )?(?:info(?:rmation)?|details?|sources?|more|online|on the web|for me))*(?:\s+(?:and|then)\s+(?:let me know|tell me|get back to me|report back))?\s*[?.!]*/i,tt=/^(?:(?:so|ok(?:ay)?|hey|and|well|now|um+|uh+)[,\s]+)+/i;function nt(e){const t=String(e||""),n=et.exec(t);if(!n)return"";const s=`${t.slice(0,n.index)} ${t.slice(n.index+n[0].length)}`.replace(tt,"").replace(/[,;:\s]+$/,"").replace(/\s+/g," ").trim(),o=s.split(" ").filter(Boolean);return o.length>=3&&new RegExp("\\p{L}{3,}","u").test(s)?o.slice(0,16).join(" "):""}function ee(e){return Me.test(e)||/@|\d{5,}/.test(e)||!new RegExp("\\p{L}{2,}","u").test(e)?!1:!Ge.test(e)||new RegExp("\\s\\p{Lu}","u").test(e)}const st=/\b(?:news|headlines|stories)\s+(?:on|about|from|in|for|regarding|around)\s+(.+)$/i,ot=/\bwhat(?:'s| is| are)\s+(?:new|happening|going on|the latest|the news)\s+(?:with|in|on|at|around|from)\s+(.+)$/i,rt=/^(?:(?:can|could) you (?:tell|give) me |tell me |give me |show me )?(?:the |any |some )?(?:latest |recent |top |today'?s |breaking )?(.{2,60}?)\s+news(?:\s+(?:today|this (?:morning|week|evening)|right now|lately|these days))?\s*[?.!]*$/i,at=/^(?:(?:can|could) you (?:tell|give) me |tell me |give me |show me |what(?:'s| is| are) )?(?:the |any )?(?:latest |top |today'?s |breaking )?(?:news|headlines)(?:\s+(?:today|this (?:morning|week|evening)|right now))?\s*[?.!]*$/i,te=/\s+(?:today|tonight|this (?:morning|week|evening|year)|right now|lately|these days|recently|now)$/i;function it(e){const t=String(e||"").trim();if(!t||he(t).length)return null;if(at.test(t))return{subject:""};const n=st.exec(t)||rt.exec(t),s=n?null:ot.exec(t),o=n||s;if(!o)return null;const r=X(o[1].replace(/[?.!]+$/,"").replace(te,"")).replace(te,"");return s&&r.split(/\s+/).length>4||!r||!ee(r)||/^(?:the )?(?:weather|stock|stocks|market)$/i.test(r)?null:{subject:r}}function yt(e){return/^\s*No (?:history matches|web results)\b/.test(String(e||""))}const ne=Object.freeze({page:15e3,web:12e3,lookup:12e3}),ct=6e3;function $t(e){return Object.hasOwn(ne,e?.kind)?ne[e.kind]:ct}const ht=/^\s*(?:(?:and|also|ok(?:ay)?|so|then)[,\s]+)?(?:(?:what|how) about|how(?:'s|’s| is| will| does)?(?: it| the weather| things)?(?: be| look(?:ing)?)?|is it|and|for)?\s*(?:(?:right )?now|currently|today|tonight|tomorrow(?: morning| afternoon| evening| night)?|(?:a |the )?day after tomorrow|later(?: today| tonight)?|(?:this|next|the) (?:morning|afternoon|evening|night|weekend|week)|(?:the )?rest of (?:the|this) week|(?:on |this |next )?(?:mon|tues|wednes|thurs|fri|satur|sun)day|outside|out there)\s*[?!.]*\s*$/i;function se(e,t){if(!t||t.kind!=="weather")return"";const n=String(t.subject||"");if(!n||L.has(n.toLowerCase()))return"";const s=String(e||"").toLowerCase();return[...L].some(o=>o!=="it"&&o!=="that"&&new RegExp(`\\b${o}\\b`).test(s))?"":n}function oe(e,t){return!t||t.kind!=="weather"?"":ht.test(String(e||""))?String(t.subject||"here"):""}function lt(e,t){const n=_(e)||oe(e,t)||M(e,t);if(n)return{kind:"weather",subject:n};if(U(e))return{kind:"weather",subject:se(e,t)||"here"};const s=J(e)||K(e,t);if(s)return{kind:"stock",subject:s};const o=Z(String(e||""),t);if(o)return o;const r=T(e,{previous:t});return r?{kind:"research",subject:r.subject,research:r}:null}function St(e){const t=(Array.isArray(e)?e:[]).filter(o=>o&&!o.pending&&(o.role==="user"||o.role==="assistant")),n=[];for(let o=0;o<t.length;o++)t[o].role==="user"&&n.push(o);if(n.length<2)return null;let s=null;for(let o=0;o<n.length-1;o++){const r=t[n[o]],l=t[n[o]+1]?.role==="assistant"?t[n[o]+1]:null,c=(r.attachments||[]).find(h=>h?.kind==="prefetch"),d=typeof r.content=="string"?r.content:"",u=lt(d,s)||(c?{kind:c.prefetch,...c.research?{research:c.research}:{}}:null)||((l?.steps||[]).some(h=>h?.input?.action==="weather"||h?.tool==="weather")?{kind:"weather"}:null),a=ut(c?.text);s=u&&{...u,...a?{resolved:a}:s?.resolved&&s.kind===u.kind?{resolved:s.resolved}:{}}}return s}function ut(e){const t=/(?:^|\n)\w+ for ([^\n(]+?)\s*\(asked:/.exec(String(e||""));return t?t[1].trim():""}function dt(e,t,n){if(!e?.resolved||e.kind!==t||/,/.test(String(n||"")))return"";const s=String(e.resolved).split(",").map(o=>o.trim()).filter(Boolean);return s.length>1?s.slice(1).join(", "):""}function _t({text:e="",previous:t=null,previousText:n="",previousAnswer:s="",reach:o=new Set,lookup:r=!1,research:l=!1,page:c=!1,tab:d=null,now:u=Date.now()}={}){const a=o instanceof Set?o:new Set(Array.isArray(o)?o:[]),h=[];if(je(e))return r?re(e,t,a):[];const f=Se.test(String(e||""))?Ae(s):"",w=String(e||"").trim().split(/\s+/).length,$=be(e)||(f?{query:f}:null)||($e.test(String(e||""))&&w<=14?{}:null);if($&&(a.has("find:web_search")||a.has("web_search"))){const i=$.query||String(n||"").trim();if(i){const p=a.has("find:web_search"),g=!$.query;return[{kind:"web",tool:p?"find":"web_search",input:p?{action:"web_search",args:{query:i}}:{query:i},label:`Web — ${i.slice(0,60)}`,subject:i,...me.test(i)?{weather:!0}:{},...g?{borrowed:!0}:{}}]}}if(c&&(a.has("page:read_page")||a.has("read_page"))&&v(e)&&!xe(e,d)){const i=a.has("page:read_page"),p=Oe.test(e)&&v(n)?String(n).trim():"";return[{kind:"page",tool:i?"page":"read_page",input:i?{action:"read_page",args:{...W}}:{...W},label:"This page",...p?{ask:p}:{}}]}const E=a.has("find:weather"),ie=a.has("weather");if(E||ie){e=Le(e)||e;const i=_(e)?"":oe(e,t),p=_(e)||(i?i!=="here"?i:"":M(e,t)),g=p||(U(e)?se(e,t)||"here":i?"here":"");if(g){const A=g!=="here"?dt(t,"weather",g):"",C=y=>E?{action:"weather",args:{location:y}}:{location:y};if(h.push({kind:"weather",tool:E?"find":"weather",input:C(g),label:p?`Weather — ${p}`:"Weather — near you",...p?{about:p}:{},...A?{retry:{input:C(`${g}, ${A}`),context:A.split(",")[0].trim()}}:{}}),p&&ke.test(String(e||""))&&(a.has("find:web_search")||a.has("web_search"))){const y=`${p} 10 day weather forecast`,N=a.has("find:web_search");h.push({kind:"web",tool:N?"find":"web_search",input:N?{action:"web_search",args:{query:y}}:{query:y},label:`Web — ${p} extended forecast`,subject:y,weather:!0})}}}const m=a.has("find:web_search");if(!h.length&&(m||a.has("web_search"))){const i=J(e)||K(e,t);if(i){const p=`${i} stock price today`;h.push({kind:"stock",tool:m?"find":"web_search",input:m?{action:"web_search",args:{query:p}}:{query:p},label:`Stock — ${i}`,about:i})}}if(!h.length&&(m||a.has("web_search"))){const i=it(e);if(i){const p=i.subject?`${i.subject} news today`:"top news today";h.push({kind:"news",tool:m?"find":"web_search",input:m?{action:"web_search",args:{query:p}}:{query:p},label:i.subject?`News — ${i.subject}`:"News — today",subject:i.subject,...i.subject?{about:i.subject}:{}})}}if(l&&!h.length&&(m||a.has("web_search"))){const i=T(e,{previous:t,now:u});if(i){const p=m?"find":"web_search";h.push({kind:"research",tool:p,input:p==="find"?{action:"web_search",args:{query:i.queries[0]}}:{query:i.queries[0]},label:`Research — ${i.subject}`,subject:i.subject,research:[...a].some(g=>/^(?:page:)?(?:open_tab|navigate)$/.test(g))?{...i,browse:!0}:i})}}return r&&!h.length&&h.push(...re(e,t,a)),h}function re(e,t,n){const s=Z(String(e||""),t);if(!s)return[];const{subject:o}=s,r=s.corrected?`The user corrected the name: it is "${o}"${s.replaced?`, not "${s.replaced}"`:""} — use this spelling; earlier answers in this chat were about the wrong name.`:"",l=a=>n.has(`find:${a}`)?{tool:"find",input:h=>({action:a,args:h})}:n.has(a)?{tool:a,input:h=>h}:null,c=[],d=l("history_search"),u=l("web_search");return d&&!s.web&&c.push({kind:"lookup",tool:d.tool,input:d.input({query:o}),label:`Library — ${o}`,subject:o,note:r}),u&&(s.web||ee(o))&&c.push({kind:"lookup",tool:u.tool,input:u.input({query:o}),label:`Web — ${o}`,subject:o,about:o,note:r,fallback:c.length>0}),c}function Et(e=[]){const t=Array.isArray(e)?e:[];for(let n=t.length-1;n>=0;n--)if(t[n]?.role==="user")return(t[n].attachments||[]).some(s=>s?.kind==="prefetch"&&String(s.text||"").trim());return!1}function At(e){const t=typeof e=="string"?e:e&&typeof e.text=="string"?e.text:JSON.stringify(e??""),n=e&&typeof e=="object"&&typeof e.note=="string"?e.note:"",s=P(e);return s?{text:t,note:n,card:s}:{text:t,note:n}}function pt(e,t=""){const n=String(t||"").replace(/^ChatPanel\s*·\s*/u,"").trim();return n&&n!=="ChatPanel"?`${e?.label||""} · ${n}`:e?.label||""}function ft(e){const t=String(e||"");if(!t.startsWith("{"))return t;try{const n=JSON.parse(t);return typeof n?.text!="string"?t:[typeof n.note=="string"?n.note:"",n.text,n.truncated?"(The page continues past what was read.)":""].filter(Boolean).join(`
2
2
 
3
- `)}catch{return t}}function ae(e,t,{now:n=Date.now(),note:s="",card:o=null}={}){const r=T({card:o});if(r)return{...ae(e,`${String(t||"")}
3
+ `)}catch{return t}}function ae(e,t,{now:n=Date.now(),note:s="",card:o=null}={}){const r=P({card:o});if(r)return{...ae(e,`${String(t||"")}
4
4
 
5
- ${ue}`,{now:n,note:s}),card:r};if(e.kind==="web"&&e.weather&&(t=le(t)||t),e.kind==="page"&&(t=ut(t)),e.kind==="research"){const a=String(t||""),{question:h,domain:f,subject:w,slots:$}=e.research||{};return{id:`prefetch_research_${n}`,kind:"prefetch",prefetch:"research",subject:e.subject||w||"",research:{question:h,domain:f,subject:w,slots:$},title:e.label,text:a,chars:a.length}}const l=e.kind==="page"?"this is the page they mean.":e.kind==="web"?`these are web results for "${String(e.subject||"").slice(0,80)}" — answer from them; search again only with different words.`:e.kind==="stock"?`do not call ${e.tool} or any search tool again for the same company. Say the price and change it gives; if it gives none, say you could not find a current price — never estimate one.`:e.kind==="lookup"?`if it is about someone or something else, or found nothing, search again with DIFFERENT words (another spelling, the other source — library or web) — never the same query.${e.note?` ${e.note}`:""}`:`do not call ${e.tool} or any weather/search tool again for the same place.`,c=e.kind==="lookup"||e.kind==="web"?`SEARCHED for "${e.subject}"`:e.kind==="page"?"READ the page the user has open":"FETCHED",p=e.kind==="page"&&e.ask?`
5
+ ${ue}`,{now:n,note:s}),card:r};if(e.kind==="web"&&e.weather&&(t=le(t)||t),e.kind==="page"&&(t=ft(t)),e.kind==="research"){const a=String(t||""),{question:h,domain:f,subject:w,slots:$}=e.research||{};return{id:`prefetch_research_${n}`,kind:"prefetch",prefetch:"research",subject:e.subject||w||"",research:{question:h,domain:f,subject:w,slots:$},title:e.label,text:a,chars:a.length}}const l=e.kind==="page"?"this is the page they mean.":e.kind==="web"?`these are web results for "${String(e.subject||"").slice(0,80)}" — answer from them; search again only with different words.`:e.kind==="stock"?`do not call ${e.tool} or any search tool again for the same company. Say the price and change it gives; if it gives none, say you could not find a current price — never estimate one.`:e.kind==="lookup"?`if it is about someone or something else, or found nothing, search again with DIFFERENT words (another spelling, the other source — library or web) — never the same query.${e.note?` ${e.note}`:""}`:`do not call ${e.tool} or any weather/search tool again for the same place.`,c=e.kind==="lookup"||e.kind==="web"?`SEARCHED for "${e.subject}"`:e.kind==="page"?"READ the page the user has open":"FETCHED",d=e.kind==="page"&&e.ask?`
6
6
 
7
7
  The question about this page: ${e.ask.slice(0,200)}`:"",u=`(ALREADY ${c} for the question below, with ${e.tool}. Answer from this; ${l})
8
8
 
9
- ${String(t||"")}${p}`;return{id:`prefetch_${e.kind}${e.kind==="lookup"?`_${e.input?.action||e.tool}`:""}_${n}`,kind:"prefetch",prefetch:e.kind,...e.subject?{subject:e.subject}:{},title:lt(e,s),text:u,chars:u.length}}async function _t(e,{execute:t,until:n=null,now:s=()=>Date.now(),onActivity:o=()=>{},read:r=null,rerank:l=null}={}){const c=s(),p=u=>{try{o({type:"tool",name:"research",prefetched:!0,...u})}catch{}};p({phase:"start",input:e.input,summary:e.label});try{const{text:u,result:a}=await ce(e,{execute:t,until:n,now:s,read:r,rerank:l,onProgress:w=>p({phase:"progress",summary:`${e.label} — ${w.label}`})});if(!u)return p({phase:"done",status:"skipped",summary:e.label,ms:s()-c}),{attachment:null,text:"",result:a,note:"",status:"skipped"};const h=a.stats,f=`${h.searches} search${h.searches===1?"":"es"} · ${h.sites} site${h.sites===1?"":"s"} · ${(h.ms/1e3).toFixed(1)} s`;return p({phase:"done",status:"ok",summary:`${e.label} — ${f}`,ms:s()-c}),{attachment:ae(e,u,{now:s()}),text:u,result:a,note:f,status:"ok"}}catch(u){const a=`error: ${String(u?.message||u).slice(0,80)}`;return p({phase:"done",status:a,summary:e.label,ms:s()-c}),{attachment:null,text:"",result:null,note:"",status:a}}}export{Le as aboutOwnPast,$t as answeredByPrefetch,ht as borrowedContext,se as carriedPlace,Q as correctedSubject,Y as joinSpelled,Ze as lookupFollowup,lt as lookupLabel,St as lookupResult,Je as lookupSubject,ot as newsAsk,Ae as offeredSearch,v as pageAsk,xe as placedElsewhere,ae as prefetchAttachment,mt as prefetchBudgetMs,bt as prefetchMissed,yt as prefetchPlan,kt as previousAsk,ct as resolvedOf,je as restatedWeather,_t as runResearchItem,z as stockFollowupSubject,J as stockSubject,I as weatherFollowupPlace,oe as weatherFollowupWhen,U as weatherHere,_ as weatherPlace,be as webRedoAsk};
9
+ ${String(t||"")}${d}`;return{id:`prefetch_${e.kind}${e.kind==="lookup"?`_${e.input?.action||e.tool}`:""}_${n}`,kind:"prefetch",prefetch:e.kind,...e.subject?{subject:e.subject}:{},title:pt(e,s),text:u,chars:u.length}}async function Lt(e,{execute:t,until:n=null,now:s=()=>Date.now(),onActivity:o=()=>{},read:r=null,rerank:l=null}={}){const c=s(),d=u=>{try{o({type:"tool",name:"research",prefetched:!0,...u})}catch{}};d({phase:"start",input:e.input,summary:e.label});try{const{text:u,result:a}=await ce(e,{execute:t,until:n,now:s,read:r,rerank:l,onProgress:w=>d({phase:"progress",summary:`${e.label} — ${w.label}`})});if(!u)return d({phase:"done",status:"skipped",summary:e.label,ms:s()-c}),{attachment:null,text:"",result:a,note:"",status:"skipped"};const h=a.stats,f=`${h.searches} search${h.searches===1?"":"es"} · ${h.sites} site${h.sites===1?"":"s"} · ${(h.ms/1e3).toFixed(1)} s`;return d({phase:"done",status:"ok",summary:`${e.label} — ${f}`,ms:s()-c}),{attachment:ae(e,u,{now:s()}),text:u,result:a,note:f,status:"ok"}}catch(u){const a=`error: ${String(u?.message||u).slice(0,80)}`;return d({phase:"done",status:a,summary:e.label,ms:s()-c}),{attachment:null,text:"",result:null,note:"",status:a}}}export{je as aboutOwnPast,Et as answeredByPrefetch,dt as borrowedContext,se as carriedPlace,Q as correctedSubject,Y as joinSpelled,Ze as lookupFollowup,pt as lookupLabel,At as lookupResult,Je as lookupSubject,it as newsAsk,Ae as offeredSearch,v as pageAsk,xe as placedElsewhere,ae as prefetchAttachment,$t as prefetchBudgetMs,yt as prefetchMissed,_t as prefetchPlan,St as previousAsk,nt as questionToLookUp,ut as resolvedOf,Le as restatedWeather,Lt as runResearchItem,K as stockFollowupSubject,J as stockSubject,M as weatherFollowupPlace,oe as weatherFollowupWhen,U as weatherHere,_ as weatherPlace,be as webRedoAsk};
package/voice-brain.js CHANGED
@@ -1 +1 @@
1
- import{createSpeakerGate as R,PINNED_SELF as W}from"./voice-speaker.js";import{createSpeakerClusterer as b,segmentWeight as O}from"./speaker-cluster.js";import{asksChap as C,ROOM_OWNER as L,ROOM_CONTEXT as M}from"./voice-room.js";const y=2,$=4e3,F=4e3,P=4e3,B=.6,T=3e3,x=n=>String(n||"").toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu," ").split(/\s+/).filter(Boolean);function h(n,t){const u=x(n);if(u.length<y||!t)return!1;const e=new Set(x(t));let a=0;for(const i of u)e.has(i)&&a++;return a/u.length>=B}const D="(?:(?:oh|ah|aw|hmm+|um+|uh+|well|so|then|ok(?:ay)?|alright|all right|thanks?|thank you|great|cool|perfect|nice|right|yeah|yes|sure)[\\s,!.]*)*",H="(?:[\\s,!.]*(?:thanks?|thank you|for now|then|now|chap|chad|chop|everyone|everybody|all|guys|friend|buddy|again))*",G=new RegExp(`^${D}(?:bye(?:[\\s-]*bye)*|good\\s*bye|see (?:you|ya)(?: later| soon)?|talk (?:to you )?later|that'?s (?:all|it)(?: for now)?|i'?m done|we'?re done|end (?:the |this )?(?:call|conversation|chat)|hang up|stop (?:voice(?: mode)?|listening)|good\\s*night)${H}[\\s,!.]*$`,"i");function _(n){const t=String(n||"").trim();return!!t&&t.split(/\s+/).length<=8&&G.test(t)}const S="Another voice";function J(){return{phase:"listening",muted:!1,mutedAt:0,pending:"",asked:"",interimWords:0,bargedIn:!1,replyText:"",turnStartedAt:0,segmentStartedAt:0,answerEndedAt:0,gate:null,voices:null,paused:!1,pendingFrom:null,room:[]}}function q(n,t={},{now:u=Date.now}={}){const e={...J(),...n||{}},a=u(),i={},d=R({now:()=>a,seed:e.gate}),r=()=>({state:{...e,gate:d.toJSON()},act:i}),s=()=>{e.phase="listening",e.paused=!1};switch(t.type){case"interim":{if(e.muted)return r();const p=String(t.text||"");if(e.segmentStartedAt||(e.segmentStartedAt=a),e.phase==="listening")return i.caption=e.pending?`${e.pending} ${p}`:p,r();const g=x(p),o=g.slice(Math.max(0,Math.min(e.interimWords,g.length))),l=g.length-e.interimWords;return e.interimWords=g.length,!t.audible||l<y||h(o.join(" "),e.replyText)||(s(),e.bargedIn=!0,i.bargeIn=!0,i.caption=p),r()}case"final":{if(e.muted&&a-e.mutedAt>$)return r();e.interimWords=0;const p=e.bargedIn;e.bargedIn=!1;const g=e.segmentStartedAt||a;e.segmentStartedAt=0;const o=String(t.text||"").trim();if(!o)return r();let l=t.info||{};const f=t.listenTo||(t.onlyMe?"me":"anyone");if(f!=="room"&&t.owner===!1&&!p)return i.held={speaker:S,text:o,count:d.heldCount()+1},i.caption=e.pending,e.paused=!1,r();if(f==="room")return V({s:e,act:i,event:t,said:o,interrupted:p,done:r,t:a});if(Array.isArray(t.vec)&&t.vec.length&&!l.speaker){const m=b({seed:e.voices}),c=m.assign(t.vec,O(t.seconds));e.voices=m.toJSON();const E=c.scores?.[c.label],I=(c.thin||c.weak)&&typeof E=="number"&&E<m.threshold;l={...l,speaker:{label:I?S:c.label,scores:c.scores,...c.weak?{weak:!0}:{},...c.thin?{thin:!0}:{}}}}const k=t.owner===!0?{send:!0,reason:"owner",speaker:W}:d.admit(l),N=e.paused;e.paused=!1;const A=()=>(N&&(i.resume=!0),r());if(!k.send&&!p)return i.held={speaker:k.speaker,text:o,count:d.heldCount()},A();if(_(o))return e.phase!=="listening"&&(i.cancel=!0),s(),e.pending="",i.end=!0,r();if(e.phase==="listening"&&!e.muted&&a-e.answerEndedAt<T&&h(o,e.replyText))return r();if(e.phase==="thinking"||e.phase==="speaking"){if(k.weak||o.split(/\s+/).filter(Boolean).length<y||h(o,e.replyText))return A();const m=!!t.audible;s(),i.cancel=!0,!m&&e.asked&&g-e.turnStartedAt<P&&(e.pending=e.asked)}return e.pending=e.pending?`${e.pending} ${o}`:o,t.info?.endOfTurn===!1&&e.pending.length<F?(i.pending=e.pending,r()):(w(e,i),r())}case"onset":return!t.audible||e.muted||e.phase==="listening"||e.paused?r():d.primary()?(e.paused=!0,i.pause=!0,r()):(s(),i.bargeIn=!0,r());case"commit":return e.pending&&w(e,i),r();case"pause-timeout":return e.paused&&(e.paused=!1,i.resume=!0),r();case"turn-start":return e.asked=String(t.said||""),e.interimWords=0,e.bargedIn=!1,e.replyText="",e.turnStartedAt=a,e.phase="thinking",r();case"reply":return e.replyText=String(t.text||""),e.replyText.trim()&&(e.phase="speaking"),r();case"turn-end":return e.answerEndedAt=a,e.paused=!1,s(),r();case"cancel":return e.paused=!1,s(),r();case"mute":return!!t.on===e.muted||(e.muted=!!t.on,e.muted?e.mutedAt=a:d.reset()),r();case"reset":return d.reset(),e.voices=null,e.pending="",e.pendingFrom=null,e.room=[],r();case"stop":return s(),e.pending="",e.pendingFrom=null,e.room=[],e.muted=!1,r();case"reset-speaker":return d.reset(),r();default:return r()}}function w(n,t){t.send=n.pending,n.pendingFrom&&(t.from=n.pendingFrom,n.room.length&&(t.room=n.room),n.room=[]),n.pending="",n.pendingFrom=null}function V({s:n,act:t,event:u,said:e,interrupted:a,done:i,t:d}){const r=u.owner!==!0;let s=L;if(r&&(s=S,Array.isArray(u.vec)&&u.vec.length)){const o=b({seed:n.voices}),l=o.assign(u.vec,O(u.seconds));n.voices=o.toJSON();const f=l.scores?.[l.label];(l.thin||l.weak)&&typeof f=="number"&&f<o.threshold||(s=l.label)}const p={label:s,guest:r},g=n.paused;if(n.paused=!1,r&&!a&&!C(e)&&!(n.pending&&n.pendingFrom?.label===s))return n.room=[...n.room,{label:s,text:e}].slice(-M),t.heard={label:s,text:e},g&&(t.resume=!0),i();if(!r&&_(e))return n.phase!=="listening"&&(t.cancel=!0),n.phase="listening",n.pending="",n.pendingFrom=null,t.end=!0,i();if(n.phase==="listening"&&!n.muted&&d-n.answerEndedAt<T&&h(e,n.replyText))return i();if(n.phase==="thinking"||n.phase==="speaking"){if(e.split(/\s+/).filter(Boolean).length<y||h(e,n.replyText))return g&&(t.resume=!0),i();n.phase="listening",t.cancel=!0}return n.pending&&n.pendingFrom&&n.pendingFrom.label!==s?(w(n,t),n.pending=e,n.pendingFrom=p,t.pending=e,i()):(n.pending=n.pending?`${n.pending} ${e}`:e,n.pendingFrom=p,u.info?.endOfTurn===!1&&n.pending.length<F?(t.pending=n.pending,i()):(w(n,t),i()))}const z=n=>({primary:n?.gate?.primary||"",held:n?.gate?.held||0});export{S as ANOTHER_VOICE,P as CONTINUATION_WINDOW_MS,B as ECHO_OVERLAP,T as ECHO_TAIL_MS,F as MAX_PENDING_CHARS,y as MIN_BARGE_IN_WORDS,$ as MUTE_GRACE_MS,J as initialVoiceState,_ as isFarewell,h as looksLikeEcho,z as voiceSpeaker,q as voiceStep};
1
+ import{createSpeakerGate as R,PINNED_SELF as W}from"./voice-speaker.js";import{createSpeakerClusterer as O,segmentWeight as T}from"./speaker-cluster.js";import{asksChap as C,ROOM_OWNER as L,ROOM_CONTEXT as M}from"./voice-room.js";const k=2,$=4e3,F=4e3,P=4e3,B=.6,N=3e3,x=n=>String(n||"").toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu," ").split(/\s+/).filter(Boolean);function y(n,t){const o=x(n);if(o.length<k||!t)return!1;const e=new Set(x(t));let a=0;for(const s of o)e.has(s)&&a++;return a/o.length>=B}const D="(?:(?:oh|ah|aw|hmm+|um+|uh+|well|so|then|ok(?:ay)?|alright|all right|thanks?|thank you|great|cool|perfect|nice|right|yeah|yes|sure)[\\s,!.]*)*",H="(?:[\\s,!.]*(?:thanks?|thank you|for now|then|now|chap|chad|chop|everyone|everybody|all|guys|friend|buddy|again))*",G=new RegExp(`^${D}(?:bye(?:[\\s-]*bye)*|good\\s*bye|see (?:you|ya)(?: later| soon)?|talk (?:to you )?later|that'?s (?:all|it)(?: for now)?|i'?m done|we'?re done|end (?:the |this )?(?:call|conversation|chat)|hang up|stop (?:voice(?: mode)?|listening)|good\\s*night)${H}[\\s,!.]*$`,"i");function _(n){const t=String(n||"").trim();return!!t&&t.split(/\s+/).length<=8&&G.test(t)}const S="Another voice";function J(){return{phase:"listening",muted:!1,mutedAt:0,pending:"",asked:"",interimWords:0,bargedIn:!1,replyText:"",turnStartedAt:0,segmentStartedAt:0,answerEndedAt:0,gate:null,voices:null,paused:!1,pendingFrom:null,room:[]}}function q(n,t={},{now:o=Date.now}={}){const e={...J(),...n||{}},a=o(),s={},p=R({now:()=>a,seed:e.gate}),r=()=>({state:{...e,gate:p.toJSON()},act:s}),c=()=>{e.phase="listening",e.paused=!1};switch(t.type){case"interim":{if(e.muted)return r();const l=String(t.text||"");if(e.segmentStartedAt||(e.segmentStartedAt=a),e.phase==="listening")return s.caption=e.pending?`${e.pending} ${l}`:l,r();const u=x(l),i=u.slice(Math.max(0,Math.min(e.interimWords,u.length))),d=u.length-e.interimWords;return e.interimWords=u.length,!t.audible||d<k||y(i.join(" "),e.replyText)||(c(),e.bargedIn=!0,s.bargeIn=!0,s.caption=l),r()}case"final":{if(e.muted&&a-e.mutedAt>$)return r();e.interimWords=0;const l=e.bargedIn;e.bargedIn=!1;const u=e.segmentStartedAt||a;e.segmentStartedAt=0;const i=String(t.text||"").trim();if(!i)return r();let d=t.info||{};const m=t.listenTo||(t.onlyMe?"me":"anyone");if(m!=="room"&&t.owner===!1&&!l)return s.held={speaker:S,text:i,count:p.heldCount()+1},s.caption=e.pending,e.paused=!1,r();if(m==="room")return V({s:e,act:s,event:t,said:i,interrupted:l,done:r,t:a});if(Array.isArray(t.vec)&&t.vec.length&&!d.speaker){const h=O({seed:e.voices}),f=h.assign(t.vec,T(t.seconds));e.voices=h.toJSON();const E=f.scores?.[f.label],I=(f.thin||f.weak)&&typeof E=="number"&&E<h.threshold;d={...d,speaker:{label:I?S:f.label,scores:f.scores,...f.weak?{weak:!0}:{},...f.thin?{thin:!0}:{}}}}const g=t.owner===!0?{send:!0,reason:"owner",speaker:W}:p.admit(d),w=e.paused;e.paused=!1;const A=()=>(w&&(s.resume=!0),r());if(!g.send&&!l)return s.held={speaker:g.speaker,text:i,count:p.heldCount()},A();if(_(i))return e.phase!=="listening"&&(s.cancel=!0),c(),e.pending="",s.end=!0,r();if(e.phase==="listening"&&!e.muted&&a-e.answerEndedAt<N&&y(i,e.replyText))return r();if(e.phase==="thinking"||e.phase==="speaking"){if(g.weak||i.split(/\s+/).filter(Boolean).length<k||y(i,e.replyText))return A();const h=!!t.audible;c(),s.cancel=!0,!h&&e.asked&&u-e.turnStartedAt<P&&(e.pending=e.asked)}return e.pending=e.pending?`${e.pending} ${i}`:i,t.info?.endOfTurn===!1&&e.pending.length<F?(s.pending=e.pending,r()):(b(e,s),r())}case"onset":return!t.audible||e.muted||e.phase==="listening"||e.paused?r():p.primary()?(e.paused=!0,s.pause=!0,r()):(c(),s.bargeIn=!0,r());case"commit":return e.pending&&b(e,s),r();case"pause-timeout":return e.paused&&(e.paused=!1,s.resume=!0),r();case"turn-start":return e.asked=String(t.said||""),e.interimWords=0,e.bargedIn=!1,e.replyText="",e.turnStartedAt=a,e.phase="thinking",r();case"reply":return e.replyText=String(t.text||""),e.replyText.trim()&&(e.phase="speaking"),r();case"turn-end":return e.answerEndedAt=a,e.paused=!1,c(),r();case"cancel":return e.paused=!1,c(),r();case"mute":return!!t.on===e.muted||(e.muted=!!t.on,e.muted?e.mutedAt=a:p.reset()),r();case"reset":return p.reset(),e.voices=null,e.pending="",e.pendingFrom=null,e.room=[],r();case"stop":return c(),e.pending="",e.pendingFrom=null,e.room=[],e.muted=!1,r();case"reset-speaker":return p.reset(),r();default:return r()}}function b(n,t){const o=n.pendingFrom?{label:n.pendingFrom.label,guest:n.pendingFrom.guest}:null;o?.guest&&!C(n.pending)?(t.heard={label:o.label,text:n.pending},n.room=[...n.room,t.heard].slice(-M)):(t.send=n.pending,o&&(t.from=o,n.room.length&&(t.room=n.room),n.room=[])),n.pending="",n.pendingFrom=null}function V({s:n,act:t,event:o,said:e,interrupted:a,done:s,t:p}){const r=o.owner===!0,c=Number(o.seconds)||0;let l=L;if(!r&&(l=S,Array.isArray(o.vec)&&o.vec.length)){const m=O({seed:n.voices}),g=m.assign(o.vec,T(o.seconds));n.voices=m.toJSON();const w=g.scores?.[g.label];(g.thin||g.weak)&&typeof w=="number"&&w<m.threshold||(l=g.label)}const u={label:l,guest:!r,seconds:c},i=n.paused;if(n.paused=!1,r&&!n.pending&&_(e))return n.phase!=="listening"&&(t.cancel=!0),n.phase="listening",n.pendingFrom=null,t.end=!0,s();if(n.phase==="listening"&&!n.muted&&p-n.answerEndedAt<N&&y(e,n.replyText))return s();if(n.phase==="thinking"||n.phase==="speaking"){if(e.split(/\s+/).filter(Boolean).length<k||y(e,n.replyText))return i&&(t.resume=!0),s();r||a?(n.phase="listening",t.cancel=!0):i&&(t.resume=!0)}const d=n.pendingFrom;return n.pending=n.pending?`${n.pending} ${e}`:e,n.pendingFrom=d?u.seconds>d.seconds||u.seconds===d.seconds&&u.guest?u:d:u,o.info?.endOfTurn===!1&&n.pending.length<F?(t.pending=n.pending,s()):(b(n,t),s())}const z=n=>({primary:n?.gate?.primary||"",held:n?.gate?.held||0});export{S as ANOTHER_VOICE,P as CONTINUATION_WINDOW_MS,B as ECHO_OVERLAP,N as ECHO_TAIL_MS,F as MAX_PENDING_CHARS,k as MIN_BARGE_IN_WORDS,$ as MUTE_GRACE_MS,J as initialVoiceState,_ as isFarewell,y as looksLikeEcho,z as voiceSpeaker,q as voiceStep};
package/voice-room.js CHANGED
@@ -1,6 +1,4 @@
1
- const p=Object.freeze(["me","room","anyone"]),d="me",i="You",m=6,h=1200;function g(t={}){const e=t?.ui?.voice||{};return p.includes(e.listenTo)?e.listenTo:e.onlyMe===!1?"anyone":d}const O=t=>t==="me"||t==="room",f=/^(?:(?:so|and|but|ok(?:ay)?|hey|um+|uh+|well|chap|chad)[,\s]+)*(?:what|what's|whats|who|who's|whose|whom|where|where's|when|why|how|how's|which|is|isn't|are|aren't|am|was|were|can|can't|could|would|will|won't|do|does|doesn't|did|didn't|should|shall|may|might|have|has|tell|explain|give|show|find|help|remind|translate|define|say)\b/i,w=/\b(?:hey\s+)?(?:chap|chad)\b/i;function S(t){const e=String(t||"").trim();return e?/\?\s*$/.test(e)||f.test(e)||w.test(e):!1}const l=`Several people are in the room with you. Each message starts with who said it: "${i}:" is the person whose Chap you are; "Speaker 1:", "Speaker 2:" and so on are other people in the room.`,y="This question is from a guest in the room, not the person whose Chap you are. Answer it helpfully, but do not use or reveal that person's personal information — their memories, notes, messages, calendar, contacts, history, location or anything said to you privately. If the answer needs it, say that only they can ask for that.";function x({text:t="",from:e=null,room:n=[]}={}){const c=String(t||"").trim(),u=String(e?.label||i),r=e?.guest===!0;let o=(Array.isArray(n)?n:[]).slice(-m).map(s=>`${s?.label||"Someone"}: ${String(s?.text||"").trim()}`).filter(s=>!/:\s*$/.test(s)).join(`
2
- `);o.length>h&&(o=o.slice(-h));const a=`${u}: ${c}`;return{text:o?`(Said in the room just before:
3
- ${o})
4
-
5
- ${a}`:a,guest:r,hint:r?`${l}
6
- ${y}`:l}}function b(t={}){const e=t?.ui||{};return{...t,mcpServers:[],recipes:[],skills:[],ui:{...e,guestTurn:!0,memory:{...e.memory||{},enabled:!1,recall:!1},historyContextMode:"off",historyTools:!1,mcpToolsMode:"off",search:{...e.search||{},personalFirst:!1}}}}export{d as DEFAULT_LISTEN_TO,y as GUEST_HINT,p as LISTEN_TO,m as ROOM_CONTEXT,l as ROOM_HINT,i as ROOM_OWNER,S as asksChap,b as guestPrefs,O as judgesOwner,g as listenToOf,x as roomMessage};
1
+ const p=Object.freeze(["me","room","anyone"]),w="me",f="You",m=6,u=1200;function _(n={}){const e=n?.ui?.voice||{};return p.includes(e.listenTo)?e.listenTo:e.onlyMe===!1?"anyone":w}const O=n=>n==="me"||n==="room",g=/^(?:(?:so|and|but|ok(?:ay)?|hey|um+|uh+|well|chap|chad)[,\s]+)*(?:what|what's|whats|who|who's|whose|whom|where|where's|when|why|how|how's|which|is|isn't|are|aren't|am|was|were|can|can't|could|would|will|won't|do|does|doesn't|did|didn't|should|shall|may|might|have|has|tell|explain|give|show|find|help|remind|translate|define|say)\b/i,y=/\b(?:hey\s+)?(?:chap|chad)\b/i,x=/\b(?:i (?:was |am |'m )?wonder(?:ing)?|i(?:'d| would) (?:like|love) to (?:know|find out|hear)|i want(?:ed)? to (?:know|find out)|(?:do|does) (?:you|anyone|anybody) know|any idea|i(?:'m| am) curious|can (?:you|someone|anyone) (?:tell|help|find|check|explain|look)|tell (?:me|us))\b/i;function b(n){const e=String(n||"").trim();return e?/\?\s*$/.test(e)||g.test(e)||x.test(e)||y.test(e):!1}const S='Several people are in the room with you. Answer what was asked, directly. Do not repeat or quote the question, and do not begin with a name or a label such as "You:" or "Chap:".',T="This question is from a guest in the room, not the person whose Chap you are. Answer it helpfully, but do not use or reveal that person's personal information — their memories, notes, messages, calendar, contacts, history, location or anything said to you privately. If the answer needs it, say that only they can ask for that.";function k({text:n="",from:e=null,room:i=[]}={}){const t=String(n||"").trim(),r=String(e?.label||f),o=e?.guest===!0;let a=(Array.isArray(i)?i:[]).slice(-m).map(s=>`${s?.label||"Someone"} said: "${String(s?.text||"").trim()}"`).filter(s=>!/: ""$/.test(s)).join(`
2
+ `);a.length>u&&(a=a.slice(-u));const c=o?`${r}, a guest in the room, asked this.`:"The person whose Chap you are asked this.";return{text:`${r}: ${t}`,speaker:{label:r,guest:o},guest:o,hint:[S,c,...o?[T]:[],...a?[`Said in the room just before:
3
+ ${a}`]:[]].join(`
4
+ `)}}function A(n={}){const e=n?.ui||{};return{...n,mcpServers:[],recipes:[],skills:[],ui:{...e,guestTurn:!0,memory:{...e.memory||{},enabled:!1,recall:!1},historyContextMode:"off",historyTools:!1,mcpToolsMode:"off",search:{...e.search||{},personalFirst:!1}}}}const l=/^\s*(?:\*\*|__)?(?:you|chap|assistant|ai|answer|response|speaker \d+|another voice)(?:\*\*|__)?\s*:\s*/i,d=n=>[...String(n||"").matchAll(/[\p{L}\p{N}']+/gu)].map(e=>({w:e[0].toLowerCase().replace(/'/g,""),end:e.index+e[0].length}));function E(n,{question:e="",done:i=!1}={}){let t=String(n||"");for(let o=l.exec(t);o;o=l.exec(t))t=t.slice(o[0].length);if(!i&&/^\s*(?:\*\*|__)?[A-Za-z]{0,9}(?: \d{0,2})?(?:\*\*|__)?\s*$/.test(t)&&t.trim().length<12)return{text:"",hold:!0};const r=d(String(e||"").replace(l,"")).map(o=>o.w);if(r.length>=3){const o=d(t),h=Math.min(o.length,r.length);let a=0;for(let s=0;s<h;s++)o[s].w===r[s]&&a++;const c=h>0&&a===h;if(!i&&c&&o.length<r.length)return{text:"",hold:!0};if(o.length>=r.length&&a/r.length>=.8){t=t.slice(o[r.length-1].end).replace(/^[\s?.!,:;—–-]+/,"");for(let s=l.exec(t);s;s=l.exec(t))t=t.slice(s[0].length)}}return{text:t,hold:!1}}export{w as DEFAULT_LISTEN_TO,T as GUEST_HINT,p as LISTEN_TO,m as ROOM_CONTEXT,S as ROOM_HINT,f as ROOM_OWNER,b as asksChap,E as cleanReplyStart,A as guestPrefs,O as judgesOwner,_ as listenToOf,k as roomMessage};