@chatpanel/events 0.458.1 → 0.460.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/lookup-decider.js +1 -1
- package/package.json +1 -1
- package/prefetch.js +4 -4
- package/turn-pipeline.js +3 -3
- package/voice-room.js +4 -6
package/lookup-decider.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decideIntent as p,intentItems as
|
|
1
|
+
import{decideIntent as p,intentItems as w,intentNeedOptions as x,intentSchema as f,intentNeeds as m}from"./turn-intent.js";const b=a=>[...Array.isArray(a)?a:[]].reverse().find(e=>e?.role==="user"&&typeof e.content=="string")?.content?.trim()||"";async function g({messages:a=[],reach:e,classify:i,attached:n=null,now:o=()=>Date.now()}={}){if(typeof i!="function")return null;const t=b(a);if(!t)return null;const s=x(e,{attached:n}),c=o();let l;try{l=await i({state:t.slice(0,600),questions:{need:{type:"choice",instructions:"Which source must the assistant look at before it replies to this message?",options:s}},wake:!1,budgetMs:4e3})}catch{return null}const r=l?.answers?.need;if(!r||!s.some(d=>d.value===r.value))return null;const h=r.value==="web"||r.value==="weather"||r.value==="own_data",u={request:t,kind:r.value==="none"?"chat":"find",need:r.value,query:h?t.slice(0,160):"",...r.value==="page"?{aboutPage:!0}:{},...r.value==="document"?{aboutDocument:!0}:{},...Number.isFinite(r.p)?{p:r.p}:{}};return{intent:u,items:w(u,{reach:e}),ms:Math.max(0,o()-c),model:String(l?.model||l?.provider||"")}}const y=Object.freeze(["find:web_search","find:weather","find:history_search"]),k=Object.freeze([{text:"i had 10 g of fiber, 20g fat and 100 g protein. which did i have the most?",expect:"none"},{text:"what causes thumb nails to become bumpy",expect:"none"},{text:"write a haiku about autumn",expect:"none"},{text:"what is 17 times 23",expect:"none"},{text:"thanks, that helps",expect:"none"},{text:"explain recursion simply",expect:"none"},{text:"open a new tab and go to example.com",expect:"none"},{text:"rewrite this sentence to sound friendlier: send me the file now",expect:"none"},{text:"whats new on hacker news today",expect:"web"},{text:"who won the world cup final this year",expect:"web"},{text:"price of nvidia stock right now",expect:"web"},{text:"find the closest ice cream shop near 98065",expect:"web"},{text:"weather in seattle tomorrow",expect:"weather"},{text:"will it rain in Paris this weekend",expect:"weather"},{text:"what did we decide in yesterday's standup",expect:"own_data"},{text:"what did i say about the budget last week",expect:"own_data"}]);async function $({decide:a,checks:e=k,onRow:i=null,now:n=()=>Date.now()}={}){const o=[];for(const t of e){const s=n();let c=null;try{c=await a([{role:"user",content:t.text}])}catch{c=null}const l=c?.intent?.need??null,r={text:t.text,expect:t.expect,got:l,query:c?.intent?.query||"",ms:Math.max(0,n()-s),ok:l===t.expect};o.push(r);try{i?.(r,o.length,e.length)}catch{}}return{score:o.filter(t=>t.ok).length,of:o.length,rows:o}}function _({complete:a=null,classify:e=null,reach:i=y,attached:n=null}={}){const o=new Set(i);return e?t=>g({messages:t,reach:o,classify:e,attached:n}):a?t=>p({messages:t,reach:o,attached:n,complete:s=>a(s,{maxTokens:160,schema:f(m(o,{attached:n}),{attached:n}),role:"decide"})}):async()=>null}function D({by:a="",need:e="",query:i="",ms:n=0,kept:o=!1,late:t=!1}={}){const s=t?"took too long — answered without it, the usual rules applied":e?o?"nothing to add — the rules' plan stood":e==="none"?"nothing to look up":e==="page"?"read the page on the screen":e==="document"?"read the attached file":`${{web:"search the web",weather:"get the weather",own_data:"search your own notes and chats"}[e]||e}${i?` for “${String(i).slice(0,80)}”`:""}`:"no decision — the usual rules applied",c=n>0?` · ${n<1e3?`${Math.round(n)} ms`:`${(n/1e3).toFixed(1)} s`}`:"";return`Decided${a?` by ${a}`:""}: ${s}${c}`}export{y as CHECK_REACH,k as DECIDER_CHECKS,$ as checkDecider,g as classifyIntent,D as decidedLine,_ as deciderFor};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/events",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.460.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=
|
|
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=
|
|
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||"")}${
|
|
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/turn-pipeline.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{isSmallWindow as
|
|
2
|
-
`):"",J=e=>e instanceof Set?e:new Set(Array.isArray(e)?e:[]),I={knowledge:()=>({id:"knowledge",kind:"tool",role:"knowledge",title:"Search the knowledge base"}),document:()=>({id:"document",kind:"tool",role:"document",title:"Read the attached document"}),gather:(e=[])=>({id:"gather",kind:"tool",role:"gather",title:"Look up",...e.length?{needs:e}:{}}),facts:()=>({id:"facts",kind:"tool",role:"facts",title:"Look up each part"}),check:(e=[])=>({id:"check",kind:"rule",role:"check",title:"Check",needs:e}),write:()=>({id:"write",kind:"generate",role:"write",title:"Answer",needs:["check"],fallback:"skip"})},Q=e=>{const l=!!(e.kb?.length&&e.can?.knowledge),q=(e.material||[]).some(c=>!c.fresh),h=!!(e.small&&(e.can?.documents&&e.documents?.length&&(e.fresh?.length||e.intent?.aboutDocument===!0)||q&&e.intent?.aboutDocument===!0)),m=[...l?[I.knowledge()]:[],...h?[I.document()]:[]],u=[...m,...e.items.length?[I.gather(m.map(c=>c.id))]:[]];return[...u,I.check(u.map(c=>c.id)),I.write()]},V=/\b(?:search(?:ing)? (?:the )?(?:web|internet|online)|on the (?:web|internet)|online|google|look (?:it |this |that )?up online|web search|the latest|news)\b/i,we=/\b(?:my|our) (?:notes?|chats?|history|meetings?|records?|memor(?:y|ies))\b|\bi (?:noted|wrote|saved|said)\b|\bwe (?:decided|discussed|said|agreed)\b|\bdid i (?:note|write|save|say)\b/i,Ze=new Set(["web","research","lookup"]),pe=Object.freeze([{id:"research",label:"Several things asked at once: each looked up, read and checked (opt-in)",when:e=>e.small&&!e.agent&&e.settings.pipeline===!0&&e.decided==="web"&&e.parts.length>=2&&e.can.read&&e.can.gather&&e.can.rerank,plan:()=>[I.facts(),I.check(["facts"]),I.write()]},{id:"passthrough",label:"A large window or a coding agent: its own tools, the rules' look-ups fetched first",when:e=>!e.small||e.agent,plan:Q},{id:"lookup",label:"One thing to fetch before the model answers",when:e=>e.items.length>0,plan:Q},{id:"chat",label:"Nothing to look up",when:()=>!0,plan:Q}]),P=[...pe];function ge(e){if(!e||typeof e.id!="string"||!e.id)throw new he("SHAPE","lane: id required");if(typeof e.when!="function"||typeof e.plan!="function")throw new he("SHAPE",`lane ${e.id}: when(route) and plan(route) required`);return Object.freeze({label:e.id,...e})}function $t(e,{before:l=null}={}){const q=ge(e),h=P.findIndex(u=>u.id===q.id);h>=0&&P.splice(h,1);const m=l?P.findIndex(u=>u.id===l):0;return P.splice(m<0?0:m,0,q),()=>{const u=P.indexOf(q);u>=0&&P.splice(u,1)}}function Dt(){return P.map(e=>({id:e.id,label:e.label}))}function et({messages:e=[],reach:l,target:q={},settings:h={},now:m=()=>Date.now()}={}){const u=Array.isArray(e)?e:[],c=u.findLastIndex(g=>g?.role==="user");if(c<0)return null;const k=j(u[c]),_=Number(q.window)||0,f=q.kind==="agent",b=Me(u.slice(0,c+1)).map(g=>({id:g.id,title:g.title||g.id,docs:Number(g.docs)||0})),x=me(u.slice(0,c+1)),C=x.filter(g=>(u[c].attachments||[]).includes(g)),B=Ge(u,{at:c}),A={at:c,question:k,window:_,small:ie(_)&&!f,agent:f,kept:!1,items:[],planned:[],world:!1,research:!1,decided:"",intent:null,parts:[],kb:b,documents:x,fresh:C,material:B,why:b.length?[`a knowledge base is attached: ${b.map(g=>g.title).join(", ")}`]:[]};if((u[c].attachments||[]).some(g=>g?.kind==="prefetch"))return{...A,kept:!0,why:[...A.why,"the message already carries a look-up"]};const n=u.slice(0,c),K=j(n.findLast(g=>g?.role==="user")),L=j(n.findLast(g=>g?.role==="assistant"&&typeof g.content=="string")),M=u[c].ambientPage||(u[c].attachments||[]).find(g=>g?.kind==="page")||null,S=$e({question:k,previous:Ee(u.slice(0,c+1)),previousText:K,previousAnswer:L,reach:J(l),window:_,personal:!!h.personal,lookup:h.lookup??null,tab:M,now:m()});return{...A,items:S.prefetch,planned:S.prefetch,world:S.world,research:S.research,why:[...A.why,...S.why.filter(g=>g!==S.tools.why)]}}async function ke(e={}){const l=typeof e.now=="function"?e.now:()=>Date.now(),q=l(),h=Array.isArray(e.messages)?e.messages:[],m=e.target&&typeof e.target=="object"?e.target:{},u=e.settings&&typeof e.settings=="object"?e.settings:{},c=e.models&&typeof e.models=="object"?e.models:{},k=J(e.reach),_=[...J(e.armable)],f=Re({onEvent:e.onEvent,now:l,runId:e.runId||`turn-${q}`,threadId:e.threadId||""}),b=Number(m.window)||0,x=j(h.findLast(A=>A?.role==="user")),C=[],B=(A={})=>({status:"prepared",lane:"chat",route:null,messages:h,attachments:[],withheld:[],steps:[],tools:G({window:b,question:x,answered:O(h),reference:me(h).length>0}),context:Y({window:b,question:x,answered:O(h)}),world:!1,research:!1,answered:O(h),answer:null,parts:[],facts:[],knowledge:null,plan:{steps:C},timing:{ms:l()-q},...A});f.runStarted({window:b});try{const A=e.resume?.checkpoint?.route||null;let n=A||et({messages:h,reach:k,target:m,settings:u,now:l});if(!n)return f.runFinished({lane:"chat",status:"prepared"}),B();const K=Array.isArray(h[n.at]?.attachments)?h[n.at].attachments:[],L=K.find(a=>a?.kind==="page")||null,M=h[n.at]?.ambientPage,S=L||(M?.url&&(k.has("page:read_page")||k.has("read_page"))?M:null),g=(n.material||[]).filter(a=>a.attachment!==L),N={page:S?{title:S.title||"",url:S.url||""}:!1,documents:[...(n.documents||[]).map(a=>({title:a.title||"",type:a.type||"",pages:a.pages??null,fresh:(n.fresh||[]).includes(a)})),...g.map(a=>({title:a.attachment.title||a.attachment.kind,type:a.attachment.kind,material:!0,fresh:a.fresh}))]},T={documents:typeof e.documents?.open=="function",gather:typeof e.execute=="function"&&k.size>0,decide:typeof c.decide=="function"||typeof c.classify=="function",read:typeof(c.read||c.decide)=="function",write:typeof c.write=="function",rerank:typeof e.rerank=="function",knowledge:typeof e.knowledge?.search=="function"&&n.kb?.length>0};T.gather||(n={...n,items:[],planned:[]});const t={messages:h,question:x,window:b,target:m,settings:u,reach:k,route:n,can:T,attachments:[],withheld:[],steps:[],facts:[],parts:[],answer:null,found:!1,text:"",budget:{searches:0},timing:{},handoff:null},Z=a=>{for(const i of a?.steps||[])C.push({id:i.id,role:i.role||i.kind,kind:i.kind,status:i.status,ms:i.cost?.ms??null,provider:i.assigned?.provider||i.assigned?.model||null,...i.blocked?{blocked:i.blocked}:{},...i.error?{error:i.error}:{}})},ye=()=>e.pageIndex?.cache?{page:{cache:e.pageIndex.cache,budgetChars:fe({window:b,small:!!t.route?.small}),question:t.route?.intent?.request||t.question||"",query:t.route?.intent?.query||""}}:{},ee=(a={})=>({execute:e.execute,fetched:e.fetched||null,deadline:e.deadline||null,events:f,now:l,limits:e.limits?.gather||{},budget:t.budget,remember:e.remember||{},signal:e.signal||null,read:e.read||null,rerank:e.rerank||null,cards:e.cards===!0,...ye(),...a}),W={async decide(){const a=h.map(D=>({role:D.role,content:j(D),...D.pending?{pending:!0}:{}})),i=l();f.stepStarted("decide",{label:"Deciding what to look up"});const s=D=>c.decide(D,{maxTokens:160,schema:Ie(Pe(k,{attached:N}),{attached:N}),role:"decide"}),r=typeof c.classify=="function"?await _e({messages:a,reach:k,classify:c.classify,attached:N,now:l}).catch(()=>null):await ve({messages:a,reach:k,planned:n.planned,complete:s,attached:N,now:l}).catch(()=>null),p=h[n.at]?.pageChosen===!0&&!!N.page&&r?.intent&&r.intent.need!=="page"?{...r.intent,need:"page",aboutPage:!0,query:"",...r.intent.need!=="none"?{also:r.intent.need,query:r.intent.query}:{}}:null,o=p?{...r,intent:p,items:R(p,{reach:k})}:r,y=l()-i;f.stepFinished("decide",{label:o?o.items[0]?.label||"Nothing to look up":"No decision — the usual rules apply",status:o?"ok":"none",ms:y});const $={by:String(o?.model||e.decider?.name||""),need:o?.intent?.need||"",query:o?.intent?.query||"",kept:!!o?.intent?.kept};return t.steps.push({kind:"decide",tool:"decide",input:{parts:o?.items.length||0},label:de({...$,ms:y}),summary:de({...$,ms:y}),decided:$,status:o?"ok":"none",ms:y}),o},async knowledge(a,i,s){const r=e.knowledge,d=l();f.stepStarted("knowledge",{label:"Searching the knowledge base"});const p=c.read||c.decide||null,o=await ze(t.question,{search:r.search,outline:r.outline||null,read:r.read||null,complete:p?(w,v)=>p(w,{...v,role:"read"}):null,kbName:r.name||n.kb.map(w=>w.title).join(", "),docs:r.docs||[],answer:s.answer!=null?String(s.answer):"",ask:r.ask!==!1&&u.ask!==!1,now:l,late:()=>!!e.signal?.aborted,onProgress:w=>f.custom("knowledge",w)}),y=l()-d;if(o.ask&&s.answer===void 0)throw f.stepFinished("knowledge",{label:o.ask.question,status:"waiting",ms:y}),new ue({...o.ask,step:"knowledge"});o.attachment&&(t.attachments.push(o.attachment),f.custom("attachment",{attachment:o.attachment})),t.found=t.found||o.hits.length>0||o.read.some(w=>w.passages?.length||w.outline?.length);const $=o.read.reduce((w,v)=>w+(v.passages?.length||0),0),D=o.frame?.whole?"Knowledge base: the outline read":o.hits.length?`Knowledge base: ${o.hits.length} passage${o.hits.length===1?"":"s"} found, ${$} read`:"Knowledge base: nothing matched";return t.knowledge={hits:o.hits.length,read:$,rounds:o.rounds,verdict:o.verdict,how:o.how,whole:!!o.frame?.whole,cites:o.attachment?.cites||[]},t.steps.push({kind:"knowledge",tool:"kb",input:{query:t.question.slice(0,120)},label:D,status:"ok",ms:y}),f.stepFinished("knowledge",{label:D,status:"ok",ms:y}),{found:o.hits.length,read:$,rounds:o.rounds}},async document(){const a=l(),i=t.route.intent?.aboutDocument===!0,s=i?(t.route.material||[]).filter(w=>!w.fresh).map(w=>w.attachment):[],d=[...e.documents?.open?i?t.route.documents:t.route.fresh:[],...s],p=w=>s.includes(w)?Ye(w):e.documents.open(w);f.stepStarted("document",{label:`Reading ${d.length===1?d[0].title||"the attached document":`${d.length} attached documents`}`});let o;try{o=await He({question:t.route.intent?.request||t.question,documents:d,open:p,budgetChars:fe({window:b,small:t.route.small})})}catch(w){const v=l()-a;return t.steps.push({kind:"document",tool:"files",input:{documents:d.length},label:`The attached document could not be read: ${String(w?.message||w).slice(0,80)}`,status:"error",ms:v}),f.stepFinished("document",{label:"The attached document could not be read",status:"error",ms:v}),{read:0,skipped:d.length}}const y=l()-a;o.attachment&&(t.attachments.push(o.attachment),f.custom("attachment",{attachment:o.attachment}),t.found=!0),t.document={read:o.read,skipped:o.skipped,how:o.how,cites:o.attachment?.cites||[]};const $=o.read.reduce((w,v)=>w+v.pages.length,0),D=o.read.length?`Document read: ${o.read.map(w=>`${w.title} (${w.how==="whole"?`${w.of} page${w.of===1?"":"s"}`:`page${w.pages.length===1?"":"s"} ${w.pages.join(", ")} of ${w.of}`})`).join(", ")}`:`The attached document could not be read here${o.skipped[0]?.why?` — ${o.skipped[0].why}`:""}`;return t.steps.push({kind:"document",tool:"files",input:{documents:d.length,pages:$},label:D,status:o.read.length?"ok":"none",ms:y}),f.stepFinished("document",{label:D,status:o.read.length?"ok":"none",ms:y}),{read:o.read.length,pages:$,skipped:o.skipped.length,how:o.how}},async gather(a,i){let s=Array.isArray(i?.items)?i.items:t.route.items;const r=t.knowledge?.hits>0?"the knowledge base":t.document?.read?.length&&t.route.intent?.aboutDocument!==!1?"the attached document":"";if(r&&t.route.small&&!V.test(t.question)){const p=s.filter(o=>o&&!o.asked&&Ze.has(o.kind));if(p.length){s=s.filter(o=>!p.includes(o));for(const o of p)t.steps.push({kind:"aside",tool:o.tool||"find",input:o.input||{},label:`${o.label||"Web search"} set aside — ${r} answered`,status:"ok",ms:0});n=t.route={...t.route,why:[...t.route.why,`${r} answered — the web is not searched for it`]}}}if(!s.length)return{found:!1,attachments:0,statuses:[],aside:!0};const d=await ce(s,ee());return t.attachments.push(...d.attachments),t.steps.push(...d.steps),t.found=t.found||d.found,{found:d.found,attachments:d.attachments.length,statuses:d.results.map(p=>p?.status||"skipped")}},async facts(a,i,s){try{return await W.readParts(a,i,s)}catch(r){return t.parts=[],t.facts=[],{...await W.gather(a,i,s),fellBack:String(r?.message||r).slice(0,120)}}},async readParts(){const a=Ne(t.route.parts),i=c.read||c.decide,s=async d=>{const p=R({need:"web",query:d},{reach:k})[0];if(!p)return{results:[],status:"no-engines"};const o=await ce([p],ee({attach:!1})),y=o.results[0],$=y&&(y.status==="ok"||y.status==="cached")?Ce(y.text).results:[],D=$.length?"ok":y?.why?"budget":We(y?.note)||(String(y?.status||"").startsWith("error")?"error":"nothing");return{results:$,status:D,step:o.steps[0]}},r=await Fe({request:t.route.intent?.request||t.question,parts:a,search:s,complete:i,rerank:e.rerank||null,deadline:e.deadline||null,events:f,hooks:e.hooks||null,today:e.today||"",limits:{readConcurrency:Je({concurrency:m.concurrency,device:m.kind==="device"}),...e.limits?.facts||{}},late:()=>!!e.signal?.aborted,now:l});return t.parts=r.parts,t.facts=r.facts,t.steps.push(...r.trail),t.found=r.facts.some(d=>d?.found),{found:r.facts.filter(d=>d?.found).length,of:r.parts.length,calls:r.calls,searches:r.searches}},async check(){const a=t.facts.filter(r=>r?.found);if(t.parts.length){const r=je({parts:t.parts,facts:t.facts});t.answer={text:r.text,final:!0,note:r.note}}const i=O(h),s=t.found||i;return t.answered=s,t.tools=t.parts.length?{offer:!1,rounds:1,why:"every part was looked up and checked"}:t.route.agent?{offer:!0,rounds:null,why:"an agent keeps its own tools"}:G({window:b,question:x,answered:s,decided:t.route.decided,reference:se()}),t.context=Y({window:t.route.agent?0:b,question:x,answered:s}),{answered:s,offer:t.tools.offer,final:!!t.answer?.final}},async ask(a,i,s){if(s.answer===void 0)throw new ue(a.ask||{question:a.title});return s.answer},async write(){const a=`${e.runId||"turn"}:answer`;f.textStart(a);let i="";if(t.answer?.final)i=t.answer.text,f.textContent(a,i);else{const s=await c.write({messages:U(),tools:t.tools,context:t.context,lane:t.lane},{onToken:d=>f.textContent(a,d)}),r=tt({messages:U(),window:b},{answer:s});i=r.text,t.answer={text:i,final:!1,note:r.note},r.text!==String(s||"")&&f.custom("answer",{text:i})}return f.textEnd(a),t.text=i,i}},H=e.runners&&typeof e.runners=="object"?e.runners:{},be=a=>(i,s,r)=>typeof H[a]=="function"?H[a](i,s,{...r,turn:t,defaults:W}):W[a](i,s,r),te=Ke({runners:{"*":(a,i,s)=>{const r=a.role||a.kind;if(!W[r]&&typeof H[r]!="function")throw new Error(`no runner for stage ${r}`);return be(r)(a,i,s)}},hooks:e.hooks||null,now:l}),ne={rule:()=>({provider:"harness"}),capability:()=>null,model:a=>a.role==="write"?T.write?{model:"write"}:null:a.role==="decide"||a.kind==="decide"?T.decide?{model:"decide"}:null:{model:"read"}},se=()=>(n.documents||[]).length>0&&!(t.document?.read?.length>0),U=()=>t.attachments.length||t.withheld.length?h.map((a,i)=>i===n.at?{...a,attachments:[...(a.attachments||[]).filter(s=>!t.withheld.includes(s)),...t.attachments]}:a):h;if(!A&&!n.kept&&T.gather&&T.decide&&!n.agent&&Te({window:b,local:!!m.local,chosen:!!m.chosen,allowed:u.lookups!==!1,messages:h.map(a=>({role:a.role,content:j(a)})),reach:k,planned:n.planned,attached:N})){const a=l(),i=await te.run(le({id:"route",origin:"chat",steps:[{id:"decide",kind:"decide",role:"decide",title:"Decide what to look up"}]},ne),{});Z(i),t.timing.decideMs=l()-a;let s=i.outputs.decide;if(s?.intent?.aboutDocument===!0&&g.length&&!g.some(d=>d.fresh)&&!(n.documents||[]).length&&!Xe(g.map(d=>d.attachment),Ue(x))){const{also:d,...p}=s.intent,o={...p,need:d||"none",query:d?s.intent.query:"",aboutDocument:!1};s={...s,intent:o,items:R(o,{reach:k})},n={...n,why:[...n.why,"the question names nothing the attached material holds — not about it"]}}if(s?.intent&&(n={...n,items:s.items,decided:s.intent.need,intent:s.intent,parts:s.intent.need==="web"&&Array.isArray(s.intent.parts)?s.intent.parts:[],world:z(s.items),why:[...n.why,s.intent.kept?"the decider found nothing to add — the rules' plan stands":`the decider asked for ${s.intent.need}`]}),s?.intent&&s.intent.need==="page"&&L&&!s.items.length&&(t.found=!0,n={...n,why:[...n.why,"the open page is what the question is about — answered by it"]}),s?.intent?.aboutDocument===!0&&(n.material||[]).some(d=>d.fresh&&d.attachment!==L)&&(t.found=!0,n={...n,why:[...n.why,"the material attached with this message is what the question is about — answered by it"]}),s?.intent&&s.intent.need!=="page"&&s.intent.aboutPage===!1){t.withheld=K.filter(d=>d?.auto&&d.kind==="page"),!L&&S&&t.withheld.push({kind:"page",title:S.title||"",url:S.url||"",ambient:!0});for(const d of t.withheld)t.steps.push({kind:"aside",tool:"page",input:{title:d.title||"",url:d.url||""},label:"This page set aside — the question is not about it",status:"ok",ms:0});t.withheld.length&&(n={...n,why:[...n.why,"the open page is not what the question is about — set aside"]})}if(s?.intent?.aboutDocument===!0&&s.intent.also){const p=(s.intent.also==="own_data"?we.test(x):V.test(x))?R({need:s.intent.also,query:s.intent.query},{reach:k}).map(y=>({...y,asked:!0})):[],o=s.intent.also==="web"?"Web search":s.intent.also==="own_data"?"Your own records":s.intent.also;p.length||t.steps.push({kind:"aside",tool:"find",input:{query:s.intent.query||""},label:`${o} set aside — the attached document is what the question is about`,status:"ok",ms:0}),n={...n,items:p,world:z(p),why:[...n.why,p.length?`${o.toLowerCase()} asked for by name — searched beside the document`:"the attached document is what the question is about — nothing else is searched for it"]}}if(s?.intent?.aboutPage===!0&&s.intent.also){const p=(s.intent.also==="own_data"?we.test(x):V.test(x))?R({need:s.intent.also,query:s.intent.query},{reach:k}):[],o=s.intent.also==="web"?"Web search":s.intent.also==="own_data"?"Your own records":s.intent.also;p.length||t.steps.push({kind:"aside",tool:"find",input:{query:s.intent.query||""},label:`${o} set aside — the page open on the screen is what the question is about`,status:"ok",ms:0}),n={...n,items:[...n.items.filter(y=>y?.kind==="page"),...p],world:z(p),why:[...n.why,p.length?`${o.toLowerCase()} asked for by name — searched beside the page`:"the open page is what the question is about — nothing else is searched for it"]}}const r=s?.intent?.act===!0&&!X(k)?_.filter(d=>X([d])):[];r.length?(t.arm=r,t.tools={offer:!0,rounds:ie(b)?Se:null,why:`asked to act — ${r.join(", ")} offered`},n={...n,items:[],planned:[],why:[...n.why,`asked to act on the computer — ${r.join(", ")} offered for this turn`]}):s?.intent?.act===!0&&!X(k)&&(t.handoff={kind:"agent",why:"act",request:s.intent.request||x},t.answer={text:Le,final:!0,note:""},n={...n,items:[],planned:[],why:[...n.why,"asked to act on the computer, and nothing here can — offered to an agent that can"]})}!A&&u.home&&n.items.length&&(n={...n,items:De(n.items,u.home)}),n={...n,settings:{pipeline:u.pipeline===!0},can:T,world:n.world||z(n.items)},t.route=n;const ae=Array.isArray(e.lanes)&&e.lanes.length?e.lanes.map(ge):P,E=A&&ae.find(a=>a.id===e.resume.checkpoint.lane)||ae.find(a=>{try{return!!a.when(n)}catch{return!1}})||pe.at(-1);t.lane=E.id,f.stateDelta([{op:"add",path:"/lane",value:E.id},{op:"add",path:"/need",value:n.decided||(n.items[0]?Oe(n.items[0])?"web":n.items[0].kind:"none")}]),f.stepStarted("lane",{lane:E.id});const qe=l(),xe=E.plan(n).filter(a=>a.role!=="write"||T.write),F=await te.run(le({id:`turn-${E.id}`,origin:"chat",flow:!0,steps:xe},ne),{...e.resume?{resume:{outputs:e.resume.checkpoint?.outputs||{},answers:e.resume.answers||{}}}:{}});Z(F),t.timing.laneMs=l()-qe,f.stepFinished("lane",{lane:E.id,status:F.status});const Ae={lane:E.id,need:n.decided||"",decided:n.decided,request:n.intent?.request||"",parts:n.parts,world:n.world,kept:n.kept,why:n.why},oe={lane:E.id,route:Ae,messages:U(),attachments:t.attachments,withheld:t.withheld.map(a=>({id:a.id??null,kind:a.kind,title:a.title||"",url:a.url||"",why:"the question is not about it",...a.ambient?{ambient:!0}:{}})),steps:t.steps,tools:t.tools||G({window:b,question:x,answered:t.found||O(h),decided:n.decided,reference:se()}),context:t.context||Y({window:b,question:x,answered:t.found||O(h)}),world:n.world,research:!!n.research&&!n.world,answered:t.answered??(t.found||O(h)),answer:t.answer,parts:t.parts,facts:t.facts,knowledge:t.knowledge||null,document:t.document||null,handoff:t.handoff||null,arm:t.arm||[],plan:{steps:C},timing:{...t.timing,ms:l()-q},window:b};if(F.status==="waiting"){const{settings:a,can:i,...s}=n,r={...oe,status:"waiting",ask:F.waiting[0]?.ask||null,checkpoint:{lane:E.id,route:s,outputs:F.checkpoint.outputs,waiting:F.waiting.map(d=>d.stepId)}};return f.runFinished({lane:E.id,status:"waiting"}),r}const re=t.answer&&(t.answer.final||T.write)?"answered":"prepared";return f.runFinished({lane:E.id,status:re,found:t.facts.filter(a=>a?.found).length,parts:t.parts.length}),{...oe,status:re}}catch(A){const n=String(A?.message||A);return f.runError(n),B({status:"failed",error:n})}}async function Et(e={},{askPerson:l=null,maxAsks:q=2,fallback:h=null}={}){let m=await ke(e);for(let u=0;u<q&&m.status==="waiting"&&m.ask;u+=1){let c=null;try{c=typeof l=="function"?await l(m.ask):null}catch{c=null}const k=Array.isArray(m.ask.options)?m.ask.options:[],_=c!=null&&String(c).trim()?String(c).trim():h??(k.length?k[k.length-1]:""),f=m.ask.step||m.checkpoint?.waiting?.[0]||"ask";m=await ke({...e,resume:{checkpoint:m.checkpoint,answers:{...e.resume?.answers||{},[f]:_}}})}return m}function tt(e={},{answer:l="",shims:q=null}={}){if(e.answer?.final)return{text:e.answer.text,note:e.answer.note||""};const h=Qe(l);if(h.fired)try{q?.fire?.("answer.wrapper-echo",{lines:h.fired})}catch{}const m=h.text;if(!m.trim())return{text:m,note:""};const u=Ve(m,e.messages||[]).echoed;if(u)try{q?.fire?.("answer.context-echo",{})}catch{}const c=Be({answer:m,messages:e.messages||[],window:e.window??0});return{text:c?`${m}
|
|
1
|
+
import{isSmallWindow as he,SMALL_WINDOW_ROUNDS as Ie}from"./context-window.js";import{planTurn as Le,toolPlan as V,contextPlan as Z,placeItems as Pe,worldPlanned as H}from"./retrieval-plan.js";import{previousAsk as _e,answeredByPrefetch as N}from"./prefetch.js";import{wantsDecision as Oe,decideIntent as Ne,intentItems as B,intentSchema as je,intentNeeds as Fe,actsOnComputer as ee}from"./turn-intent.js";import{classifyIntent as Ce,decidedLine as me}from"./lookup-decider.js";const We="I can't do that from here: nothing connected to this chat can change files or run commands on your computer. An agent that can use your computer can do it for you.";import{gatherItems as fe,isWebSearch as Re}from"./turn-gather.js";import{partsOf as Me,gatherFacts as Be,finishAnswer as Ke}from"./question-plan.js";import{parseSearchText as ze}from"./web-research.js";import{searchFailureOf as Ue}from"./web-search-tool.js";import{createTurnEvents as Ge}from"./turn-events.js";import{turnGroundingNote as He}from"./answer-grounding.js";import{assign as we}from"./plan.js";import{createExecutor as Ye,PlanPause as pe}from"./plan-executor.js";import{EventError as ge}from"./event.js";import{kbAttachmentsOf as Xe}from"./kb-capability.js";import{kbResearch as Je}from"./kb-research.js";import{attachedDocumentsOf as ke}from"./attached-paths.js";import{documentContext as Qe,documentBudget as ye,documentTerms as Ve}from"./document-context.js";import{threadMaterialOf as Ze,materialReader as et,questionTouches as tt}from"./thread-material.js";import{partsAtOnce as nt}from"./digest.js";import{stripEchoedWrapper as st,contextEcho as at}from"./answer-grounding.js";const be=Object.freeze({device:1500,api:6e3,agent:6e3}),Lt=Object.freeze(["decide","knowledge","document","gather","facts","check","ask","write"]),C=e=>typeof e?.content=="string"?e.content:Array.isArray(e?.content)?e.content.map(l=>typeof l?.text=="string"?l.text:"").join(`
|
|
2
|
+
`):"",te=e=>e instanceof Set?e:new Set(Array.isArray(e)?e:[]),L={knowledge:()=>({id:"knowledge",kind:"tool",role:"knowledge",title:"Search the knowledge base"}),document:()=>({id:"document",kind:"tool",role:"document",title:"Read the attached document"}),gather:(e=[])=>({id:"gather",kind:"tool",role:"gather",title:"Look up",...e.length?{needs:e}:{}}),facts:()=>({id:"facts",kind:"tool",role:"facts",title:"Look up each part"}),check:(e=[])=>({id:"check",kind:"rule",role:"check",title:"Check",needs:e}),write:()=>({id:"write",kind:"generate",role:"write",title:"Answer",needs:["check"],fallback:"skip"})},ne=e=>{const l=!!(e.kb?.length&&e.can?.knowledge),x=(e.material||[]).some(c=>!c.fresh),m=!!(e.small&&(e.can?.documents&&e.documents?.length&&(e.fresh?.length||e.intent?.aboutDocument===!0)||x&&e.intent?.aboutDocument===!0)),f=[...l?[L.knowledge()]:[],...m?[L.document()]:[]],h=[...f,...e.items.length?[L.gather(f.map(c=>c.id))]:[]];return[...h,L.check(h.map(c=>c.id)),L.write()]},se=/\b(?:search(?:ing)? (?:the )?(?:web|internet|online)|on the (?:web|internet)|online|google|look (?:it |this |that )?up online|web search|the latest|news)\b/i,xe=/\b(?:my|our) (?:notes?|chats?|history|meetings?|records?|memor(?:y|ies))\b|\bi (?:noted|wrote|saved|said)\b|\bwe (?:decided|discussed|said|agreed)\b|\bdid i (?:note|write|save|say)\b/i,ot=new Set(["web","research","lookup"]),qe=Object.freeze([{id:"research",label:"Several things asked at once: each looked up, read and checked (opt-in)",when:e=>e.small&&!e.agent&&e.settings.pipeline===!0&&e.decided==="web"&&e.parts.length>=2&&e.can.read&&e.can.gather&&e.can.rerank,plan:()=>[L.facts(),L.check(["facts"]),L.write()]},{id:"passthrough",label:"A large window or a coding agent: its own tools, the rules' look-ups fetched first",when:e=>!e.small||e.agent,plan:ne},{id:"lookup",label:"One thing to fetch before the model answers",when:e=>e.items.length>0,plan:ne},{id:"chat",label:"Nothing to look up",when:()=>!0,plan:ne}]),P=[...qe];function Ae(e){if(!e||typeof e.id!="string"||!e.id)throw new ge("SHAPE","lane: id required");if(typeof e.when!="function"||typeof e.plan!="function")throw new ge("SHAPE",`lane ${e.id}: when(route) and plan(route) required`);return Object.freeze({label:e.id,...e})}function Pt(e,{before:l=null}={}){const x=Ae(e),m=P.findIndex(h=>h.id===x.id);m>=0&&P.splice(m,1);const f=l?P.findIndex(h=>h.id===l):0;return P.splice(f<0?0:f,0,x),()=>{const h=P.indexOf(x);h>=0&&P.splice(h,1)}}function _t(){return P.map(e=>({id:e.id,label:e.label}))}function rt({messages:e=[],reach:l,target:x={},settings:m={},now:f=()=>Date.now()}={}){const h=Array.isArray(e)?e:[],c=h.findLastIndex(g=>g?.role==="user");if(c<0)return null;const k=C(h[c]),_=Number(x.window)||0,w=x.kind==="agent",b=Xe(h.slice(0,c+1)).map(g=>({id:g.id,title:g.title||g.id,docs:Number(g.docs)||0})),A=ke(h.slice(0,c+1)),W=A.filter(g=>(h[c].attachments||[]).includes(g)),K=Ze(h,{at:c}),S={at:c,question:k,window:_,small:he(_)&&!w,agent:w,kept:!1,items:[],planned:[],world:!1,research:!1,decided:"",intent:null,parts:[],kb:b,documents:A,fresh:W,material:K,why:b.length?[`a knowledge base is attached: ${b.map(g=>g.title).join(", ")}`]:[]};if((h[c].attachments||[]).some(g=>g?.kind==="prefetch"))return{...S,kept:!0,why:[...S.why,"the message already carries a look-up"]};const s=h.slice(0,c),z=C(s.findLast(g=>g?.role==="user")),O=C(s.findLast(g=>g?.role==="assistant"&&typeof g.content=="string")),U=h[c].ambientPage||(h[c].attachments||[]).find(g=>g?.kind==="page")||null,$=Le({question:k,previous:_e(h.slice(0,c+1)),previousText:z,previousAnswer:O,reach:te(l),window:_,personal:!!m.personal,lookup:m.lookup??null,tab:U,now:f()});return{...S,items:$.prefetch,planned:$.prefetch,world:$.world,research:$.research,why:[...S.why,...$.why.filter(g=>g!==$.tools.why)]}}async function Se(e={}){const l=typeof e.now=="function"?e.now:()=>Date.now(),x=l(),m=Array.isArray(e.messages)?e.messages:[],f=e.target&&typeof e.target=="object"?e.target:{},h=e.settings&&typeof e.settings=="object"?e.settings:{},c=e.models&&typeof e.models=="object"?e.models:{},k=te(e.reach),_=[...te(e.armable)],w=Ge({onEvent:e.onEvent,now:l,runId:e.runId||`turn-${x}`,threadId:e.threadId||""}),b=Number(f.window)||0,A=C(m.findLast(S=>S?.role==="user")),W=[],K=(S={})=>({status:"prepared",lane:"chat",route:null,messages:m,attachments:[],withheld:[],steps:[],tools:V({window:b,question:A,answered:N(m),reference:ke(m).length>0}),context:Z({window:b,question:A,answered:N(m)}),world:!1,research:!1,answered:N(m),answer:null,parts:[],facts:[],knowledge:null,plan:{steps:W},timing:{ms:l()-x},...S});w.runStarted({window:b});try{const S=e.resume?.checkpoint?.route||null;let s=S||rt({messages:m,reach:k,target:f,settings:h,now:l});if(!s)return w.runFinished({lane:"chat",status:"prepared"}),K();const z=Array.isArray(m[s.at]?.attachments)?m[s.at].attachments:[],O=z.find(a=>a?.kind==="page")||null,U=m[s.at]?.ambientPage,$=O||(U?.url&&(k.has("page:read_page")||k.has("read_page"))?U:null),g=(s.material||[]).filter(a=>a.attachment!==O),j={page:$?{title:$.title||"",url:$.url||""}:!1,documents:[...(s.documents||[]).map(a=>({title:a.title||"",type:a.type||"",pages:a.pages??null,fresh:(s.fresh||[]).includes(a)})),...g.map(a=>({title:a.attachment.title||a.attachment.kind,type:a.attachment.kind,material:!0,fresh:a.fresh}))]},I={documents:typeof e.documents?.open=="function",gather:typeof e.execute=="function"&&k.size>0,decide:typeof c.decide=="function"||typeof c.classify=="function",read:typeof(c.read||c.decide)=="function",write:typeof c.write=="function",rerank:typeof e.rerank=="function",knowledge:typeof e.knowledge?.search=="function"&&s.kb?.length>0};I.gather||(s={...s,items:[],planned:[]});const t={messages:m,question:A,window:b,target:f,settings:h,reach:k,route:s,can:I,attachments:[],withheld:[],steps:[],facts:[],parts:[],answer:null,found:!1,text:"",budget:{searches:0},timing:{},handoff:null},ae=a=>{for(const d of a?.steps||[])W.push({id:d.id,role:d.role||d.kind,kind:d.kind,status:d.status,ms:d.cost?.ms??null,provider:d.assigned?.provider||d.assigned?.model||null,...d.blocked?{blocked:d.blocked}:{},...d.error?{error:d.error}:{}})},$e=()=>e.pageIndex?.cache?{page:{cache:e.pageIndex.cache,budgetChars:ye({window:b,small:!!t.route?.small}),question:t.route?.intent?.request||t.question||"",query:t.route?.intent?.query||""}}:{},oe=(a={})=>({execute:e.execute,fetched:e.fetched||null,deadline:e.deadline||null,events:w,now:l,limits:e.limits?.gather||{},budget:t.budget,remember:e.remember||{},signal:e.signal||null,read:e.read||null,rerank:e.rerank||null,cards:e.cards===!0,...$e(),...a}),R={async decide(){const a=m.map(M=>({role:M.role,content:C(M),...M.pending?{pending:!0}:{}})),d=l();w.stepStarted("decide",{label:"Deciding what to look up"});const n=new AbortController,i=()=>n.abort();e.signal?.addEventListener?.("abort",i);const r=Number(e.limits?.decideMs??be[f.kind]??be.api),p=r>0&&typeof e.deadline=="function"?e.deadline(r):null,o=M=>c.decide(M,{maxTokens:160,schema:je(Fe(k,{attached:j}),{attached:j}),role:"decide",signal:n.signal}),y=typeof c.classify=="function"?Ce({messages:a,reach:k,classify:c.classify,attached:j,now:l}).catch(()=>null):Ne({messages:a,reach:k,planned:s.planned,complete:o,attached:j,now:l}).catch(()=>null),E=Symbol("late"),T=p?await Promise.race([y,p.promise.then(()=>E)]):await y;p?.cancel?.(),e.signal?.removeEventListener?.("abort",i);const u=T===E;u&&n.abort();const q=u?null:T,J=m[s.at]?.pageChosen===!0&&!!j.page&&q?.intent&&q.intent.need!=="page"?{...q.intent,need:"page",aboutPage:!0,query:"",...q.intent.need!=="none"?{also:q.intent.need,query:q.intent.query}:{}}:null,v=J?{...q,intent:J,items:B(J,{reach:k})}:q,G=l()-d;w.stepFinished("decide",{label:u?"Took too long to decide — the usual rules apply":v?v.items[0]?.label||"Nothing to look up":"No decision — the usual rules apply",status:u?"late":v?"ok":"none",ms:G});const Q={by:String(v?.model||e.decider?.name||""),need:v?.intent?.need||"",query:v?.intent?.query||"",kept:!!v?.intent?.kept,...u?{late:!0,budgetMs:r}:{}};return t.steps.push({kind:"decide",tool:"decide",input:{parts:v?.items.length||0},label:me({...Q,ms:G}),summary:me({...Q,ms:G}),decided:Q,status:v?"ok":"none",ms:G}),v},async knowledge(a,d,n){const i=e.knowledge,r=l();w.stepStarted("knowledge",{label:"Searching the knowledge base"});const p=c.read||c.decide||null,o=await Je(t.question,{search:i.search,outline:i.outline||null,read:i.read||null,complete:p?(u,q)=>p(u,{...q,role:"read"}):null,kbName:i.name||s.kb.map(u=>u.title).join(", "),docs:i.docs||[],answer:n.answer!=null?String(n.answer):"",ask:i.ask!==!1&&h.ask!==!1,now:l,late:()=>!!e.signal?.aborted,onProgress:u=>w.custom("knowledge",u)}),y=l()-r;if(o.ask&&n.answer===void 0)throw w.stepFinished("knowledge",{label:o.ask.question,status:"waiting",ms:y}),new pe({...o.ask,step:"knowledge"});o.attachment&&(t.attachments.push(o.attachment),w.custom("attachment",{attachment:o.attachment})),t.found=t.found||o.hits.length>0||o.read.some(u=>u.passages?.length||u.outline?.length);const E=o.read.reduce((u,q)=>u+(q.passages?.length||0),0),T=o.frame?.whole?"Knowledge base: the outline read":o.hits.length?`Knowledge base: ${o.hits.length} passage${o.hits.length===1?"":"s"} found, ${E} read`:"Knowledge base: nothing matched";return t.knowledge={hits:o.hits.length,read:E,rounds:o.rounds,verdict:o.verdict,how:o.how,whole:!!o.frame?.whole,cites:o.attachment?.cites||[]},t.steps.push({kind:"knowledge",tool:"kb",input:{query:t.question.slice(0,120)},label:T,status:"ok",ms:y}),w.stepFinished("knowledge",{label:T,status:"ok",ms:y}),{found:o.hits.length,read:E,rounds:o.rounds}},async document(){const a=l(),d=t.route.intent?.aboutDocument===!0,n=d?(t.route.material||[]).filter(u=>!u.fresh).map(u=>u.attachment):[],r=[...e.documents?.open?d?t.route.documents:t.route.fresh:[],...n],p=u=>n.includes(u)?et(u):e.documents.open(u);w.stepStarted("document",{label:`Reading ${r.length===1?r[0].title||"the attached document":`${r.length} attached documents`}`});let o;try{o=await Qe({question:t.route.intent?.request||t.question,documents:r,open:p,budgetChars:ye({window:b,small:t.route.small})})}catch(u){const q=l()-a;return t.steps.push({kind:"document",tool:"files",input:{documents:r.length},label:`The attached document could not be read: ${String(u?.message||u).slice(0,80)}`,status:"error",ms:q}),w.stepFinished("document",{label:"The attached document could not be read",status:"error",ms:q}),{read:0,skipped:r.length}}const y=l()-a;o.attachment&&(t.attachments.push(o.attachment),w.custom("attachment",{attachment:o.attachment}),t.found=!0),t.document={read:o.read,skipped:o.skipped,how:o.how,cites:o.attachment?.cites||[]};const E=o.read.reduce((u,q)=>u+q.pages.length,0),T=o.read.length?`Document read: ${o.read.map(u=>`${u.title} (${u.how==="whole"?`${u.of} page${u.of===1?"":"s"}`:`page${u.pages.length===1?"":"s"} ${u.pages.join(", ")} of ${u.of}`})`).join(", ")}`:`The attached document could not be read here${o.skipped[0]?.why?` — ${o.skipped[0].why}`:""}`;return t.steps.push({kind:"document",tool:"files",input:{documents:r.length,pages:E},label:T,status:o.read.length?"ok":"none",ms:y}),w.stepFinished("document",{label:T,status:o.read.length?"ok":"none",ms:y}),{read:o.read.length,pages:E,skipped:o.skipped.length,how:o.how}},async gather(a,d){let n=Array.isArray(d?.items)?d.items:t.route.items;const i=t.knowledge?.hits>0?"the knowledge base":t.document?.read?.length&&t.route.intent?.aboutDocument!==!1?"the attached document":"";if(i&&t.route.small&&!se.test(t.question)){const p=n.filter(o=>o&&!o.asked&&ot.has(o.kind));if(p.length){n=n.filter(o=>!p.includes(o));for(const o of p)t.steps.push({kind:"aside",tool:o.tool||"find",input:o.input||{},label:`${o.label||"Web search"} set aside — ${i} answered`,status:"ok",ms:0});s=t.route={...t.route,why:[...t.route.why,`${i} answered — the web is not searched for it`]}}}if(!n.length)return{found:!1,attachments:0,statuses:[],aside:!0};const r=await fe(n,oe());return t.attachments.push(...r.attachments),t.steps.push(...r.steps),t.found=t.found||r.found,{found:r.found,attachments:r.attachments.length,statuses:r.results.map(p=>p?.status||"skipped")}},async facts(a,d,n){try{return await R.readParts(a,d,n)}catch(i){return t.parts=[],t.facts=[],{...await R.gather(a,d,n),fellBack:String(i?.message||i).slice(0,120)}}},async readParts(){const a=Me(t.route.parts),d=c.read||c.decide,n=async r=>{const p=B({need:"web",query:r},{reach:k})[0];if(!p)return{results:[],status:"no-engines"};const o=await fe([p],oe({attach:!1})),y=o.results[0],E=y&&(y.status==="ok"||y.status==="cached")?ze(y.text).results:[],T=E.length?"ok":y?.why?"budget":Ue(y?.note)||(String(y?.status||"").startsWith("error")?"error":"nothing");return{results:E,status:T,step:o.steps[0]}},i=await Be({request:t.route.intent?.request||t.question,parts:a,search:n,complete:d,rerank:e.rerank||null,deadline:e.deadline||null,events:w,hooks:e.hooks||null,today:e.today||"",limits:{readConcurrency:nt({concurrency:f.concurrency,device:f.kind==="device"}),...e.limits?.facts||{}},late:()=>!!e.signal?.aborted,now:l});return t.parts=i.parts,t.facts=i.facts,t.steps.push(...i.trail),t.found=i.facts.some(r=>r?.found),{found:i.facts.filter(r=>r?.found).length,of:i.parts.length,calls:i.calls,searches:i.searches}},async check(){const a=t.facts.filter(i=>i?.found);if(t.parts.length){const i=Ke({parts:t.parts,facts:t.facts});t.answer={text:i.text,final:!0,note:i.note}}const d=N(m),n=t.found||d;return t.answered=n,t.tools=t.parts.length?{offer:!1,rounds:1,why:"every part was looked up and checked"}:t.route.agent?{offer:!0,rounds:null,why:"an agent keeps its own tools"}:V({window:b,question:A,answered:n,decided:t.route.decided,reference:de()}),t.context=Z({window:t.route.agent?0:b,question:A,answered:n}),{answered:n,offer:t.tools.offer,final:!!t.answer?.final}},async ask(a,d,n){if(n.answer===void 0)throw new pe(a.ask||{question:a.title});return n.answer},async write(){const a=`${e.runId||"turn"}:answer`;w.textStart(a);let d="";if(t.answer?.final)d=t.answer.text,w.textContent(a,d);else{const n=await c.write({messages:X(),tools:t.tools,context:t.context,lane:t.lane},{onToken:r=>w.textContent(a,r)}),i=it({messages:X(),window:b},{answer:n});d=i.text,t.answer={text:d,final:!1,note:i.note},i.text!==String(n||"")&&w.custom("answer",{text:d})}return w.textEnd(a),t.text=d,d}},Y=e.runners&&typeof e.runners=="object"?e.runners:{},Ee=a=>(d,n,i)=>typeof Y[a]=="function"?Y[a](d,n,{...i,turn:t,defaults:R}):R[a](d,n,i),re=Ye({runners:{"*":(a,d,n)=>{const i=a.role||a.kind;if(!R[i]&&typeof Y[i]!="function")throw new Error(`no runner for stage ${i}`);return Ee(i)(a,d,n)}},hooks:e.hooks||null,now:l}),ie={rule:()=>({provider:"harness"}),capability:()=>null,model:a=>a.role==="write"?I.write?{model:"write"}:null:a.role==="decide"||a.kind==="decide"?I.decide?{model:"decide"}:null:{model:"read"}},de=()=>(s.documents||[]).length>0&&!(t.document?.read?.length>0),X=()=>t.attachments.length||t.withheld.length?m.map((a,d)=>d===s.at?{...a,attachments:[...(a.attachments||[]).filter(n=>!t.withheld.includes(n)),...t.attachments]}:a):m;if(!S&&!s.kept&&I.gather&&I.decide&&!s.agent&&Oe({window:b,local:!!f.local,chosen:!!f.chosen,allowed:h.lookups!==!1,messages:m.map(a=>({role:a.role,content:C(a)})),reach:k,planned:s.planned,attached:j})){const a=l(),d=await re.run(we({id:"route",origin:"chat",steps:[{id:"decide",kind:"decide",role:"decide",title:"Decide what to look up"}]},ie),{});ae(d),t.timing.decideMs=l()-a;let n=d.outputs.decide;if(n?.intent?.aboutDocument===!0&&g.length&&!g.some(r=>r.fresh)&&!(s.documents||[]).length&&!tt(g.map(r=>r.attachment),Ve(A))){const{also:r,...p}=n.intent,o={...p,need:r||"none",query:r?n.intent.query:"",aboutDocument:!1};n={...n,intent:o,items:B(o,{reach:k})},s={...s,why:[...s.why,"the question names nothing the attached material holds — not about it"]}}if(n?.intent&&(s={...s,items:n.items,decided:n.intent.need,intent:n.intent,parts:n.intent.need==="web"&&Array.isArray(n.intent.parts)?n.intent.parts:[],world:H(n.items),why:[...s.why,n.intent.kept?"the decider found nothing to add — the rules' plan stands":`the decider asked for ${n.intent.need}`]}),n?.intent&&n.intent.need==="page"&&O&&!n.items.length&&(t.found=!0,s={...s,why:[...s.why,"the open page is what the question is about — answered by it"]}),n?.intent?.aboutDocument===!0&&(s.material||[]).some(r=>r.fresh&&r.attachment!==O)&&(t.found=!0,s={...s,why:[...s.why,"the material attached with this message is what the question is about — answered by it"]}),n?.intent&&n.intent.need!=="page"&&n.intent.aboutPage===!1){t.withheld=z.filter(r=>r?.auto&&r.kind==="page"),!O&&$&&t.withheld.push({kind:"page",title:$.title||"",url:$.url||"",ambient:!0});for(const r of t.withheld)t.steps.push({kind:"aside",tool:"page",input:{title:r.title||"",url:r.url||""},label:"This page set aside — the question is not about it",status:"ok",ms:0});t.withheld.length&&(s={...s,why:[...s.why,"the open page is not what the question is about — set aside"]})}if(n?.intent?.aboutDocument===!0&&n.intent.also){const p=(n.intent.also==="own_data"?xe.test(A):se.test(A))?B({need:n.intent.also,query:n.intent.query},{reach:k}).map(y=>({...y,asked:!0})):[],o=n.intent.also==="web"?"Web search":n.intent.also==="own_data"?"Your own records":n.intent.also;p.length||t.steps.push({kind:"aside",tool:"find",input:{query:n.intent.query||""},label:`${o} set aside — the attached document is what the question is about`,status:"ok",ms:0}),s={...s,items:p,world:H(p),why:[...s.why,p.length?`${o.toLowerCase()} asked for by name — searched beside the document`:"the attached document is what the question is about — nothing else is searched for it"]}}if(n?.intent?.aboutPage===!0&&n.intent.also){const p=(n.intent.also==="own_data"?xe.test(A):se.test(A))?B({need:n.intent.also,query:n.intent.query},{reach:k}):[],o=n.intent.also==="web"?"Web search":n.intent.also==="own_data"?"Your own records":n.intent.also;p.length||t.steps.push({kind:"aside",tool:"find",input:{query:n.intent.query||""},label:`${o} set aside — the page open on the screen is what the question is about`,status:"ok",ms:0}),s={...s,items:[...s.items.filter(y=>y?.kind==="page"),...p],world:H(p),why:[...s.why,p.length?`${o.toLowerCase()} asked for by name — searched beside the page`:"the open page is what the question is about — nothing else is searched for it"]}}const i=n?.intent?.act===!0&&!ee(k)?_.filter(r=>ee([r])):[];i.length?(t.arm=i,t.tools={offer:!0,rounds:he(b)?Ie:null,why:`asked to act — ${i.join(", ")} offered`},s={...s,items:[],planned:[],why:[...s.why,`asked to act on the computer — ${i.join(", ")} offered for this turn`]}):n?.intent?.act===!0&&!ee(k)&&(t.handoff={kind:"agent",why:"act",request:n.intent.request||A},t.answer={text:We,final:!0,note:""},s={...s,items:[],planned:[],why:[...s.why,"asked to act on the computer, and nothing here can — offered to an agent that can"]})}!S&&h.home&&s.items.length&&(s={...s,items:Pe(s.items,h.home)}),s={...s,settings:{pipeline:h.pipeline===!0},can:I,world:s.world||H(s.items)},t.route=s;const ce=Array.isArray(e.lanes)&&e.lanes.length?e.lanes.map(Ae):P,D=S&&ce.find(a=>a.id===e.resume.checkpoint.lane)||ce.find(a=>{try{return!!a.when(s)}catch{return!1}})||qe.at(-1);t.lane=D.id,w.stateDelta([{op:"add",path:"/lane",value:D.id},{op:"add",path:"/need",value:s.decided||(s.items[0]?Re(s.items[0])?"web":s.items[0].kind:"none")}]),w.stepStarted("lane",{lane:D.id});const De=l(),Te=D.plan(s).filter(a=>a.role!=="write"||I.write),F=await re.run(we({id:`turn-${D.id}`,origin:"chat",flow:!0,steps:Te},ie),{...e.resume?{resume:{outputs:e.resume.checkpoint?.outputs||{},answers:e.resume.answers||{}}}:{}});ae(F),t.timing.laneMs=l()-De,w.stepFinished("lane",{lane:D.id,status:F.status});const ve={lane:D.id,need:s.decided||"",decided:s.decided,request:s.intent?.request||"",parts:s.parts,world:s.world,kept:s.kept,why:s.why},le={lane:D.id,route:ve,messages:X(),attachments:t.attachments,withheld:t.withheld.map(a=>({id:a.id??null,kind:a.kind,title:a.title||"",url:a.url||"",why:"the question is not about it",...a.ambient?{ambient:!0}:{}})),steps:t.steps,tools:t.tools||V({window:b,question:A,answered:t.found||N(m),decided:s.decided,reference:de()}),context:t.context||Z({window:b,question:A,answered:t.found||N(m)}),world:s.world,research:!!s.research&&!s.world,answered:t.answered??(t.found||N(m)),answer:t.answer,parts:t.parts,facts:t.facts,knowledge:t.knowledge||null,document:t.document||null,handoff:t.handoff||null,arm:t.arm||[],plan:{steps:W},timing:{...t.timing,ms:l()-x},window:b};if(F.status==="waiting"){const{settings:a,can:d,...n}=s,i={...le,status:"waiting",ask:F.waiting[0]?.ask||null,checkpoint:{lane:D.id,route:n,outputs:F.checkpoint.outputs,waiting:F.waiting.map(r=>r.stepId)}};return w.runFinished({lane:D.id,status:"waiting"}),i}const ue=t.answer&&(t.answer.final||I.write)?"answered":"prepared";return w.runFinished({lane:D.id,status:ue,found:t.facts.filter(a=>a?.found).length,parts:t.parts.length}),{...le,status:ue}}catch(S){const s=String(S?.message||S);return w.runError(s),K({status:"failed",error:s})}}async function Ot(e={},{askPerson:l=null,maxAsks:x=2,fallback:m=null}={}){let f=await Se(e);for(let h=0;h<x&&f.status==="waiting"&&f.ask;h+=1){let c=null;try{c=typeof l=="function"?await l(f.ask):null}catch{c=null}const k=Array.isArray(f.ask.options)?f.ask.options:[],_=c!=null&&String(c).trim()?String(c).trim():m??(k.length?k[k.length-1]:""),w=f.ask.step||f.checkpoint?.waiting?.[0]||"ask";f=await Se({...e,resume:{checkpoint:f.checkpoint,answers:{...e.resume?.answers||{},[w]:_}}})}return f}function it(e={},{answer:l="",shims:x=null}={}){if(e.answer?.final)return{text:e.answer.text,note:e.answer.note||""};const m=st(l);if(m.fired)try{x?.fire?.("answer.wrapper-echo",{lines:m.fired})}catch{}const f=m.text;if(!f.trim())return{text:f,note:""};const h=at(f,e.messages||[]).echoed;if(h)try{x?.fire?.("answer.context-echo",{})}catch{}const c=He({answer:f,messages:e.messages||[],window:e.window??0});return{text:c?`${f}
|
|
3
3
|
|
|
4
|
-
${c}`:
|
|
4
|
+
${c}`:f,note:c,...h?{echoed:!0}:{}}}export{We as ACT_HANDOFF_TEXT,be as DECIDE_BUDGET_MS,Lt as TURN_STAGES,Pt as defineLane,it as finishTurn,_t as listLanes,rt as routeByRule,Se as runTurnPipeline,Ot as runTurnPipelineAsking};
|
package/voice-room.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
const
|
|
2
|
-
`);o.length>
|
|
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 c=Object.freeze(["me","room","anyone"]),u="me",d="You",p=6,i=1200;function g(t={}){const e=t?.ui?.voice||{};return c.includes(e.listenTo)?e.listenTo:e.onlyMe===!1?"anyone":u}const O=t=>t==="me"||t==="room",w=/^(?:(?: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,m=/\b(?:hey\s+)?(?:chap|chad)\b/i;function x(t){const e=String(t||"").trim();return e?/\?\s*$/.test(e)||w.test(e)||m.test(e):!1}const f='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:".',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 S({text:t="",from:e=null,room:r=[]}={}){const h=String(t||"").trim(),a=String(e?.label||d),s=e?.guest===!0;let o=(Array.isArray(r)?r:[]).slice(-p).map(n=>`${n?.label||"Someone"} said: "${String(n?.text||"").trim()}"`).filter(n=>!/: ""$/.test(n)).join(`
|
|
2
|
+
`);o.length>i&&(o=o.slice(-i));const l=s?`${a}, a guest in the room, asked this.`:"The person whose Chap you are asked this.";return{text:h,speaker:{label:a,guest:s},guest:s,hint:[f,l,...s?[y]:[],...o?[`Said in the room just before:
|
|
3
|
+
${o}`]:[]].join(`
|
|
4
|
+
`)}}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{u as DEFAULT_LISTEN_TO,y as GUEST_HINT,c as LISTEN_TO,p as ROOM_CONTEXT,f as ROOM_HINT,d as ROOM_OWNER,x as asksChap,b as guestPrefs,O as judgesOwner,g as listenToOf,S as roomMessage};
|