@chatpanel/events 0.435.0 → 0.447.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/tool-need.js CHANGED
@@ -1,3 +1,3 @@
1
- import{offeredSearch as O}from"./prefetch.js";import{signalsFrom as _}from"./router.js";const j=new Set(["hi","hii","hiya","hey","heya","hello","helo","yo","sup","howdy","greetings","good","morning","afternoon","evening","night","day","thanks","thank","thankyou","thx","tnx","ty","cheers","appreciated","ok","okay","k","kk","got","sounds","perfect","great","cool","nice","awesome","lol","haha","hah","hehe","nvm","yep","yeah","yes","no","nope","sure","bye","goodbye","later","ya","cya","ciao","welcome","worries","problem","np","please","there","again","all","everyone","team","friend","mate","buddy","you","u","so","much","very","well","and","a","the"]),q=6;function L(e){const o=String(e||"").toLowerCase().replace(/[^\p{L}\s']/gu," ").split(/\s+/).filter(Boolean);return!o.length||o.length>q?!1:o.every(a=>j.has(a))}function P({request:e=null,signals:o=null,attachments:a=[],explicit:c=!1}={}){if(c)return{tools:!0,why:"the turn asked for tools"};if((a||[]).some(s=>s&&!s.auto))return{tools:!0,why:"the turn carries an attachment"};const r=String(e?.text??(e?.messages||[]).map(s=>s?.content||"").join(`
2
- `));return L(r)?e?.previousAnswer&&O(e.previousAnswer)?{tools:!0,why:"accepting the offer to search"}:(o||_(e||{})).smalltalk?{tools:!1,why:"a greeting — nothing to look up"}:{tools:!0,why:"the request may need something fetched"}:{tools:!0,why:"the request may need something fetched"}}const G=Object.freeze([["web",/\b(search|google|look ?up|latest|current|recent|today|this (week|month|year)|news|price|prices|pricing|cost of|quote|stock|market|website|url|online|web|docs?umentation|release notes|changelog|versions?)\b/i],["history",/\b(our (meeting|call|notes?|chats?|conversation)|what (did|was) (we|i)|we (decided|agreed|discussed|said)|in (my|our) (notes?|meetings?|history|chats?)|past (chats?|meetings?|notes?)|earlier (meeting|conversation|chat|note)|transcript|standup|retro)\b/i],["data",/\b(attached|attachment|this (page|document|file|pdf|spreadsheet|sheet)|the (document|file|pdf|spreadsheet) (above|provided|attached))\b/i]]);function U(e,{held:o=null}={}){const a=String(e||"");if(!a.trim())return[];const c=G.filter(([,t])=>t.test(a)).map(([t])=>t);if(!o)return c;const r=new Set((Array.isArray(o)?o:[]).map(t=>String(t).toLowerCase()));return c.filter(t=>r.has(t)||t==="history"&&r.has("data"))}const u=Object.freeze(["page","data","mcp","memory","note","team","sideline","skills","widgets","recipes"]),k=Object.freeze(["data","mcp","memory"]),f="page_read",v=/\b(this|the|current|open|active|that|my) (page|tab|site|website|article|post|thread|document|doc|file|pdf|sheet|spreadsheet|form|canvas|board|diagram|screen|window|video|table|cell|button|field|link|image)\b|\bon (the|this) (page|screen|tab)\b|\bhere\b|\bthis\b(?!\s+(morning|afternoon|evening|week|weekend|month|year|time|is (a|the|my))\b)|\bthese\b|\bthose\b/i,S=/\b(click|tap|press|type|fill|enter|select|scroll|drag|draw|paint|sketch|navigate|go to|open|close|submit|upload|download|play|pause|screenshot|inspect|read (the|this)|zoom|highlight|copy|paste|log ?in|sign ?in|sign ?up|checkout|add to cart|search (on|in) (the|this)|watch|browse)\b/i,A=/\b(build|make|create|write|generate|draft|code|design|implement|prototype)\b[^.?!]{0,40}\b(app|widget|tool|timer|calculator|tracker|checklist|game|dashboard|form|page|site|script|component|converter|counter|scoreboard|clock|note|dice)\b|\b(widget|app)\b/i,z=/\b(run|use|ask|start|save|create|make|set ?up|open|launch|kick ?off|assign|delegate)\b[^.?!]{0,30}\b(team|teams|agent|agents|skill|skills|recipe|recipes|sideline|project)\b|\b(the|my|our|this|that)\s+(\w+[\s-]+)?(team|agent|skill|recipe|sideline|project)\b|\bask (the|our|my) \w+ (to|for)\b|\b(executive|breakout|workflow)\b|remember this|save (this|that) as|^\s*\//i,x=/\b(summar\w*|analy[sz](?:e|es|ed|ing|is)|review|edit|rewrite|fix|refactor|debug|translate|convert|extract|compare|explain (this|that|the)|proofread|format|organi[sz]e|plan)\b/i,F=300;function $({request:e=null,signals:o=null,attachments:a=[],explicit:c=!1,stable:r=!1,ambient:t=null}={}){const s=R({request:e,signals:o,attachments:a,explicit:c,stable:r,ambient:t});return N(s,e,t)}function N(e,o,a){const c=String(o?.previousRequest||"").trim();if(!e.tools||e.tier==="full"||!c)return e;const r=R({request:{text:c},ambient:a});if(!r.tools||r.tier==="light"||r.tier==="none")return e;const t=new Set([...e.groups,...r.groups]);return t.has("page")&&t.delete(f),u.every(s=>t.has(s))?{tools:!0,tier:"full",groups:new Set(u),why:`${e.why}; carried from the request before: ${r.why}`}:{tools:!0,tier:"task",groups:t,why:`${e.why}; carried from the request before: ${r.why}`}}function R({request:e=null,signals:o=null,attachments:a=[],explicit:c=!1,stable:r=!1,ambient:t=null}={}){const s=i=>({tools:!0,tier:"full",groups:new Set(u),why:i});if(r)return s("a warm process keeps one tool set");const d=P({request:e,signals:o,attachments:a,explicit:c});if(!d.tools)return{tools:!1,tier:"none",groups:new Set,why:d.why};if(c)return s(d.why);const l=String(e?.text??(e?.messages||[]).map(i=>i?.content||"").join(`
3
- `)),m=i=>{const y=s(i);return A.test(l)||y.groups.delete("widgets"),y};if((a||[]).some(i=>i&&!i.auto))return m("the turn carries an attachment");if(!l.trim())return s("no text to read");if(l.length>F||/```/.test(l))return m("a long or code-bearing request");const b=v.test(l)||S.test(l)||x.test(l),p=z.test(l),w=A.test(l),E=x.test(l),g=!!t?.page;if(!b&&!p&&!w){const i=new Set(k);return g&&i.add(f),{tools:!0,tier:"light",groups:i,why:g?"a lookup, asked from a readable tab — the user's data, the web, and a reader for the tab":"a lookup — the user's data and the web are enough"}}const n=new Set(k),h=[];return b&&(n.add("page"),n.add("note"),h.push(S.test(l)?"the request asks to act":v.test(l)?"the request refers to the page or to something in view":"the request is work, not a lookup")),(E||p)&&n.add("skills"),p&&(n.add("team"),n.add("sideline"),n.add("recipes"),n.add("note"),h.push("the request names a team, skill, recipe or command")),w&&(n.add("widgets"),n.add("note"),h.push("the request asks to make something")),g&&!n.has("page")&&n.add(f),u.every(i=>n.has(i))?s(h.join("; ")):{tools:!0,tier:"task",groups:n,why:h.join("; ")}}export{$ as equipmentFor,U as grantsNeededFor,L as isPleasantry,P as toolNeedFor};
1
+ import{offeredSearch as E}from"./prefetch.js";import{signalsFrom as O}from"./router.js";const P=new Set(["hi","hii","hiya","hey","heya","hello","helo","yo","sup","howdy","greetings","good","morning","afternoon","evening","night","day","thanks","thank","thankyou","thx","tnx","ty","cheers","appreciated","ok","okay","k","kk","got","sounds","perfect","great","cool","nice","awesome","lol","haha","hah","hehe","nvm","yep","yeah","yes","no","nope","sure","bye","goodbye","later","ya","cya","ciao","welcome","worries","problem","np","please","there","again","all","everyone","team","friend","mate","buddy","you","u","so","much","very","well","and","a","the"]),_=6;function q(e){const r=String(e||"").toLowerCase().replace(/[^\p{L}\s']/gu," ").split(/\s+/).filter(Boolean);return!r.length||r.length>_?!1:r.every(s=>P.has(s))}function L({request:e=null,signals:r=null,attachments:s=[],explicit:n=!1}={}){if(n)return{tools:!0,why:"the turn asked for tools"};if((s||[]).some(a=>a&&!a.auto))return{tools:!0,why:"the turn carries an attachment"};const o=String(e?.text??(e?.messages||[]).map(a=>a?.content||"").join(`
2
+ `));return q(o)?e?.previousAnswer&&E(e.previousAnswer)?{tools:!0,why:"accepting the offer to search"}:(r||O(e||{})).smalltalk?{tools:!1,why:"a greeting — nothing to look up"}:{tools:!0,why:"the request may need something fetched"}:{tools:!0,why:"the request may need something fetched"}}const G=Object.freeze([["web",/\b(search|google|look ?up|latest|current|recent|today|this (week|month|year)|news|price|prices|pricing|cost of|quote|stock|market|website|url|online|web|docs?umentation|release notes|changelog|versions?)\b/i],["history",/\b(our (meeting|call|notes?|chats?|conversation)|what (did|was) (we|i)|we (decided|agreed|discussed|said)|in (my|our) (notes?|meetings?|history|chats?)|past (chats?|meetings?|notes?)|earlier (meeting|conversation|chat|note)|transcript|standup|retro)\b/i],["data",/\b(attached|attachment|this (page|document|file|pdf|spreadsheet|sheet)|the (document|file|pdf|spreadsheet) (above|provided|attached))\b/i]]);function U(e,{held:r=null}={}){const s=String(e||"");if(!s.trim())return[];const n=G.filter(([,t])=>t.test(s)).map(([t])=>t);if(!r)return n;const o=new Set((Array.isArray(r)?r:[]).map(t=>String(t).toLowerCase()));return n.filter(t=>o.has(t)||t==="history"&&o.has("data"))}const d=Object.freeze(["page","data","mcp","memory","note","team","sideline","skills","widgets","recipes"]),k=Object.freeze(["data","mcp","memory"]),f="page_read",v=/\b(this|the|current|open|active|that|my) (page|tab|site|website|article|post|thread|document|doc|file|pdf|sheet|spreadsheet|form|canvas|board|diagram|screen|window|video|table|cell|button|field|link|image)\b|\bon (the|this) (page|screen|tab)\b|\bhere\b|\bthis\b(?!\s+(morning|afternoon|evening|week|weekend|month|year|time|is (a|the|my))\b)|\bthese\b|\bthose\b/i,S=/\b(click|tap|press|type|fill|enter|select|scroll|drag|draw|paint|sketch|navigate|go to|open|close|submit|upload|download|play|pause|screenshot|inspect|read (the|this)|zoom|highlight|copy|paste|log ?in|sign ?in|sign ?up|checkout|add to cart|search (on|in) (the|this)|watch|browse)\b/i,A=/\b(build|make|create|write|generate|draft|code|design|implement|prototype)\b[^.?!]{0,40}\b(app|widget|tool|timer|calculator|tracker|checklist|game|dashboard|form|page|site|script|component|converter|counter|scoreboard|clock|note|dice)\b|\b(widget|app)\b/i,z=/\b(run|use|ask|start|save|create|make|set ?up|open|launch|kick ?off|assign|delegate)\b[^.?!]{0,30}\b(team|teams|agent|agents|skill|skills|recipe|recipes|sideline|project)\b|\b(the|my|our|this|that)\s+(\w+[\s-]+)?(team|agent|skill|recipe|sideline|project)\b|\bask (the|our|my) \w+ (to|for)\b|\b(executive|breakout|workflow)\b|remember this|save (this|that) as|^\s*\//i,x=/\b(summar\w*|analy[sz](?:e|es|ed|ing|is)|review|edit|rewrite|fix|refactor|debug|translate|convert|extract|compare|explain (this|that|the)|proofread|format|organi[sz]e|plan)\b/i,F=300;function D({request:e=null,signals:r=null,attachments:s=[],explicit:n=!1,stable:o=!1,ambient:t=null,pinned:a=[]}={}){const h=R({request:e,signals:r,attachments:s,explicit:n,stable:o,ambient:t});return $(N(h,e,t),a)}function $(e,r){const s=(Array.isArray(r)?r:[]).filter(o=>typeof o=="string"&&o);if(!s.length||e.tier==="full")return e;const n=new Set([...e.tools?e.groups:[],...s]);return{tools:!0,tier:e.tools&&e.tier!=="none"?e.tier==="light"?"task":e.tier:"task",groups:n,why:`${e.why}; picked: ${s.join(", ")}`}}function N(e,r,s){const n=String(r?.previousRequest||"").trim();if(!e.tools||e.tier==="full"||!n)return e;const o=R({request:{text:n},ambient:s});if(!o.tools||o.tier==="light"||o.tier==="none")return e;const t=new Set([...e.groups,...o.groups]);return t.has("page")&&t.delete(f),d.every(a=>t.has(a))?{tools:!0,tier:"full",groups:new Set(d),why:`${e.why}; carried from the request before: ${o.why}`}:{tools:!0,tier:"task",groups:t,why:`${e.why}; carried from the request before: ${o.why}`}}function R({request:e=null,signals:r=null,attachments:s=[],explicit:n=!1,stable:o=!1,ambient:t=null}={}){const a=l=>({tools:!0,tier:"full",groups:new Set(d),why:l});if(o)return a("a warm process keeps one tool set");const h=L({request:e,signals:r,attachments:s,explicit:n});if(!h.tools)return{tools:!1,tier:"none",groups:new Set,why:h.why};if(n)return a(h.why);const c=String(e?.text??(e?.messages||[]).map(l=>l?.content||"").join(`
3
+ `)),m=l=>{const y=a(l);return A.test(c)||y.groups.delete("widgets"),y};if((s||[]).some(l=>l&&!l.auto))return m("the turn carries an attachment");if(!c.trim())return a("no text to read");if(c.length>F||/```/.test(c))return m("a long or code-bearing request");const b=v.test(c)||S.test(c)||x.test(c),p=z.test(c),w=A.test(c),j=x.test(c),g=!!t?.page;if(!b&&!p&&!w){const l=new Set(k);return g&&l.add(f),{tools:!0,tier:"light",groups:l,why:g?"a lookup, asked from a readable tab — the user's data, the web, and a reader for the tab":"a lookup — the user's data and the web are enough"}}const i=new Set(k),u=[];return b&&(i.add("page"),i.add("note"),u.push(S.test(c)?"the request asks to act":v.test(c)?"the request refers to the page or to something in view":"the request is work, not a lookup")),(j||p)&&i.add("skills"),p&&(i.add("team"),i.add("sideline"),i.add("recipes"),i.add("note"),u.push("the request names a team, skill, recipe or command")),w&&(i.add("widgets"),i.add("note"),u.push("the request asks to make something")),g&&!i.has("page")&&i.add(f),d.every(l=>i.has(l))?a(u.join("; ")):{tools:!0,tier:"task",groups:i,why:u.join("; ")}}export{D as equipmentFor,U as grantsNeededFor,q as isPleasantry,L as toolNeedFor};
package/toolset.js CHANGED
@@ -1,3 +1,3 @@
1
- const T=/^mcp[_-]/i;function N(A,{mcpSystem:f=""}={}){const i=(A||[]).filter(e=>e&&e.specs?.length);if(!i.length)return;const r=[],u=new Map,g=new Set,h=new Map,y=new Set,m=[],o=new Map,M=new Map,S=new Set,l=[];for(const e of i){if(typeof e.hint=="function"&&l.push(e.hint),Array.isArray(e.hinters))for(const t of e.hinters)typeof t=="function"&&l.push(t);const s=e.remote===!0;if(e.traits instanceof Map)for(const[t,n]of e.traits)h.has(t)||h.set(t,n);const a=e.hiddenVia instanceof Map;if(a){const t=new Map((Array.isArray(e.reach)?e.reach:[]).filter(n=>n?.name).map(n=>[n.name,n]));for(const[n,w]of e.hiddenVia)o.has(n)||!e.specs.some(R=>R?.name===w)||(o.set(n,w),t.has(n)&&m.push(t.get(n)))}else if(Array.isArray(e.reach)&&e.specs.length===1)for(const t of e.reach)t?.name&&!o.has(t.name)&&(o.set(t.name,e.specs[0].name),m.push(t));const c=e.remoteTools instanceof Set?e.remoteTools:null,E=e.serialTools instanceof Set?e.serialTools:null;for(const t of e.specs){if(u.has(t.name))continue;r.push(t),u.set(t.name,e.execute);const n=a&&e.residents instanceof Map?e.residents.get(t.name):e.system;n&&M.set(t.name,String(n)),(s||c?.has(t.name)||T.test(String(t.name||"")))&&g.add(t.name),(e.serial===!0||E?.has(t.name))&&y.add(t.name),(e.quiet===!0||e.quietTools instanceof Set&&e.quietTools.has(t.name))&&S.add(t.name)}}if(!r.length)return;const p=r.some(e=>T.test(String(e?.name||"")))?String((typeof f=="function"?f():f)||""):"",q=[p,...i.filter(e=>e.quiet!==!0).map(e=>e.system)].map(e=>String(e||"").trim()).filter(Boolean).join(`
1
+ const A=/^mcp[_-]/i;function V(g,{mcpSystem:h=""}={}){const i=(g||[]).filter(e=>e&&e.specs?.length);if(!i.length)return;const r=[],u=new Map,y=new Set,p=new Map,M=new Set,l=[],o=new Map,S=new Map,w=new Set,a=[];for(const e of g||[])!e||e.specs?.length||typeof e.hint=="function"&&a.push(e.hint);for(const e of i){if(typeof e.hint=="function"&&a.push(e.hint),Array.isArray(e.hinters))for(const t of e.hinters)typeof t=="function"&&a.push(t);const s=e.remote===!0;if(e.traits instanceof Map)for(const[t,n]of e.traits)p.has(t)||p.set(t,n);const c=e.hiddenVia instanceof Map;if(c){const t=new Map((Array.isArray(e.reach)?e.reach:[]).filter(n=>n?.name).map(n=>[n.name,n]));for(const[n,T]of e.hiddenVia)o.has(n)||!e.specs.some(R=>R?.name===T)||(o.set(n,T),t.has(n)&&l.push(t.get(n)))}else if(Array.isArray(e.reach)&&e.specs.length===1)for(const t of e.reach)t?.name&&!o.has(t.name)&&(o.set(t.name,e.specs[0].name),l.push(t));const f=e.remoteTools instanceof Set?e.remoteTools:null,E=e.serialTools instanceof Set?e.serialTools:null;for(const t of e.specs){if(u.has(t.name))continue;r.push(t),u.set(t.name,e.execute);const n=c&&e.residents instanceof Map?e.residents.get(t.name):e.system;n&&S.set(t.name,String(n)),(s||f?.has(t.name)||A.test(String(t.name||"")))&&y.add(t.name),(e.serial===!0||E?.has(t.name))&&M.add(t.name),(e.quiet===!0||e.quietTools instanceof Set&&e.quietTools.has(t.name))&&w.add(t.name)}}if(!r.length)return;const m=r.some(e=>A.test(String(e?.name||"")))?String((typeof h=="function"?h():h)||""):"",q=[m,...i.filter(e=>e.quiet!==!0).map(e=>e.system)].map(e=>String(e||"").trim()).filter(Boolean).join(`
2
2
 
3
- `)||void 0,d={};p.trim()&&(d.mcp=Math.round(p.length/4));for(const e of i){if(e.quiet===!0)continue;const s=Math.round(String(e.system||"").trim().length/4);s&&(d[e.id||e.specs[0]?.name||"group"]=s)}return{specs:r,system:q,systemParts:d,remoteTools:g,traits:h,serialTools:y,reach:m,hiddenVia:o,residents:M,quietTools:S,hinters:l,async execute(e,s,a={}){const c=u.get(e);return c?c(e,s,a):JSON.stringify({error:`Unknown tool: ${e}`})}}}export{N as buildToolset};
3
+ `)||void 0,d={};m.trim()&&(d.mcp=Math.round(m.length/4));for(const e of i){if(e.quiet===!0)continue;const s=Math.round(String(e.system||"").trim().length/4);s&&(d[e.id||e.specs[0]?.name||"group"]=s)}return{specs:r,system:q,systemParts:d,remoteTools:y,traits:p,serialTools:M,reach:l,hiddenVia:o,residents:S,quietTools:w,hinters:a,async execute(e,s,c={}){const f=u.get(e);return f?f(e,s,c):JSON.stringify({error:`Unknown tool: ${e}`})}}}export{V as buildToolset};
package/turn-loop.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import{runToolRound as pt}from"./tool-round.js";import{toolTraits as dt,effectiveToolName as W,parallelEligible as ft}from"./tool-traits.js";import{createToolLoopGuard as tt,roundSignature as mt,toolMadeProgress as ht,blockedToolResult as gt}from"./tool-loop-guard.js";import{createAdaptiveToolPolicy as et,adaptiveToolRetryHint as yt,resultText as P}from"./adaptive-tool-policy.js";import{toolStatus as kt}from"./tool-hints.js";import{isSmallWindow as Tt,SMALL_WINDOW_ROUNDS as nt}from"./context-window.js";import{createShimLog as ot}from"./shim.js";import{EXHAUSTED_NOTE as xt}from"./model-view.js";import{HUB_TOOL_NAME as _t}from"./tool-hub.js";const q=60,wt=6,X=4e3,Y=`
2
2
 
3
- `,z=Object.freeze(["The tool budget for this turn is spent. Do not call tools again; write your answer now with what you have, including your findings.","No more tool calls will be answered. Reply with your answer as plain text, now — a partial answer beats none.","FINAL: any further tool call ends this turn with no answer. Write what you have found, as text, in this message."]),St="You have repeated the same tool call several times. Do not call tools again; answer now with what you have.",rt=/\[External MCP[^\n]*\n|⟦\/?EXTERNAL_MCP_OUTPUT⟧/g,bt=t=>/^\s*(?:error\b|\{"error")|"error"\s*:/i.test(String(t||"").replace(rt,""));function qt(t=[],{finish:o="",window:e=0,thinking:n=!1}={}){if(/^(length|max_tokens|max_output_tokens)$/i.test(String(o||"")))return`⚠ The model ran out of room: its${Number(e)>0?` ${Math.round(Number(e)/1024)}k-token`:""} window filled ${n?"while it was still thinking":"before it wrote an answer"}. A longer context (Settings › Runtime › the engine's Profile), less thinking (its Thinking setting), or a new chat gives it room.`;const r=[...Array.isArray(t)?t:[]].reverse().find(x=>/^error/i.test(String(x?.status||""))||bt(x?.result));if(!r)return"⚠ The model ended this turn without an answer. Try again, or pick another model.";const a=r.input?.action||r.action||r.tool||r.name||"an action",c=(/^error/i.test(String(r.status||""))?String(r.status).replace(/^error:\s*/i,""):String(r.result||"")).replace(rt,"").replace(/\s+/g," ").trim().slice(0,200);return`⚠ No answer: the turn ended after \`${a}\` failed${c?` — ${c}`:""}. Try again, or ask without it.`}function Xt({tools:t,agent:o,settings:e,fallback:n=q}={}){if(!t)return 1;const a=[Math.max(1,Number(n)||q)],h=Number(o?.maxRequestsPerTurn)||0;h>0&&a.push(h);const c=Number(e?.ui?.maxToolRoundsPerTurn??e?.maxToolRoundsPerTurn)||0;return c>0&&a.push(c),Tt(o?.window||o?.contextLength||o?.contextWindow)&&a.push(nt),Math.max(1,Math.min(...a))}function B(t){if(!t)return{};if(typeof t=="object")return t;try{return JSON.parse(t)}catch{return{}}}const st=t=>typeof t.arguments=="string"?t.arguments:JSON.stringify(t.arguments??t.input??{});function Nt(t){const o=String(P(t)||"");return o.length>X?`${o.slice(0,X)}…`:o}function Rt(t){const o=String(P(t)||"").length;if(o<=X)return"";const e=n=>n.toLocaleString("en-US");return`Showing the first ${e(X)} of ${e(o)} characters — the model received all of them.`}function At(t,o){const e=W(t,o),n=o&&typeof o=="object"&&o.args&&typeof o.args=="object"?o.args:o||{},r=["query","id","tool","location","ref"].find(a=>typeof n[a]=="string"&&n[a]);return r?`${e} "${String(n[r]).slice(0,80)}"`:e}function zt(t,o){const e=Array.isArray(t)?[...t]:[],n=String(o||"").trim();if(!n)return e;const r=e.findIndex(a=>a?.role==="system"&&typeof a.content=="string");return r>=0?(e[r]={...e[r],content:`${e[r].content}
3
+ `,z=Object.freeze(["The tool budget for this turn is spent. Do not call tools again; write your answer now with what you have, including your findings.","No more tool calls will be answered. Reply with your answer as plain text, now — a partial answer beats none.","FINAL: any further tool call ends this turn with no answer. Write what you have found, as text, in this message."]),St="You have repeated the same tool call several times. Do not call tools again; answer now with what you have.",rt=/\[External MCP[^\n]*\n|⟦\/?EXTERNAL_MCP_OUTPUT⟧/g,bt=t=>/^\s*(?:error\b|\{"error")|"error"\s*:/i.test(String(t||"").replace(rt,""));function qt(t=[],{finish:o="",window:e=0,thinking:n=!1}={}){if(/^(length|max_tokens|max_output_tokens)$/i.test(String(o||"")))return`⚠ The model ran out of room: its${Number(e)>0?` ${Math.round(Number(e)/1024)}k-token`:""} window filled ${n?"while it was still thinking":"before it wrote an answer"}. A longer context (Settings › Runtime › the engine's Profile), less thinking (its Thinking setting), or a new chat gives it room.`;const r=[...Array.isArray(t)?t:[]].reverse().find(x=>/^error/i.test(String(x?.status||""))||bt(x?.result));if(!r)return"⚠ The model ended this turn without an answer. Try again, or pick another model.";const a=r.input?.action||r.action||r.tool||r.name||"an action",c=(/^error/i.test(String(r.status||""))?String(r.status).replace(/^error:\s*/i,""):String(r.result||"")).replace(rt,"").replace(/\s+/g," ").trim().slice(0,200);return`⚠ No answer: the turn ended after \`${a}\` failed${c?` — ${c}`:""}. Try again, or ask without it.`}function Xt({tools:t,agent:o,settings:e,fallback:n=q}={}){if(!t)return 1;const a=[Math.max(1,Number(n)||q)],h=Number(o?.maxRequestsPerTurn)||0;h>0&&a.push(h);const c=Number(e?.ui?.maxToolRoundsPerTurn??e?.maxToolRoundsPerTurn)||0;return c>0&&a.push(c),Tt(o?.window||o?.contextLength||o?.contextWindow)&&a.push(nt+(t?.handoff?1:0)),Math.max(1,Math.min(...a))}function B(t){if(!t)return{};if(typeof t=="object")return t;try{return JSON.parse(t)}catch{return{}}}const st=t=>typeof t.arguments=="string"?t.arguments:JSON.stringify(t.arguments??t.input??{});function Nt(t){const o=String(P(t)||"");return o.length>X?`${o.slice(0,X)}…`:o}function Rt(t){const o=String(P(t)||"").length;if(o<=X)return"";const e=n=>n.toLocaleString("en-US");return`Showing the first ${e(X)} of ${e(o)} characters — the model received all of them.`}function At(t,o){const e=W(t,o),n=o&&typeof o=="object"&&o.args&&typeof o.args=="object"?o.args:o||{},r=["query","id","tool","location","ref"].find(a=>typeof n[a]=="string"&&n[a]);return r?`${e} "${String(n[r]).slice(0,80)}"`:e}function zt(t,o){const e=Array.isArray(t)?[...t]:[],n=String(o||"").trim();if(!n)return e;const r=e.findIndex(a=>a?.role==="system"&&typeof a.content=="string");return r>=0?(e[r]={...e[r],content:`${e[r].content}
4
4
 
5
5
  ${n}`},e):[{role:"system",content:n},...e]}const N=t=>Number(t)||0;function it(t){if(!t||typeof t!="object")return null;const o=N(t.cacheReadTokens??t.cache_read_input_tokens??t.prompt_tokens_details?.cached_tokens),e=N(t.cacheWriteTokens??t.cache_creation_input_tokens),n=t.inputTokens??t.input_tokens,r=n!=null?N(n):Math.max(0,N(t.prompt_tokens)-o-e),a=N(t.outputTokens??t.output_tokens??t.completion_tokens),h=r+o+e,c={inputTokens:r,outputTokens:a,cacheReadTokens:o,cacheWriteTokens:e,prompt_tokens:h,completion_tokens:a,total_tokens:N(t.total_tokens)||h+a,calls:N(t.calls)||1,reported:t.reported!==!1&&(h>0||a>0)},x=N(t.usd??t.cost);return x&&(c.usd=x),c}function Ot(t,o){const e=it(t),n=it(o);if(!n)return e;if(!e)return n;const r={inputTokens:e.inputTokens+n.inputTokens,outputTokens:e.outputTokens+n.outputTokens,cacheReadTokens:e.cacheReadTokens+n.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens+n.cacheWriteTokens,calls:e.calls+n.calls,reported:e.reported||n.reported};r.prompt_tokens=r.inputTokens+r.cacheReadTokens+r.cacheWriteTokens,r.completion_tokens=r.outputTokens,r.total_tokens=e.total_tokens+n.total_tokens;const a=N(e.usd)+N(n.usd);return a&&(r.usd=a),r}function at(t){return Math.max(0,Math.round(String(t||"").length/4))}function Mt(t,o){const e=(t||[]).map(n=>typeof n?.content=="string"?n.content:JSON.stringify(n?.content||"")).join(`
6
6
  `);return{inputTokens:at(e),outputTokens:at(o),cacheReadTokens:0,cacheWriteTokens:0,estimated:!0}}const Et=Object.freeze({asked(t,o){return{role:"assistant",content:String(t?.text||"")||null,tool_calls:o.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:st(e)}}))}},answered(t,{noVision:o=!1}={}){const e=t.map(({call:n,result:r})=>({role:"tool",tool_call_id:n.id,content:P(r)}));for(const{call:n,result:r}of t){const a=r&&typeof r=="object"?r.image:null;a&&e.push(o?{role:"user",content:`(Screenshot from ${n.name} omitted — this model has no vision. Rely on read_canvas / inspect_page / tool results.)`}:{role:"user",content:[{type:"text",text:`(Screenshot from ${n.name})`},{type:"image_url",image_url:{url:a}}]})}return e},nudge(t,o){return[{role:"assistant",content:null,tool_calls:t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:st(e)}}))},...t.map(e=>({role:"tool",tool_call_id:e.id,content:o}))]},system:t=>({role:"system",content:t}),said:t=>({role:"assistant",content:t})}),Bt=Object.freeze({asked(t,o){return{role:"assistant",content:Array.isArray(t?.blocks)&&t.blocks.length?t.blocks.filter(n=>n&&(n.type==="tool_use"||n.type==="text"&&n.text)).map(n=>n.type==="tool_use"?{type:"tool_use",id:n.id,name:n.name,input:n.input??B(n.json)}:{type:"text",text:n.text}):[...t?.text?[{type:"text",text:String(t.text)}]:[],...o.map(n=>({type:"tool_use",id:n.id,name:n.name,input:n.input}))]}},answered(t){return[{role:"user",content:t.map(({call:o,result:e})=>{const n=P(e),r=e&&typeof e=="object"?e.image:null;if(!r)return{type:"tool_result",tool_use_id:o.id,content:n};const a=/^data:([^;]+);base64,(.+)$/s.exec(r),h=[];return a&&h.push({type:"image",source:{type:"base64",media_type:a[1],data:a[2]}}),h.push({type:"text",text:n}),{type:"tool_result",tool_use_id:o.id,content:h}})}]},nudge(t,o){return[{role:"assistant",content:t.map(e=>({type:"tool_use",id:e.id,name:e.name,input:e.input}))},{role:"user",content:t.map(e=>({type:"tool_result",tool_use_id:e.id,content:o}))}]},system:t=>({role:"user",content:t}),said:t=>({role:"assistant",content:t})});function vt({tools:t,guard:o=null,policy:e=null,modelLabel:n=()=>null,maxCalls:r=0,onStep:a=null,steps:h=[],now:c=Date.now,shims:x=ot()}={}){o=o||tt({shims:x}),e=e||et({shims:x});let R=0,w=0;const M=c(),_=new Map,j=s=>{const l=W(s.name,s.input);return t?.traits?.get(l)||t?.traits?.get(s.name)||dt({name:l})},E=(s,l,i,m)=>{const y={phase:l,callId:s.id,name:s.name,action:W(s.name,s.input),input:s.input,text:At(s.name,s.input),model:n(),...m};if(l==="start")_.set(s.id,y.at=Math.max(0,c()-M));else{const b=i&&typeof i=="object"?i.image:void 0,u=_.get(s.id)??Math.max(0,c()-M),f=Rt(i);Object.assign(y,{status:kt(i),result:Nt(i),...f?{resultNote:f}:{},at:u,ms:Math.max(0,c()-M-u),...b?{image:b}:{}})}return y},I=(s,l)=>{try{a?.(E(s,"start",void 0,l))}catch{}},A=(s,l,i)=>{const m=E(s,"done",l,i);h.push(m);try{a?.(m)}catch{}},C=(s,l,i)=>{e.recordResult(W(s.name,s.input),i),!l.blocked&&!l.replayed&&ht(s.name,i,s.input)&&o.reset(l.key),l.replayed||o.remember(l.key,s.name,s.input,i,{readOnly:!!j(s)?.readOnly})},V=s=>(x.fire("loop.budget-spent",{tool:W(s.name,s.input),calls:R,maxCalls:r}),gt(s.name,z[Math.min(Math.max(0,R-r-1),z.length-1)],{budget:"spent",calls:R,maxCalls:r})),J=async(s,l,i)=>{if(R+=1,r>0&&R>r)return V(s);if(l.blocked||l.replayed)return l.result;if(typeof t?.execute!="function")return JSON.stringify({error:"no tools armed"});const m=W(s.name,s.input);return m!==s.name&&e.isSuppressed(m)?JSON.stringify({error:`${m} rejected its parameters earlier in this turn and is off for the rest of it.`,retry_hint:yt(m)}):t.execute(s.name,s.input,{callId:s.id,shims:x,...i||{}})};return{guard:o,policy:e,steps:h,traitsOf:j,shims:x,get calls(){return R},get exhausted(){return r>0&&R>=r},async one(s,l=null){const i={id:s.id,name:s.name,input:s.input??B(s.arguments)};I(i);const m=o.check(i.name,i.input);let y;try{y=await J(i,m,l)}catch(b){y=JSON.stringify({error:String(b?.message||b)})}return C(i,m,y),A(i,y),y},async round(s){const l=s.map(u=>({id:u.id,name:u.name,input:u.input??B(u.arguments)})),i=l.map(u=>o.check(u.name,u.input)),m=w+=1,{results:y}=await pt(l,{execute:(u,f)=>J(u,i[f]),traitsOf:j,concurrent:(u,f)=>ft(t,u,f),onStart:(u,f,p)=>I(u,{round:m,batch:p}),onDone:(u,f,p,v)=>A(u,p,{round:m,batch:v})});y.forEach((u,f)=>C(l[f],i[f],u));const b=i.filter(u=>u.blocked).length;return o.noteRound(b,l.length,mt(l)),{calls:l,results:y,blocked:b}}}}function Dt(t){const o=String(t?.input?.action||"").toLowerCase();return t?.name===_t&&o==="find"||o==="describe"}const $t=2;function Ut(t){const o=String(t||"").trim();if(!o)return!1;const e=o.split(/(?<=[.!?…:])\s+|\n+/).map(n=>n.trim()).filter(Boolean).at(-1)||"";return e.length>200||/\?\s*$/.test(e)?!1:/^(?:(?:ok(?:ay)?|sure|alright|now|first|so)[,.!]?\s+)?(?:let me|let[’']s|i[’']?ll|i will|i[’']?m going to|i am going to|i[’']?m now going to|now i[’']?ll|one moment|give me a (?:moment|sec(?:ond)?))\b[^?]{0,160}\b(?:look|check|search|find|open|read|fetch|pull|browse|see|try|get|gather|query|dig|explore)\b/i.test(e)}const Wt="You said what you would do next, but called no tool. Do it now with a tool call, or, if no tool can do it, answer with what you have.";async function Vt({model:t,messages:o,tools:e,signal:n,redaction:r,run:a,stream:h,transcript:c=Et,maxRounds:x=q,maxFinishTries:R=wt,guard:w=null,policy:M=null,shims:_=null,modelLabel:j=()=>t||null,usageLabel:E=null,onDelta:I=null,onEvent:A=null,onStep:C=null,onMessage:V=null,onActivity:J=null}={}){if(typeof h!="function")throw new Error("runTurnLoop: stream required");_=_||ot({emit:A?(k,d)=>A({type:"shim",...d}):null,engine:E?.provider?{kind:"model",id:E.provider,model:E.model||t||void 0}:t?{kind:"model",id:t}:null}),w=w||tt({shims:_}),M=M||et({shims:_});const s=!!(e&&Array.isArray(e.specs)&&e.specs.length),l=s?e.specs:null;let i=s?Math.max(1,Number(x)||q):1,m=$t,y=!1;const b=[],u=vt({tools:e,guard:w,policy:M,modelLabel:j,steps:b,shims:_,onStep:k=>{try{C?.(k)}catch{}try{A?.({type:"tool",...k})}catch{}}});let f=[...o||[]],p="",v=null,S=0,K=!1,D=0,F=!1;const $=k=>{for(const d of k){f=[...f,d];try{V?.(d)}catch{}}},L=k=>{try{A?.({type:"finish",reason:k})}catch{}},Q=k=>{if(!A)return;const d=v&&v.reported?{...v,estimated:!1}:Mt(f,k);try{A({type:"usage",provider:E?.provider||"unknown",model:E?.model||t||null,inputTokens:d.inputTokens,outputTokens:d.outputTokens,cacheReadTokens:d.cacheReadTokens,cacheWriteTokens:d.cacheWriteTokens,estimated:!!d.estimated,requests:S})}catch{}},Z=k=>({ok:!0,text:p,usage:v,rounds:S,steps:b,transcript:f,exhausted:F,aborted:!1,shims:_.summary(),...k}),G=(k,d={})=>{const O=String(k||"");return O.trim()&&$([c.said(O)]),Z(d)};for(;;){S+=1;const k=!s||S>=i||w.stalled||w.looping||D>0;s&&S<i&&D===0&&(w.stalled||w.looping)&&_.fire("loop.closing-early",{round:S,cap:i,stalled:!!w.stalled,looping:!!w.looping});const d=k?null:l.filter(g=>!M.isSuppressed(g?.name));let O="";const T=await h({model:t,messages:f,tools:d&&d.length?d:null,signal:n,onActivity:J,...r!==void 0?{redaction:r}:{},...a?{run:a}:{},onDelta:g=>{if(g){if(!O&&p){p+=Y;try{I?.(Y,p)}catch{}}O+=g,p+=g;try{I?.(g,p)}catch{}}}});T?.usage&&(v=Ot(v,T.usage)),T?.noVision&&(K=!0);const H=String(T?.text||"");if(H&&!O&&(p&&(p+=Y),p+=H,O=H),!T?.ok)return L("error"),Z({ok:!1,error:T?.error||"the model did not answer",...T?.status?{status:T.status}:{},aborted:!!T?.aborted,transcript:H.trim()?[...f,c.said(p)]:f});if(T.aborted||n?.aborted)return L("aborted"),G(p,{aborted:!0});const U=(Array.isArray(T.toolCalls)?T.toolCalls:[]).filter(g=>g&&g.name).map(g=>({id:g.id,name:g.name,input:g.input??B(g.arguments),arguments:g.arguments}));if(!U.length){if(!y&&d&&d.length&&Ut(O)){y=!0,S+1>=i&&(i=S+2),_.fire("loop.announced-not-done",{round:S}),$([c.said(O),{role:"user",content:Wt}]);continue}return L(T.finish||"stop"),Q(p),G(p,{finish:T.finish||"stop"})}if(!d||!d.length){if(D+=1,D>R)return L("tool-step-limit"),Q(p),G(p,{exhausted:!0});F=F||S>=i,_.fire("loop.finish-nudge",{attempt:D,calls:U.length}),$(c.nudge(U,z[Math.min(D-1,z.length-1)]));continue}$([c.asked(T,U)]);const{calls:lt,results:ut}=await u.round(U);if($(c.answered(lt.map((g,ct)=>({call:g,result:ut[ct]})),{noVision:K})),n?.aborted)return L("aborted"),G(p,{aborted:!0});w.looping&&(_.fire("loop.looping-nudge",{repeats:w.repeats}),$([c.system(St)])),m>0&&U.every(Dt)&&(m-=1,i+=1,_.fire("loop.discovery-round",{round:S,cap:i})),S+1>=i&&(F=!0)}}export{Wt as ANNOUNCED_NUDGE,wt as DEFAULT_MAX_FINISH_TRIES,q as DEFAULT_MAX_ROUNDS,$t as DISCOVERY_GRACE,xt as EXHAUSTED_NOTE,z as FINISH_NUDGES,St as LOOPING_NUDGE,Y as ROUND_SEPARATOR,nt as SMALL_WINDOW_ROUNDS,X as STEP_RESULT_MAX_CHARS,Ot as addUsage,Ut as announcesAction,Bt as anthropicTranscript,vt as createCallRunner,At as describeCall,qt as emptyTurnNote,at as estimateTokens,Dt as isDiscoveryCall,it as normalizeUsage,Et as openAiTranscript,P as resultText,Xt as roundCap,Vt as runTurnLoop,Rt as stepResultNote,Nt as stepResultText,zt as withToolSystem};
package/web-research.js CHANGED
@@ -1,7 +1,7 @@
1
- import{fuseRRF as W,planQueries as re}from"./rrf.js";import{buildIndex as oe,bm25Search as ne}from"./text-index.js";import{offersIn as ae,rankOffers as ie,quoteFormIn as ce,formatValue as Z,basisLabel as M,hostOf as le}from"./offers.js";import{fenceUntrusted as ue}from"./page-guard.js";import{markdownUrl as U}from"./citations.js";const P=Object.freeze({queries:4,rounds:2,parallel:3,pages:10,perHost:2,read:6,passages:8,passageChars:700,offers:8,forms:5,ms:25e3,briefChars:9e3}),C="jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?",Y="monday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tue|wed|thu|fri|sat|sun",N=new RegExp(String.raw`\b(?:(?:${C})\.?\s+\d{1,2}(?:st|nd|rd|th)?(?:\s*(?:-|–|to|until)\s*(?:(?:${C})\.?\s+)?\d{1,2}(?:st|nd|rd|th)?)?(?:,?\s+\d{4})?|\d{1,2}(?:st|nd|rd|th)?\s+(?:${C})\b(?:\s+\d{4})?|(?:in|during|for|this|next|early|mid|late)\s+(?:${C})\b|\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}(?:\/\d{2,4})?|(?:this|next|coming)\s+(?:week(?:end)?|month|(?:${Y}))|tomorrow|tonight|today|(?:over|for)\s+(?:christmas|thanksgiving|new year'?s?|easter|spring break|the holidays)|in\s+\d+\s+(?:days?|weeks?|months?))\b`,"i"),he=new RegExp(`^(?:${C}|${Y}|today|tomorrow|tonight|next|this|the|a|an|my|our|me|us|\\d+)$`,"i"),de=/\s+(?:for|from|to|on|in|at|under|below|with|next|this|during|by|and|or|between|around|near|within|over|departing|leaving|returning|round|one|nonstop|direct|cheap|best|flights?|hotels?|deals?)\b.*$/i,pe=/\b(\d{5}(?:-\d{4})?|[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2})\b/,K=/\b([A-Z]{3})\s*(?:-|–|→|>|to)\s*([A-Z]{3})\b/;function z(e){const t=String(e||"").replace(de,"").replace(/[?!.,;:]+$/g,"").trim();return!t||t.split(/\s+/).length>4||he.test(t)||N.test(t)||!new RegExp("\\p{L}","u").test(t)||/^(?:me|here|there|home|you|it|them|us|the|a|my|our|cheap|best|flights?|hotels?)$/i.test(t)?"":t}const D={where:e=>{const t=pe.exec(e);if(t)return t[1];const r=/\b(?:in|near|around|at|for)\s+([\p{L}][\p{L}.'’ -]{1,40})/iu.exec(e.replace(N," "));return r?z(r[1]):""},from:e=>{const t=K.exec(e);if(t)return t[1];const r=/\bfrom\s+([\p{L}][\p{L}.'’ -]{1,40}?)(?=\s+(?:to|→|-)\s|\s*$|[?,])/iu.exec(e)||/\b([\p{L}][\p{L}.'’ -]{1,30}?)\s+to\s+[\p{L}][\p{L} .'-]{1,30}?\s+(?:flights?|fares?|airfare|tickets?)\b/iu.exec(e);return r?z(r[1].replace(/^(?:cheap(?:est)?|best|find|flights?|fly(?:ing)?|airfares?)\s+/i,"").replace(/^(?:flights?|fly(?:ing)?)\s+/i,"")):""},to:e=>{const t=K.exec(e);if(t)return t[2];const r=/\bto\s+([\p{L}][\p{L}.'’ -]{1,40})/iu.exec(e.replace(/\bhow much\b/i,""));return r?z(r[1]):""},when:e=>(N.exec(e)?.[0]||"").trim(),who:e=>/\b(\d+|one|two|three|four|five|six|seven|eight)\s+(?:adults?|people|persons|passengers|travell?ers|guests|of us)\b|\bfamily of (\d+)\b|\b(solo|couple)\b/i.exec(e)?.[0]||"",budget:e=>/\b(?:under|below|less than|max(?:imum)?|up to|within|no more than|<)\s*(?:[$€£]\s?)?\d[\d,.]*\s?(?:k|usd|eur|gbp|dollars|euros|pounds)?(?:\s*(?:\/|per|a)\s*(?:mo(?:nth)?|yr|year|night))?\b/i.exec(e)?.[0]||"",kind:e=>(/\b(auto|car|vehicle|motorcycle|homeowners?|home|house|renters?|condo|landlord|term life|whole life|life|health|medical|dental|vision|pet|dog|cat|travel|boat|umbrella|business)\b/i.exec(e)?.[1]||"").toLowerCase()},B=Object.freeze([{id:"insurance",label:"insurance",match:/\binsur(?:ance|er|ers)\b|\b(?:premiums?|coverage) (?:quotes?|rates?|prices?)\b/i,terms:["insurance","quote","rate","premium","coverage"],subject:"{kind?} insurance",queries:["{kind?} insurance quotes {where?}","cheapest {kind?} insurance {where?} {year}","{kind?} insurance rates compared {year}"],slots:[{id:"kind",label:"what to insure (car, home, renters, life, health, pet, travel…)",required:!0},{id:"where",label:"ZIP code / postcode or state",required:!0}],forms:!0},{id:"flight",label:"flights",match:/\b(?:flights?|airfares?|air ?fares?|plane tickets?|airline tickets?|fly(?:ing)? (?:to|from|out)|nonstop to)\b/i,terms:["flight","fare","airline","round","trip"],subject:"flights",queries:["cheap flights {from} to {to} {when?}","{from} to {to} flight deals","{from} {to} airfare {when?} {year}","cheap flight deals {year}","best time to book flights {year}"],slots:[{id:"from",label:"departure city or airport",required:!0},{id:"to",label:"destination",required:!0},{id:"when",label:"travel dates",required:!0},{id:"who",label:"number of travellers",required:!1}],forms:!0},{id:"hotel",label:"hotels",match:/\b(?:hotels?|motels?|resorts?|accommodation|lodging|places? to stay|vacation rentals?|airbnb|b&b)\b/i,terms:["hotel","night","room","stay"],subject:"hotels",queries:["best hotel deals {where} {when?}","cheap hotels {where} {when?}","{where} hotels price per night {year}","hotel deals {year}"],slots:[{id:"where",label:"city or area",required:!0},{id:"when",label:"dates",required:!0},{id:"who",label:"number of guests",required:!1}],forms:!0},{id:"car-rental",label:"car rental",match:/\b(?:car rentals?|rental cars?|rent a car|hire car|car hire)\b/i,terms:["rental","car","day"],subject:"car rental",queries:["cheap car rental {where} {when?}","car rental deals {where} {year}","car rental deals {year}"],slots:[{id:"where",label:"pick-up city or airport",required:!0},{id:"when",label:"dates",required:!0}],forms:!0},{id:"plan",label:"plans",match:/\b(?:internet|broadband|fib(?:er|re)|wi-?fi|mobile|cell(?:ular)?|phone|sim|electric(?:ity)?|energy|power|gas|streaming|vpn|cloud storage)\s+(?:plans?|providers?|deals?|services?|bills?|tariffs?|rates?|packages?)\b/i,terms:["plan","month","price"],queries:["best {subject} {where?} {year}","cheapest {subject} {where?}","{subject} prices compared {year}"],slots:[{id:"where",label:"ZIP code / city",required:!1},{id:"budget",label:"budget",required:!1}],forms:!1},{id:"product",label:"products",match:null,terms:["price","review"],queries:["best {subject} {budget?} {year}","{subject} price","{subject} deals {budget?}"],slots:[{id:"budget",label:"budget",required:!1}],forms:!1}]),I=e=>B.find(t=>t.id===e)||B[B.length-1],Q=/\b(?:cheapest|cheaper|lowest (?:price|fare|rate|cost)s?|affordable|deals?|discounts?|coupons?|promo codes?|on sale|bargains?|prices?|pricing|fares?|(?:get|want|need|free|instant) (?:a |an |my )?quotes?|quotes? (?:for|on)|how much (?:is|are|does|do|would|will|for|to)\b(?!\s+(?:time|longer|more|of my|of the (?:meeting|page|doc)))[^?]*\b(?:cost|costs|charge|pay|price)|how much (?:is|are) (?:a|an|the)? ?(?:flight|ticket|hotel|room|night)|cost of (?:a|an|the)?)\b/i,fe=/\b(?:best|top[- ]rated|compare|comparison|vs\.?|versus|recommend(?:ation)?s? for|worth buying|quotes?|where (?:can i|to|should i) (?:buy|get|find|book|rent)|save money on|rates?)\b/i,ge=/\b(?:buy|buying|purchase|shop(?:ping)?|order|book(?:ing)?|rent(?:al|ing)?|subscribe|subscription|plans?|insurance|flights?|hotels?|tickets?|deals?|prices?|costs?|rates?|fares?|movers?|moving company|contractors?|plumbers?|roofers?|repair (?:shop|service)s?|installation|providers?|under\s*[$€£]?\s?\d)\b|[$€£]\s?\d/i,me=/\bbest\s+(?!way|ways|practice|practices|time|approach|method|answer|thing|things|idea|ideas|advice|place to (?:learn|start)|book(?!ing))[\p{L}\d][\p{L}\d+-]*(?:\s+[\p{L}\d][\p{L}\d+-]*){0,3}\s+(?:for|under|below|to buy|in 20\d\d|of 20\d\d)\b/iu,be=/\b(?:stocks?|shares?|share price|ticker|market cap|dividend|crypto(?:currency)?|bitcoin|ethereum|exchange rate)\b|\b(?:my|our) (?:notes?|meetings?|chats?|calendar|emails?|inbox|files?|docs?|documents?|history|library)\b|\b(?:this|the) (?:page|tab|doc(?:ument)?|file|repo(?:sitory)?|code(?:base)?|pr|diff|function|spreadsheet)\b|\b(?:function|exception|stack ?trace|npm|pip|python|javascript|typescript|regex|sql|compile|git|docker|kubernetes|api key|endpoint)\b/i,G=/^\s*(?:(?:hey|hi|ok(?:ay)?|so|please|pls|can you|could you|would you|will you|help me|i need(?: to)?|i want(?: to)?|i'?m looking for|i am looking for|look(?:ing)? for|find(?: me)?|get(?: me)?|show(?: me)?|search(?: for)?|look up|tell me|give me|what(?:'s| is| are)|which(?: is| are)?|where(?:'s| is| are| can i (?:buy|get|find|book))?|who (?:has|offers)|how much (?:is|are|does|do|for)|how much)\s+)+/i,F=/\s+(?:for me|for us|near me|right now|now|today|online|please|pls|this year|in 20\d\d)\s*$|[?!.]+$/i,we=/\b(?:the|a|an|best|cheapest|cheaper|cheap|lowest|affordable|good|great|top[- ]rated|top|most|really|deals?|discounts?|coupons?|bargains?|quotes?|prices?|pricing|costs?|rates?|fares?|offers?|options?|compare|comparison|cost|to buy|on sale)\b/gi;function ye(e,t){let r=String(e||"").replace(G,"").replace(F,"").replace(F,"");return r=r.replace(N," ").replace(/\b(?:from|to|in|near|around|under|below|for|with|between)\s+.*$/i,o=>t.id==="product"||t.id==="plan"?o.replace(/\b(?:in|near|around|from|to)\s+.*$/i,""):""),r=r.replace(D.budget(r)||"\0"," ").replace(we," ").replace(/\b(?:does|do|is|are|a|an|it|cost|costs|20\d\d|i|can|buy|get|where)\b/gi," ").replace(/\s+/g," ").trim(),r.length>=2?r:t.label}function V(e,t){let r=!0;const o=e.replace(/\{(\w+)(\?)?\}/g,(l,i,s)=>(!t[i]&&!s&&(r=!1),t[i]||""));return r?o.replace(/\s+/g," ").trim():""}function Ie(e,{previous:t=null,now:r=Date.now()}={}){const o=String(e||"").trim();if(!o||o.length>400)return null;const l=o.split(/\s+/).length,i=t?.kind==="research"&&t.research?.domain?t.research:null;let s=B.find(u=>u.match&&u.match.test(o))||null;const d=s?s.slots.filter(u=>D[u.id]?.(o)).length:0,p=!be.test(o)&&l>=2&&(Q.test(o)||fe.test(o)&&(s||ge.test(o))||me.test(o)||s&&(/\b(?:find|search|look|book|get|need)\b/i.test(o)||d>=2));if(!p&&i&&l<=14&&(!s||s.id===i.domain)){const u=I(i.domain),b=Object.fromEntries(u.slots.map(c=>[c.id,D[c.id]?.(o)||""]).filter(([,c])=>c));return Object.keys(b).length?J(`${i.question} ${o}`,u,{...i.slots,...b},r,!0,u.subject?"":i.subject):null}if(!p)return null;s||=I("product");const h=Object.fromEntries(s.slots.map(u=>[u.id,D[u.id]?.(o)||""]).filter(([,u])=>u));return J(o,s,h,r,!1)}function J(e,t,r,o,l,i=""){const s=String(new Date(o).getFullYear()),d=i||(t.subject?V(t.subject,r):ye(e,t)),p={...r,subject:d,year:s},h=t.queries.map(c=>V(c,p)).filter(Boolean),u=l?"":e.replace(G,"").replace(F,"").replace(/^(?:a|an|the)\s+/i,"").trim(),b=(u?re(u,{extra:h,max:P.queries*2}):[...new Set(h)]).filter(c=>c.split(/\s+/).length>=2).slice(0,P.queries);return{question:e,domain:t.id,subject:d,slots:r,missing:t.slots.filter(c=>c.required&&!r[c.id]).map(c=>({id:c.id,label:c.label})),queries:b,forms:t.forms,followUp:l}}function $e(e,t=[],{now:r=Date.now()}={}){const o=String(new Date(r).getFullYear()),l=I(e.domain),i=l.slots.map(u=>e.slots?.[u.id]).filter(Boolean).join(" "),s=e.subject,d=[`${s} ${i} price ${o}`,l.forms?`${s} ${i} average cost`:`${s} ${i} cost`,`${s} ${i} comparison`,`${s} ${i}`],p=new Set(t.map(u=>u.toLowerCase().replace(/\s+/g," ").trim())),h=[];for(const u of d){const b=u.replace(/\s+/g," ").trim();b.split(/\s+/).length>=2&&!p.has(b.toLowerCase())&&!h.includes(b)&&h.push(b)}return h.slice(0,3)}function ke(e){if(e&&typeof e=="object"&&Array.isArray(e.results))return{query:e.query||"",engines:e.engines||[],results:e.results.filter(i=>i?.url)};const t=typeof e=="string"?e:typeof e?.text=="string"?e.text:"",r=/^Web search results for "([^"]*)" \(engines: ([^)]*)\)/m.exec(t),o=t.indexOf("Result details:");if(!r||o<0)return{query:r?.[1]||"",engines:[],results:[]};const l=[];for(const i of t.slice(o).split(/\n+---\n+(?=### \[\d+\])/)){const s=/### \[(\d+)\] ([^\n]*)\n<([^>\s]+)>\n\n?([\s\S]*)$/.exec(i);s&&l.push({rank:Number(s[1]),title:s[2].trim(),url:s[3],text:s[4].trim()})}return{query:r[1],engines:r[2].split(/,\s*/).filter(Boolean),results:l}}const X=/^(?:utm_\w+|gclid|fbclid|msclkid|mc_[a-z]+|ref|ref_src|source|campaign|affiliate|aff_id|clickid|irclickid|_ga)$/i;function xe(e){try{const t=new URL(e);for(const r of[...t.searchParams.keys()])X.test(r)&&t.searchParams.delete(r);return t.hash="",t.toString()}catch{return String(e||"")}}function qe(e){try{const t=new URL(e),o=[...t.searchParams.entries()].filter(([l])=>!X.test(l)).sort(([l],[i])=>l.localeCompare(i)).map(([l,i])=>`${l}=${i}`).join("&");return`${t.hostname.replace(/^www\./,"").toLowerCase()}${t.pathname.replace(/\/+$/,"")||"/"}${o?`?${o}`:""}`}catch{return String(e||"")}}function ve(e,t=P.passageChars){const r=[];let o="";const l=()=>{const i=o.trim();i.length>=40&&r.push(i),o=""};for(const i of String(e||"").split(/\n\s*\n/)){const s=i.replace(/[ \t]+/g," ").trim();if(s)if(s.length>t){l();let d="";for(const p of s.split(/(?<=[.!?])\s+/))d&&d.length+p.length+1>t&&(o=d,l(),d=""),d=d?`${d} ${p}`:p.slice(0,t);o=d,l()}else o.length+s.length+2>t?(l(),o=s):o=o?`${o}
2
- ${s}`:s}return l(),r}async function ee(e,t,r,o){const l=new Array(e.length);let i=0;const s=Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;i<e.length;){const d=i++;try{l[d]=await r(e[d],d)}catch{l[d]=null}}});return await(o?Promise.race([Promise.all(s),o]):Promise.all(s)),l}async function je({ask:e,search:t,read:r=null,rerank:o=null,now:l=()=>Date.now(),until:i=null,limits:s={},onProgress:d=()=>{}}={}){if(!e||typeof t!="function")throw new Error("webResearch: ask and search required");const p={...P,...s},h=l(),u=()=>l()-h>p.ms;let b=!1;const c=i?i.then(()=>{b=!0}):null,x=I(e.domain),q=[],A=[],k=new Map,O=new Set;let v=0,a=null;const f=(S,L)=>{try{d({phase:S,label:L,searches:q.length,pages:k.size,offers:a?.offerCount||0})}catch{}};let m=e.queries.slice(0,p.queries);for(let S=1;S<=p.rounds&&m.length;S++){f("search",`Searching: ${m.map($=>`“${$}”`).join(", ")}`);const L=await ee(m,p.parallel,async $=>ke(await t($)),c);if(m.forEach(($,n)=>{q.push($);const g=L[n];if(!g?.results?.length){v+=1;return}g.engines.forEach(y=>O.add(y));const w=[];g.results.forEach(y=>{const R=qe(y.url);w.push(R);const T=k.get(R),H=String(y.text||y.snippet||"");T?(T.foundBy.push($),H.length>T.text.length&&(T.text=H)):k.set(R,{key:R,url:xe(y.url),title:y.title||y.url,host:le(y.url),text:H,foundBy:[$]})}),A.push(w)}),r&&!b&&!u()){const $=te(A,k,p).filter(n=>n.text.length<400).slice(0,p.read);if($.length){f("read",`Reading ${$.length} page${$.length===1?"":"s"}`);const n=await ee($,p.parallel,g=>r(g.url),c);$.forEach((g,w)=>{const y=n[w],R=typeof y=="string"?y:y?.text;R&&R.length>g.text.length&&(g.text=String(R),y?.title&&(g.title=y.title))})}}if(a=await se({ask:e,d:x,lists:A,pages:k,L:p,rerank:o}),f("decide",Se(a)),a.enough||b||u()||S===p.rounds)break;m=$e(e,q,{now:h})}a||=await se({ask:e,d:x,lists:A,pages:k,L:p,rerank:null});const E={searches:q.length,failed:v,pages:k.size,sites:new Set([...k.values()].map(S=>S.host)).size,engines:[...O],ms:Math.max(0,l()-h)},j={ask:e,queries:q,...a,stats:E};return{...j,text:Ee(j,p)}}function te(e,t,r){const o=new Map,l=[];for(const{id:i}of W(e)){const s=t.get(i);if(!s?.host)continue;const d=o.get(s.host)||0;if(!(d>=r.perHost)&&(o.set(s.host,d+1),l.push(s),l.length>=r.pages))break}return l}async function se({ask:e,d:t,lists:r,pages:o,L:l,rerank:i}){const s=te(r,o,l),d=new Map(s.map((n,g)=>[n.key,g])),p=[e.subject,...Object.values(e.slots||{}),...t.terms],h=t.id!=="product"||Q.test(e.question)||!!e.slots?.budget||/\b(?:cheap|costs?|deals?|quotes?|rates?)\b|[$€£]/i.test(e.question),u=[];for(const n of s)ve(n.text,l.passageChars).forEach((g,w)=>u.push({id:`${n.key}#${w}`,key:n.key,url:n.url,host:n.host,title:n.title,text:g}));const b=`${p.join(" ")}${h?" price cost per month":""}`,c=u.length?ne(oe(u),b).map(n=>n.id):[],x=[...u].sort((n,g)=>d.get(n.key)-d.get(g.key)).map(n=>n.id),q=h?u.filter(n=>/[$€£]\s?\d|\d\s?(?:€|£|USD|EUR|GBP)\b/.test(n.text)).map(n=>n.id):[],A=[c,x,...q.length?[q]:[]];if(typeof i=="function"&&c.length){const n=c.slice(0,40).map(g=>u.find(w=>w.id===g));try{const g=await i(e.question,n.map(w=>w.text));Array.isArray(g)&&g.length===n.length&&A.push(n.map((w,y)=>({id:w.id,s:Number(g[y])||0})).sort((w,y)=>y.s-w.s).map(w=>w.id))}catch{}}const k=new Set(c),O=new Map(u.map(n=>[n.id,n])),v=new Map,a=[];for(const{id:n}of W(A)){if(!k.has(n))continue;const g=O.get(n),w=v.get(g.host)||0;if(!(w>=2)&&(v.set(g.host,w+1),a.push(g),a.length>=l.passages))break}const f=h?ie(s.flatMap(n=>ae(n.text,{url:n.url,title:n.title,terms:p,max:l.offers}))):{basis:"",currency:"",ranked:[],floors:[],other:[],averages:[]},m=[];for(const n of s){const g=t.forms||/\bquote\b/i.test(e.question)?ce(n.text):"";if(g&&!m.some(w=>w.host===n.host)&&m.push({url:n.url,title:n.title,host:n.host,cta:g}),m.length>=l.forms)break}const E=f.ranked.length+f.floors.length,j=new Set([...f.ranked,...f.floors].map(n=>n.host)).size,S=f.ranked.some(n=>n.seenOn>=2),L=new Set(a.map(n=>n.host)).size,$=h?E>=3&&j>=2||S&&f.ranked.length>=2:a.length>=4&&L>=3;return{pages:s,passages:a,offers:f,forms:m,enough:$,offerCount:E,wantPrices:h}}function Se(e){const t=[`${e.pages.length} page${e.pages.length===1?"":"s"}`];return e.wantPrices&&t.push(`${e.offerCount} price${e.offerCount===1?"":"s"}`),e.forms.length&&t.push(`${e.forms.length} quote form${e.forms.length===1?"":"s"}`),t.join(" · ")}const _=(e,t)=>{const r=String(e||"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}…`:r};function Ee(e,t={}){const r={...P,...t};if(!e?.pages?.length)return"";const o=new Map,l=a=>(o.has(a.url)||o.set(a.url,{n:o.size+1,title:a.title||a.host||a.url,url:a.url}),o.get(a.url).n),i=a=>`[${l(a)}](${U(a.url)})`,{offers:s,forms:d,passages:p,ask:h,stats:u}=e,b=I(h.domain),c=[],x=`${u.searches} search${u.searches===1?"":"es"}, ${u.pages} page${u.pages===1?"":"s"} from ${u.sites} site${u.sites===1?"":"s"}, ${(u.ms/1e3).toFixed(1)} s`;e.wantPrices&&h.browse?c.push(`(FIRST PASS from web search for the question below — ${x}. These are listing and article pages, not live quotes. A price answers the question only when its page says it is for THIS request (the route or item, and the dates asked); a 12-month low, an average or a deal advertised for other dates does not. When nothing below is that, get it live before answering: open the booking or comparison site in your own tab (page open_tab), enter the request, read the results, and compare at least two sites. Cite with the markdown links given and with the pages you open. Do not repeat these searches.)`):c.push(`(ALREADY RESEARCHED on the web for the question below — ${x}. Answer from this and cite with the markdown links given. `+(e.wantPrices?'State ONLY prices listed under "Prices found" — each was read on the linked page — and call a "from" price an advertised minimum, not a quote. ':"")+"Do not repeat these searches; search again only for something this does not cover.)"),c.push(""),c.push(`Question: ${_(h.question,200)}`);const q=b.slots.filter(a=>h.slots?.[a.id]).map(a=>`${a.id} = ${h.slots[a.id]}`);if(c.push(`Looking for: ${h.subject}${b.id!=="product"?` (${b.label})`:""}${q.length?` · known: ${q.join(" · ")}`:""}`),h.missing?.length&&h.browse?c.push(`Not given: ${h.missing.map(a=>a.label).join("; ")}. Use what the conversation, the user's memory or the pages below point to (a page searched from a city says where they are), say it is an assumption, and go on — ask only when nothing points anywhere. A vague time ("the holidays") is the usual span; say which dates you took.`):h.missing?.length&&c.push(`Missing for a personalised price: ${h.missing.map(a=>a.label).join("; ")}. Ask the user for these before filling any quote form — say what the prices below are based on meanwhile.`),e.wantPrices){c.push("");const a=s.basis==="month"?"per month":M(s.basis);if(s.ranked.length){c.push(`Prices found (cheapest first, ${a}${s.currency?`, ${s.currency}`:""}):`);const f=[];for(const m of s.ranked){const E=f.find(j=>j.o.currency===m.currency&&Math.round(j.o.value*100)===Math.round(m.value*100));E?E.also.some(j=>j.url===m.url)||E.also.push(m):f.push({o:m,also:[]})}f.slice(0,r.offers).forEach(({o:m,also:E},j)=>{const S=[m,...E].map(i).filter((L,$,n)=>n.indexOf(L)===$).join(" ");c.push(`${j+1}. ${Z(m.value,m.currency,s.basis)}${m.converted?` (${m.raw} ${M(m.basis)})`:""} — “${_(m.quote,160)}” ${S}${m.seenOn>1?` · stated by ${m.seenOn} sites`:""}`)})}else c.push(h.browse?"Prices found: none stated plainly on the pages read — do not invent one; get them live, as above.":"Prices found: none stated plainly on the pages read — do not invent one; say so and offer to get a quote.");s.floors.length&&c.push(`Advertised minimums ("from" — not a quote for this person): ${s.floors.slice(0,4).map(f=>`${Z(f.value,f.currency,s.basis)} ${i(f)}`).join(" · ")}`),s.other.length&&c.push(`On another basis or currency (not comparable with the list above): ${s.other.slice(0,4).map(f=>`${f.raw} ${M(f.basis)} ${i(f)}`).join(" · ")}`),s.averages.length&&c.push(`Averages (context, not offers): ${s.averages.slice(0,3).map(f=>`${f.raw} ${M(f.basis)} — “${_(f.quote,100)}” ${i(f)}`).join(" · ")}`)}if(d.length){c.push(""),c.push("Quote forms (an exact price needs the user's details — you can fill these in the user's browser with the page tools, asking them for anything missing; NEVER press a submit/continue/pay button without the user's OK):");for(const a of d)c.push(`- ${a.host}: “${a.cta}” ${i(a)}`)}const A=p.map(a=>`[${l(a)}] ${a.title?`${_(a.title,80)} — `:""}${a.text}`);c.push(""),c.push("Sources:");for(const a of o.values())c.push(`[${a.n}] [${_(a.title,90)}](${U(a.url)})`);let k=c.join(`
3
- `);const O=r.briefChars-k.length-200;let v="";for(const a of A){if(v.length+a.length+2>O)break;v+=`${v?`
1
+ import{fuseRRF as W,planQueries as re}from"./rrf.js";import{buildIndex as oe,bm25Search as ne}from"./text-index.js";import{offersIn as ae,rankOffers as ie,quoteFormIn as ce,formatValue as Z,basisLabel as M,hostOf as le}from"./offers.js";import{fenceUntrusted as ue}from"./page-guard.js";import{markdownUrl as U}from"./citations.js";const P=Object.freeze({queries:4,rounds:2,parallel:3,pages:10,perHost:2,read:6,passages:8,passageChars:700,offers:8,forms:5,ms:25e3,briefChars:9e3}),C="jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?",Y="monday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tue|wed|thu|fri|sat|sun",N=new RegExp(String.raw`\b(?:(?:${C})\.?\s+\d{1,2}(?:st|nd|rd|th)?(?:\s*(?:-|–|to|until)\s*(?:(?:${C})\.?\s+)?\d{1,2}(?:st|nd|rd|th)?)?(?:,?\s+\d{4})?|\d{1,2}(?:st|nd|rd|th)?\s+(?:${C})\b(?:\s+\d{4})?|(?:in|during|for|this|next|early|mid|late)\s+(?:${C})\b|\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}(?:\/\d{2,4})?|(?:this|next|coming)\s+(?:week(?:end)?|month|(?:${Y}))|tomorrow|tonight|today|(?:over|for)\s+(?:christmas|thanksgiving|new year'?s?|easter|spring break|the holidays)|in\s+\d+\s+(?:days?|weeks?|months?))\b`,"i"),he=new RegExp(`^(?:${C}|${Y}|today|tomorrow|tonight|next|this|the|a|an|my|our|me|us|\\d+)$`,"i"),de=/\s+(?:for|from|to|on|in|at|under|below|with|next|this|during|by|and|or|between|around|near|within|over|departing|leaving|returning|round|one|nonstop|direct|cheap|best|flights?|hotels?|deals?)\b.*$/i,pe=/\b(\d{5}(?:-\d{4})?|[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2})\b/,K=/\b([A-Z]{3})\s*(?:-|–|→|>|to)\s*([A-Z]{3})\b/;function z(e){const t=String(e||"").replace(de,"").replace(/[?!.,;:]+$/g,"").trim();return!t||t.split(/\s+/).length>4||he.test(t)||N.test(t)||!new RegExp("\\p{L}","u").test(t)||/^(?:me|here|there|home|you|it|them|us|the|a|my|our|cheap|best|flights?|hotels?)$/i.test(t)?"":t}const D={where:e=>{const t=pe.exec(e);if(t)return t[1];const r=/\b(?:in|near|around|at|for)\s+([\p{L}][\p{L}.'’ -]{1,40})/iu.exec(e.replace(N," "));return r?z(r[1]):""},from:e=>{const t=K.exec(e);if(t)return t[1];const r=/\bfrom\s+([\p{L}][\p{L}.'’ -]{1,40}?)(?=\s+(?:to|→|-)\s|\s*$|[?,])/iu.exec(e)||/\b([\p{L}][\p{L}.'’ -]{1,30}?)\s+to\s+[\p{L}][\p{L} .'-]{1,30}?\s+(?:flights?|fares?|airfare|tickets?)\b/iu.exec(e);return r?z(r[1].replace(/^(?:cheap(?:est)?|best|find|flights?|fly(?:ing)?|airfares?)\s+/i,"").replace(/^(?:flights?|fly(?:ing)?)\s+/i,"")):""},to:e=>{const t=K.exec(e);if(t)return t[2];const r=/\bto\s+([\p{L}][\p{L}.'’ -]{1,40})/iu.exec(e.replace(/\bhow much\b/i,""));return r?z(r[1]):""},when:e=>(N.exec(e)?.[0]||"").trim(),who:e=>/\b(\d+|one|two|three|four|five|six|seven|eight)\s+(?:adults?|people|persons|passengers|travell?ers|guests|of us)\b|\bfamily of (\d+)\b|\b(solo|couple)\b/i.exec(e)?.[0]||"",budget:e=>/\b(?:under|below|less than|max(?:imum)?|up to|within|no more than|<)\s*(?:[$€£]\s?)?\d[\d,.]*\s?(?:k|usd|eur|gbp|dollars|euros|pounds)?(?:\s*(?:\/|per|a)\s*(?:mo(?:nth)?|yr|year|night))?\b/i.exec(e)?.[0]||"",kind:e=>(/\b(auto|car|vehicle|motorcycle|homeowners?|home|house|renters?|condo|landlord|term life|whole life|life|health|medical|dental|vision|pet|dog|cat|travel|boat|umbrella|business)\b/i.exec(e)?.[1]||"").toLowerCase()},B=Object.freeze([{id:"insurance",label:"insurance",match:/\binsur(?:ance|er|ers)\b|\b(?:premiums?|coverage) (?:quotes?|rates?|prices?)\b/i,terms:["insurance","quote","rate","premium","coverage"],subject:"{kind?} insurance",queries:["{kind?} insurance quotes {where?}","cheapest {kind?} insurance {where?} {year}","{kind?} insurance rates compared {year}"],slots:[{id:"kind",label:"what to insure (car, home, renters, life, health, pet, travel…)",required:!0},{id:"where",label:"ZIP code / postcode or state",required:!0}],forms:!0},{id:"flight",label:"flights",match:/\b(?:flights?|airfares?|air ?fares?|plane tickets?|airline tickets?|fly(?:ing)? (?:to|from|out)|nonstop to)\b/i,terms:["flight","fare","airline","round","trip"],subject:"flights",queries:["cheap flights {from} to {to} {when?}","{from} to {to} flight deals","{from} {to} airfare {when?} {year}","cheap flight deals {year}","best time to book flights {year}"],slots:[{id:"from",label:"departure city or airport",required:!0},{id:"to",label:"destination",required:!0},{id:"when",label:"travel dates",required:!0},{id:"who",label:"number of travellers",required:!1}],forms:!0},{id:"hotel",label:"hotels",match:/\b(?:hotels?|motels?|resorts?|accommodation|lodging|places? to stay|vacation rentals?|airbnb|b&b)\b/i,terms:["hotel","night","room","stay"],subject:"hotels",queries:["best hotel deals {where} {when?}","cheap hotels {where} {when?}","{where} hotels price per night {year}","hotel deals {year}"],slots:[{id:"where",label:"city or area",required:!0},{id:"when",label:"dates",required:!0},{id:"who",label:"number of guests",required:!1}],forms:!0},{id:"car-rental",label:"car rental",match:/\b(?:car rentals?|rental cars?|rent a car|hire car|car hire)\b/i,terms:["rental","car","day"],subject:"car rental",queries:["cheap car rental {where} {when?}","car rental deals {where} {year}","car rental deals {year}"],slots:[{id:"where",label:"pick-up city or airport",required:!0},{id:"when",label:"dates",required:!0}],forms:!0},{id:"plan",label:"plans",match:/\b(?:internet|broadband|fib(?:er|re)|wi-?fi|mobile|cell(?:ular)?|phone|sim|electric(?:ity)?|energy|power|gas|streaming|vpn|cloud storage)\s+(?:plans?|providers?|deals?|services?|bills?|tariffs?|rates?|packages?)\b/i,terms:["plan","month","price"],queries:["best {subject} {where?} {year}","cheapest {subject} {where?}","{subject} prices compared {year}"],slots:[{id:"where",label:"ZIP code / city",required:!1},{id:"budget",label:"budget",required:!1}],forms:!1},{id:"product",label:"products",match:null,terms:["price","review"],queries:["best {subject} {budget?} {year}","{subject} price","{subject} deals {budget?}"],slots:[{id:"budget",label:"budget",required:!1}],forms:!1}]),I=e=>B.find(t=>t.id===e)||B[B.length-1],Q=/\b(?:cheapest|cheaper|lowest (?:price|fare|rate|cost)s?|affordable|deals?|discounts?|coupons?|promo codes?|on sale|bargains?|prices?|pricing|fares?|(?:get|want|need|free|instant) (?:a |an |my )?quotes?|quotes? (?:for|on)|how much (?:is|are|does|do|would|will|for|to)\b(?!\s+(?:time|longer|more|of my|of the (?:meeting|page|doc)))[^?]*\b(?:cost|costs|charge|pay|price)|how much (?:is|are) (?:a|an|the)? ?(?:flight|ticket|hotel|room|night)|cost of (?:a|an|the)?)\b/i,fe=/\b(?:best|top[- ]rated|compare|comparison|vs\.?|versus|recommend(?:ation)?s? for|worth buying|quotes?|where (?:can i|to|should i) (?:buy|get|find|book|rent)|save money on|rates?)\b/i,ge=/\b(?:buy|buying|purchase|shop(?:ping)?|order|book(?:ing)?|rent(?:al|ing)?|subscribe|subscription|plans?|insurance|flights?|hotels?|tickets?|deals?|prices?|costs?|rates?|fares?|movers?|moving company|contractors?|plumbers?|roofers?|repair (?:shop|service)s?|installation|providers?|under\s*[$€£]?\s?\d)\b|[$€£]\s?\d/i,me=/\bbest\s+(?!way|ways|practice|practices|time|approach|method|answer|thing|things|idea|ideas|advice|place to (?:learn|start)|book(?!ing))[\p{L}\d][\p{L}\d+-]*(?:\s+[\p{L}\d][\p{L}\d+-]*){0,3}\s+(?:for|under|below|to buy|in 20\d\d|of 20\d\d)\b/iu,be=/\b(?:stocks?|shares?|share price|ticker|market cap|dividend|crypto(?:currency)?|bitcoin|ethereum|exchange rate)\b|\b(?:my|our) (?:notes?|meetings?|chats?|calendar|emails?|inbox|files?|docs?|documents?|history|library)\b|\b(?:this|the) (?:page|tab|doc(?:ument)?|file|repo(?:sitory)?|code(?:base)?|pr|diff|function|spreadsheet)\b|\b(?:function|exception|stack ?trace|npm|pip|python|javascript|typescript|regex|sql|compile|git|docker|kubernetes|api key|endpoint)\b/i,G=/^\s*(?:(?:hey|hi|ok(?:ay)?|so|please|pls|can you|could you|would you|will you|help me|i need(?: to)?|i want(?: to)?|i'?m looking for|i am looking for|look(?:ing)? for|find(?: me)?|get(?: me)?|show(?: me)?|search(?: for)?|look up|tell me|give me|what(?:'s| is| are)|which(?: is| are)?|where(?:'s| is| are| can i (?:buy|get|find|book))?|who (?:has|offers)|how much (?:is|are|does|do|for)|how much)\s+)+/i,F=/\s+(?:for me|for us|near me|right now|now|today|online|please|pls|this year|in 20\d\d)\s*$|[?!.]+$/i,we=/\b(?:the|a|an|best|cheapest|cheaper|cheap|lowest|affordable|good|great|top[- ]rated|top|most|really|deals?|discounts?|coupons?|bargains?|quotes?|prices?|pricing|costs?|rates?|fares?|offers?|options?|compare|comparison|cost|to buy|on sale)\b/gi;function ye(e,t){let r=String(e||"").replace(G,"").replace(F,"").replace(F,"");return r=r.replace(N," ").replace(/\b(?:from|to|in|near|around|under|below|for|with|between)\s+.*$/i,o=>t.id==="product"||t.id==="plan"?o.replace(/\b(?:in|near|around|from|to)\s+.*$/i,""):""),r=r.replace(D.budget(r)||"\0"," ").replace(we," ").replace(/\b(?:does|do|is|are|a|an|it|cost|costs|20\d\d|i|can|buy|get|where)\b/gi," ").replace(/\s+/g," ").trim(),r.length>=2?r:t.label}function V(e,t){let r=!0;const o=e.replace(/\{(\w+)(\?)?\}/g,(a,c,s)=>(!t[c]&&!s&&(r=!1),t[c]||""));return r?o.replace(/\s+/g," ").trim():""}function $e(e){const t=String(e||"").trim(),r=t.split(/(?<=[.!?])\s+(?=\S)/).map(a=>a.trim()).filter(Boolean),o=r.filter(a=>/\?$/.test(a));return r.length>1&&o.length&&o.length<r.length?o.join(" "):t}function _e(e,{previous:t=null,now:r=Date.now()}={}){const o=String(e||"").trim();if(!o||o.length>400)return null;const a=o.split(/\s+/).length,c=t?.kind==="research"&&t.research?.domain?t.research:null;let s=B.find(p=>p.match&&p.match.test(o))||null;const h=s?s.slots.filter(p=>D[p.id]?.(o)).length:0,d=$e(o),u=!be.test(o)&&a>=2&&(Q.test(d)||fe.test(d)&&(s||ge.test(d))||me.test(d)||s&&(/\b(?:find|search|look|book|get|need)\b/i.test(d)||d===o&&h>=2));if(!u&&c&&a<=14&&(!s||s.id===c.domain)){const p=I(c.domain),l=Object.fromEntries(p.slots.map(k=>[k.id,D[k.id]?.(o)||""]).filter(([,k])=>k));return Object.keys(l).length?J(`${c.question} ${o}`,p,{...c.slots,...l},r,!0,p.subject?"":c.subject):null}if(!u)return null;s||=I("product");const f=Object.fromEntries(s.slots.map(p=>[p.id,D[p.id]?.(o)||""]).filter(([,p])=>p));return J(o,s,f,r,!1)}function J(e,t,r,o,a,c=""){const s=String(new Date(o).getFullYear()),h=c||(t.subject?V(t.subject,r):ye(e,t)),d={...r,subject:h,year:s},u=t.queries.map(l=>V(l,d)).filter(Boolean),f=a?"":e.replace(G,"").replace(F,"").replace(/^(?:a|an|the)\s+/i,"").trim(),p=(f?re(f,{extra:u,max:P.queries*2}):[...new Set(u)]).filter(l=>l.split(/\s+/).length>=2).slice(0,P.queries);return{question:e,domain:t.id,subject:h,slots:r,missing:t.slots.filter(l=>l.required&&!r[l.id]).map(l=>({id:l.id,label:l.label})),queries:p,forms:t.forms,followUp:a}}function ke(e,t=[],{now:r=Date.now()}={}){const o=String(new Date(r).getFullYear()),a=I(e.domain),c=a.slots.map(f=>e.slots?.[f.id]).filter(Boolean).join(" "),s=e.subject,h=[`${s} ${c} price ${o}`,a.forms?`${s} ${c} average cost`:`${s} ${c} cost`,`${s} ${c} comparison`,`${s} ${c}`],d=new Set(t.map(f=>f.toLowerCase().replace(/\s+/g," ").trim())),u=[];for(const f of h){const p=f.replace(/\s+/g," ").trim();p.split(/\s+/).length>=2&&!d.has(p.toLowerCase())&&!u.includes(p)&&u.push(p)}return u.slice(0,3)}function xe(e){if(e&&typeof e=="object"&&Array.isArray(e.results))return{query:e.query||"",engines:e.engines||[],results:e.results.filter(c=>c?.url)};const t=typeof e=="string"?e:typeof e?.text=="string"?e.text:"",r=/^Web search results for "([^"]*)" \(engines: ([^)]*)\)/m.exec(t),o=t.indexOf("Result details:");if(!r||o<0)return{query:r?.[1]||"",engines:[],results:[]};const a=[];for(const c of t.slice(o).split(/\n+---\n+(?=### \[\d+\])/)){const s=/### \[(\d+)\] ([^\n]*)\n<([^>\s]+)>\n\n?([\s\S]*)$/.exec(c);s&&a.push({rank:Number(s[1]),title:s[2].trim(),url:s[3],text:s[4].trim()})}return{query:r[1],engines:r[2].split(/,\s*/).filter(Boolean),results:a}}const X=/^(?:utm_\w+|gclid|fbclid|msclkid|mc_[a-z]+|ref|ref_src|source|campaign|affiliate|aff_id|clickid|irclickid|_ga)$/i;function qe(e){try{const t=new URL(e);for(const r of[...t.searchParams.keys()])X.test(r)&&t.searchParams.delete(r);return t.hash="",t.toString()}catch{return String(e||"")}}function ve(e){try{const t=new URL(e),o=[...t.searchParams.entries()].filter(([a])=>!X.test(a)).sort(([a],[c])=>a.localeCompare(c)).map(([a,c])=>`${a}=${c}`).join("&");return`${t.hostname.replace(/^www\./,"").toLowerCase()}${t.pathname.replace(/\/+$/,"")||"/"}${o?`?${o}`:""}`}catch{return String(e||"")}}function je(e,t=P.passageChars){const r=[];let o="";const a=()=>{const c=o.trim();c.length>=40&&r.push(c),o=""};for(const c of String(e||"").split(/\n\s*\n/)){const s=c.replace(/[ \t]+/g," ").trim();if(s)if(s.length>t){a();let h="";for(const d of s.split(/(?<=[.!?])\s+/))h&&h.length+d.length+1>t&&(o=h,a(),h=""),h=h?`${h} ${d}`:d.slice(0,t);o=h,a()}else o.length+s.length+2>t?(a(),o=s):o=o?`${o}
2
+ ${s}`:s}return a(),r}async function ee(e,t,r,o){const a=new Array(e.length);let c=0;const s=Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;c<e.length;){const h=c++;try{a[h]=await r(e[h],h)}catch{a[h]=null}}});return await(o?Promise.race([Promise.all(s),o]):Promise.all(s)),a}async function Se({ask:e,search:t,read:r=null,rerank:o=null,now:a=()=>Date.now(),until:c=null,limits:s={},onProgress:h=()=>{}}={}){if(!e||typeof t!="function")throw new Error("webResearch: ask and search required");const d={...P,...s},u=a(),f=()=>a()-u>d.ms;let p=!1;const l=c?c.then(()=>{p=!0}):null,k=I(e.domain),q=[],A=[],x=new Map,O=new Set;let v=0,i=null;const g=(S,L)=>{try{h({phase:S,label:L,searches:q.length,pages:x.size,offers:i?.offerCount||0})}catch{}};let b=e.queries.slice(0,d.queries);for(let S=1;S<=d.rounds&&b.length;S++){g("search",`Searching: ${b.map($=>`“${$}”`).join(", ")}`);const L=await ee(b,d.parallel,async $=>xe(await t($)),l);if(b.forEach(($,n)=>{q.push($);const m=L[n];if(!m?.results?.length){v+=1;return}m.engines.forEach(y=>O.add(y));const w=[];m.results.forEach(y=>{const R=ve(y.url);w.push(R);const T=x.get(R),H=String(y.text||y.snippet||"");T?(T.foundBy.push($),H.length>T.text.length&&(T.text=H)):x.set(R,{key:R,url:qe(y.url),title:y.title||y.url,host:le(y.url),text:H,foundBy:[$]})}),A.push(w)}),r&&!p&&!f()){const $=te(A,x,d).filter(n=>n.text.length<400).slice(0,d.read);if($.length){g("read",`Reading ${$.length} page${$.length===1?"":"s"}`);const n=await ee($,d.parallel,m=>r(m.url),l);$.forEach((m,w)=>{const y=n[w],R=typeof y=="string"?y:y?.text;R&&R.length>m.text.length&&(m.text=String(R),y?.title&&(m.title=y.title))})}}if(i=await se({ask:e,d:k,lists:A,pages:x,L:d,rerank:o}),g("decide",Ee(i)),i.enough||p||f()||S===d.rounds)break;b=ke(e,q,{now:u})}i||=await se({ask:e,d:k,lists:A,pages:x,L:d,rerank:null});const E={searches:q.length,failed:v,pages:x.size,sites:new Set([...x.values()].map(S=>S.host)).size,engines:[...O],ms:Math.max(0,a()-u)},j={ask:e,queries:q,...i,stats:E};return{...j,text:Ae(j,d)}}function te(e,t,r){const o=new Map,a=[];for(const{id:c}of W(e)){const s=t.get(c);if(!s?.host)continue;const h=o.get(s.host)||0;if(!(h>=r.perHost)&&(o.set(s.host,h+1),a.push(s),a.length>=r.pages))break}return a}async function se({ask:e,d:t,lists:r,pages:o,L:a,rerank:c}){const s=te(r,o,a),h=new Map(s.map((n,m)=>[n.key,m])),d=[e.subject,...Object.values(e.slots||{}),...t.terms],u=t.id!=="product"||Q.test(e.question)||!!e.slots?.budget||/\b(?:cheap|costs?|deals?|quotes?|rates?)\b|[$€£]/i.test(e.question),f=[];for(const n of s)je(n.text,a.passageChars).forEach((m,w)=>f.push({id:`${n.key}#${w}`,key:n.key,url:n.url,host:n.host,title:n.title,text:m}));const p=`${d.join(" ")}${u?" price cost per month":""}`,l=f.length?ne(oe(f),p).map(n=>n.id):[],k=[...f].sort((n,m)=>h.get(n.key)-h.get(m.key)).map(n=>n.id),q=u?f.filter(n=>/[$€£]\s?\d|\d\s?(?:€|£|USD|EUR|GBP)\b/.test(n.text)).map(n=>n.id):[],A=[l,k,...q.length?[q]:[]];if(typeof c=="function"&&l.length){const n=l.slice(0,40).map(m=>f.find(w=>w.id===m));try{const m=await c(e.question,n.map(w=>w.text));Array.isArray(m)&&m.length===n.length&&A.push(n.map((w,y)=>({id:w.id,s:Number(m[y])||0})).sort((w,y)=>y.s-w.s).map(w=>w.id))}catch{}}const x=new Set(l),O=new Map(f.map(n=>[n.id,n])),v=new Map,i=[];for(const{id:n}of W(A)){if(!x.has(n))continue;const m=O.get(n),w=v.get(m.host)||0;if(!(w>=2)&&(v.set(m.host,w+1),i.push(m),i.length>=a.passages))break}const g=u?ie(s.flatMap(n=>ae(n.text,{url:n.url,title:n.title,terms:d,max:a.offers}))):{basis:"",currency:"",ranked:[],floors:[],other:[],averages:[]},b=[];for(const n of s){const m=t.forms||/\bquote\b/i.test(e.question)?ce(n.text):"";if(m&&!b.some(w=>w.host===n.host)&&b.push({url:n.url,title:n.title,host:n.host,cta:m}),b.length>=a.forms)break}const E=g.ranked.length+g.floors.length,j=new Set([...g.ranked,...g.floors].map(n=>n.host)).size,S=g.ranked.some(n=>n.seenOn>=2),L=new Set(i.map(n=>n.host)).size,$=u?E>=3&&j>=2||S&&g.ranked.length>=2:i.length>=4&&L>=3;return{pages:s,passages:i,offers:g,forms:b,enough:$,offerCount:E,wantPrices:u}}function Ee(e){const t=[`${e.pages.length} page${e.pages.length===1?"":"s"}`];return e.wantPrices&&t.push(`${e.offerCount} price${e.offerCount===1?"":"s"}`),e.forms.length&&t.push(`${e.forms.length} quote form${e.forms.length===1?"":"s"}`),t.join(" · ")}const _=(e,t)=>{const r=String(e||"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}…`:r};function Ae(e,t={}){const r={...P,...t};if(!e?.pages?.length)return"";const o=new Map,a=i=>(o.has(i.url)||o.set(i.url,{n:o.size+1,title:i.title||i.host||i.url,url:i.url}),o.get(i.url).n),c=i=>`[${a(i)}](${U(i.url)})`,{offers:s,forms:h,passages:d,ask:u,stats:f}=e,p=I(u.domain),l=[],k=`${f.searches} search${f.searches===1?"":"es"}, ${f.pages} page${f.pages===1?"":"s"} from ${f.sites} site${f.sites===1?"":"s"}, ${(f.ms/1e3).toFixed(1)} s`;e.wantPrices&&u.browse?l.push(`(FIRST PASS from web search for the question below — ${k}. These are listing and article pages, not live quotes. A price answers the question only when its page says it is for THIS request (the route or item, and the dates asked); a 12-month low, an average or a deal advertised for other dates does not. When nothing below is that, get it live before answering: open the booking or comparison site in your own tab (page open_tab), enter the request, read the results, and compare at least two sites. Cite with the markdown links given and with the pages you open. Do not repeat these searches.)`):l.push(`(ALREADY RESEARCHED on the web for the question below — ${k}. Answer from this and cite with the markdown links given. `+(e.wantPrices?'State ONLY prices listed under "Prices found" — each was read on the linked page — and call a "from" price an advertised minimum, not a quote. ':"")+"Do not repeat these searches; search again only for something this does not cover.)"),l.push(""),l.push(`Question: ${_(u.question,200)}`);const q=p.slots.filter(i=>u.slots?.[i.id]).map(i=>`${i.id} = ${u.slots[i.id]}`);if(l.push(`Looking for: ${u.subject}${p.id!=="product"?` (${p.label})`:""}${q.length?` · known: ${q.join(" · ")}`:""}`),u.missing?.length&&u.browse?l.push(`Not given: ${u.missing.map(i=>i.label).join("; ")}. Use what the conversation, the user's memory or the pages below point to (a page searched from a city says where they are), say it is an assumption, and go on — ask only when nothing points anywhere. A vague time ("the holidays") is the usual span; say which dates you took.`):u.missing?.length&&l.push(`Missing for a personalised price: ${u.missing.map(i=>i.label).join("; ")}. Ask the user for these before filling any quote form — say what the prices below are based on meanwhile.`),e.wantPrices){l.push("");const i=s.basis==="month"?"per month":M(s.basis);if(s.ranked.length){l.push(`Prices found (cheapest first, ${i}${s.currency?`, ${s.currency}`:""}):`);const g=[];for(const b of s.ranked){const E=g.find(j=>j.o.currency===b.currency&&Math.round(j.o.value*100)===Math.round(b.value*100));E?E.also.some(j=>j.url===b.url)||E.also.push(b):g.push({o:b,also:[]})}g.slice(0,r.offers).forEach(({o:b,also:E},j)=>{const S=[b,...E].map(c).filter((L,$,n)=>n.indexOf(L)===$).join(" ");l.push(`${j+1}. ${Z(b.value,b.currency,s.basis)}${b.converted?` (${b.raw} ${M(b.basis)})`:""} — “${_(b.quote,160)}” ${S}${b.seenOn>1?` · stated by ${b.seenOn} sites`:""}`)})}else l.push(u.browse?"Prices found: none stated plainly on the pages read — do not invent one; get them live, as above.":"Prices found: none stated plainly on the pages read — do not invent one; say so and offer to get a quote.");s.floors.length&&l.push(`Advertised minimums ("from" — not a quote for this person): ${s.floors.slice(0,4).map(g=>`${Z(g.value,g.currency,s.basis)} ${c(g)}`).join(" · ")}`),s.other.length&&l.push(`On another basis or currency (not comparable with the list above): ${s.other.slice(0,4).map(g=>`${g.raw} ${M(g.basis)} ${c(g)}`).join(" · ")}`),s.averages.length&&l.push(`Averages (context, not offers): ${s.averages.slice(0,3).map(g=>`${g.raw} ${M(g.basis)} — “${_(g.quote,100)}” ${c(g)}`).join(" · ")}`)}if(h.length){l.push(""),l.push("Quote forms (an exact price needs the user's details — you can fill these in the user's browser with the page tools, asking them for anything missing; NEVER press a submit/continue/pay button without the user's OK):");for(const i of h)l.push(`- ${i.host}: “${i.cta}” ${c(i)}`)}const A=d.map(i=>`[${a(i)}] ${i.title?`${_(i.title,80)} — `:""}${i.text}`);l.push(""),l.push("Sources:");for(const i of o.values())l.push(`[${i.n}] [${_(i.title,90)}](${U(i.url)})`);let x=l.join(`
3
+ `);const O=r.briefChars-x.length-200;let v="";for(const i of A){if(v.length+i.length+2>O)break;v+=`${v?`
4
4
 
5
- `:""}${a}`}return v&&(k+=`
5
+ `:""}${i}`}return v&&(x+=`
6
6
 
7
- ${ue(v,{source:"web search results"})}`),k}function Ae(e,t){return e?.tool==="find"?{tool:"find",input:{action:"web_search",args:{query:t}}}:{tool:e?.tool||"web_search",input:{query:t}}}async function _e(e,{execute:t,read:r=null,rerank:o=null,now:l=()=>Date.now(),until:i=null,onProgress:s=()=>{},limits:d={}}={}){const p=async u=>{const b=Ae(e,u),c=await t(b.tool,b.input,{prefetched:!0,research:!0}),x=typeof c=="string"?c:c?.text;if(!x||/^(?:error\b|\w+ failed\b|\{"error")/i.test(x))throw new Error("search failed");return x},h=await je({ask:e.research,search:p,read:r,rerank:o,now:l,until:i,limits:d,onProgress:s});return{text:h.text,result:h}}export{P as WEB_RESEARCH_LIMITS,B as WEB_TASK_DOMAINS,xe as cleanUrl,qe as pageKey,ke as parseSearchText,ve as passagesOf,$e as refineQueries,Ie as researchAsk,Ee as researchBrief,Ae as researchCall,_e as runResearch,je as webResearch};
7
+ ${ue(v,{source:"web search results"})}`),x}function Re(e,t){return e?.tool==="find"?{tool:"find",input:{action:"web_search",args:{query:t}}}:{tool:e?.tool||"web_search",input:{query:t}}}async function Te(e,{execute:t,read:r=null,rerank:o=null,now:a=()=>Date.now(),until:c=null,onProgress:s=()=>{},limits:h={}}={}){const d=async f=>{const p=Re(e,f),l=await t(p.tool,p.input,{prefetched:!0,research:!0}),k=typeof l=="string"?l:l?.text;if(!k||/^(?:error\b|\w+ failed\b|\{"error")/i.test(k))throw new Error("search failed");return k},u=await Se({ask:e.research,search:d,read:r,rerank:o,now:a,until:c,limits:h,onProgress:s});return{text:u.text,result:u}}export{P as WEB_RESEARCH_LIMITS,B as WEB_TASK_DOMAINS,$e as askingPart,qe as cleanUrl,ve as pageKey,xe as parseSearchText,je as passagesOf,ke as refineQueries,_e as researchAsk,Ae as researchBrief,Re as researchCall,Te as runResearch,Se as webResearch};