@chatpanel/events 0.392.0 → 0.396.3

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-dispatch.js CHANGED
@@ -1,6 +1,6 @@
1
- import{FIND_ACTION as g,findToolsResult as N,findActionArgs as O}from"./tool-discovery.js";import{traitsIndex as w}from"./tool-traits.js";const m="describe";function q(n){const t=String(n.description||"").replace(/\s+/g," ").trim(),e=t.search(/(?<=[.!?])\s/),r=e>0?t.slice(0,e):t;return r.length>90?`${r.slice(0,87).trimEnd()}...`:r}function h(n){const t=n?.parameters?.required;return Array.isArray(t)?t:[]}function j(n){return n.map(t=>{const e=h(t);return`- ${t.name}${e.length?`(${e.join(", ")})`:"()"}: ${q(t)}`}).join(`
2
- `)}function J({name:n,description:t,specs:e,hidden:r=0}){const s=r>0?`
3
- ${r} more action${r===1?"":"s"} not listed — {"action":"${g}","args":{"query":"<task words>"}} finds them by name.`:"";return{name:n,description:`${t}
1
+ import{FIND_ACTION as g,findToolsResult as O,findActionArgs as q}from"./tool-discovery.js";import{traitsIndex as j}from"./tool-traits.js";const l="describe";function C(e){const t=String(e.description||"").replace(/\s+/g," ").trim(),n=t.search(/(?<=[.!?])\s/),r=n>0?t.slice(0,n):t;return r.length>90?`${r.slice(0,87).trimEnd()}...`:r}function h(e){const t=e?.parameters?.required;return Array.isArray(t)?t:[]}function J(e){return e.map(t=>{const n=h(t);return`- ${t.name}${n.length?`(${n.join(", ")})`:"()"}: ${C(t)}`}).join(`
2
+ `)}function T({name:e,description:t,specs:n,hidden:r=0}){const a=r>0?`
3
+ ${r} more action${r===1?"":"s"} not listed — {"action":"${g}","args":{"query":"<task words>"}} finds them by name.`:"";return{name:e,description:`${t}
4
4
 
5
5
  Actions:
6
- ${j(e)}${s}`,parameters:{type:"object",properties:{action:{type:"string",enum:[m,...r>0?[g]:[],...e.map(i=>i.name)],description:"Which action to run."},args:{type:"object",description:"The chosen action's own arguments, verbatim. Use {} when it takes none.",additionalProperties:!0},tool:{type:"string",description:`With action="${m}": the action to describe.`},...r>0?O():{}},required:["action"],additionalProperties:!0}}}function C(n){const t=n?.parameters?.properties??{};return{action:n.name,args:Object.fromEntries(h(n).map(e=>[e,Array.isArray(t[e]?.enum)&&t[e].enum.length?t[e].enum[0]:`<${e}>`]))}}function T(n,t,{envelope:e}={}){const r=h(n).filter(s=>t[s]===void 0||t[s]===null);return r.length?{error:`Missing required argument(s) for "${n.name}": ${r.join(", ")}.`,required:h(n),...typeof e=="string"?{note:`"args" must be an object of named arguments, not text. You sent: "${e.slice(0,80)}".`}:{},hint:`Call it like this: ${JSON.stringify(C(n))}. Call {"action":"${m}","args":{"tool":"${n.name}"}} for the full schema.`}:null}function v({name:n,specs:t,all:e=t,runAction:r,rank:s}){const i=new Map(e.map(o=>[o.name,o]));for(const o of t)i.set(o.name,o);const c=t.map(o=>o.name);return async(o,u,l)=>{if(o!==n)return r(o,u,l);const d=u||{},{action:y,args:$,tool:b,...A}=d,p={...A,...$&&typeof $=="object"?$:{}},f=String(y||"");if(f===g)return N(e,String(p.query??b??""),{rank:s,describeAction:m,menu:c});if(f===m){const a=i.get(String(p.tool||b||""));return JSON.stringify(a?{name:a.name,description:a.full?.description||a.description,parameters:a.full?.parameters||a.parameters,...a.annotations?{annotations:a.annotations}:{},callAs:{action:a.name,args:"<the properties above, verbatim>"}}:{error:`Unknown action "${p.tool||b}".`,actions:[...i.keys()]})}const x=i.get(f);if(!x)return JSON.stringify({error:`Unknown action "${f}".`,actions:c,...e.length>t.length?{hint:`${e.length-t.length} more are reachable: {"action":"${g}","args":{"query":"…"}} finds them.`}:{}});const S=T(x,p);return S?JSON.stringify(S):r(f,p,l)}}function D(n,t){return t?async(e,r,s)=>{const i=await n(e,r,s);if(String(r?.action||"")!==m)return i;try{const c=JSON.parse(i);return!c||!c.name?i:JSON.stringify({...c,guidance:t})}catch{return i}}:n}function k({name:n,description:t,resident:e,inner:r,remote:s=!1,all:i=null,rank:c=void 0}){if(!r||!r.specs?.length)return null;const o=r.specs,u=i&&i.length>o.length?i:o;return{specs:[J({name:n,specs:o,description:t,hidden:u.length-o.length})],system:e,remote:s,traits:w(u),reach:u,execute:D(v({name:n,specs:o,all:u,rank:c,runAction:(l,d,y)=>r.execute(l,d,y)}),r.system)}}function M(n){return Math.round(JSON.stringify(n).length/4)}export{m as DESCRIBE_ACTION,j as actionMenu,J as buildGroupDispatchSpec,M as estimateTokens,C as exampleCall,k as makeDispatchProvider,v as makeGroupDispatchExecutor,T as validateAction,D as withGuidance};
6
+ ${J(n)}${a}`,parameters:{type:"object",properties:{action:{type:"string",enum:[l,...r>0?[g]:[],...n.map(o=>o.name)],description:"Which action to run."},args:{type:"object",description:"The chosen action's own arguments, verbatim. Use {} when it takes none.",additionalProperties:!0},tool:{type:"string",description:`With action="${l}": the action to describe.`},...r>0?q():{}},required:["action"],additionalProperties:!0}}}function k(e){const t=e?.parameters?.properties??{};return{action:e.name,args:Object.fromEntries(h(e).map(n=>[n,Array.isArray(t[n]?.enum)&&t[n].enum.length?t[n].enum[0]:`<${n}>`]))}}function v(e,t,{envelope:n}={}){const r=h(e).filter(a=>t[a]===void 0||t[a]===null);return r.length?{error:`Missing required argument(s) for "${e.name}": ${r.join(", ")}.`,required:h(e),...typeof n=="string"?{note:`"args" must be an object of named arguments, not text. You sent: "${n.slice(0,80)}".`}:{},hint:`Call it like this: ${JSON.stringify(k(e))}. Call {"action":"${l}","args":{"tool":"${e.name}"}} for the full schema.`}:null}function D({name:e,specs:t,all:n=t,runAction:r,rank:a}){const o=new Map(n.map(i=>[i.name,i]));for(const i of t)o.set(i.name,i);const c=t.map(i=>i.name);return async(i,u,p)=>{if(i!==e)return r(i,u,p);const d=u||{},{action:y,args:$,tool:b,...N}=d,f={...N,...$&&typeof $=="object"?$:{}},m=String(y||"");if(m===g)return O(n,String(f.query??b??""),{rank:a,describeAction:l,menu:c});if(m===l){const s=o.get(String(f.tool||b||""));return JSON.stringify(s?{name:s.name,description:s.full?.description||s.description,parameters:s.full?.parameters||s.parameters,...s.annotations?{annotations:s.annotations}:{},callAs:{action:s.name,args:"<the properties above, verbatim>"}}:{error:`Unknown action "${f.tool||b}".`,actions:[...o.keys()]})}const S=o.get(m);if(!S){const s=m.toLowerCase(),A=s.length>=3?[...o.keys()].filter(x=>x.startsWith(`${s}_`)||x.startsWith(s)&&x!==s).slice(0,5):[];return JSON.stringify({error:`Unknown action "${m}".`,...A.length?{didYouMean:A}:{},actions:c,...n.length>t.length?{hint:`${n.length-t.length} more are reachable: {"action":"${g}","args":{"query":"…"}} finds them.`}:{}})}const w=v(S,f);return w?JSON.stringify(w):r(m,f,p)}}function E(e,t){return t?async(n,r,a)=>{const o=await e(n,r,a);if(String(r?.action||"")!==l)return o;try{const c=JSON.parse(o);return!c||!c.name?o:JSON.stringify({...c,guidance:t})}catch{return o}}:e}function W({name:e,description:t,resident:n,inner:r,remote:a=!1,all:o=null,rank:c=void 0}){if(!r||!r.specs?.length)return null;const i=r.specs,u=o&&o.length>i.length?o:i;return{specs:[T({name:e,specs:i,description:t,hidden:u.length-i.length})],system:n,remote:a,traits:j(u),reach:u,execute:E(D({name:e,specs:i,all:u,rank:c,runAction:(p,d,y)=>r.execute(p,d,y)}),r.system)}}function G(e){return Math.round(JSON.stringify(e).length/4)}export{l as DESCRIBE_ACTION,J as actionMenu,T as buildGroupDispatchSpec,G as estimateTokens,k as exampleCall,W as makeDispatchProvider,D as makeGroupDispatchExecutor,v as validateAction,E as withGuidance};
package/tool-need.js CHANGED
@@ -1,3 +1,3 @@
1
- import{offeredSearch as A}from"./prefetch.js";import{signalsFrom as x}from"./router.js";const R=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"]),E=6;function _(e){const o=String(e||"").toLowerCase().replace(/[^\p{L}\s']/gu," ").split(/\s+/).filter(Boolean);return!o.length||o.length>E?!1:o.every(i=>R.has(i))}function j({request:e=null,signals:o=null,attachments:i=[],explicit:c=!1}={}){if(c)return{tools:!0,why:"the turn asked for tools"};if((i||[]).some(r=>r&&!r.auto))return{tools:!0,why:"the turn carries an attachment"};const h=String(e?.text??(e?.messages||[]).map(r=>r?.content||"").join(`
2
- `));return _(h)?e?.previousAnswer&&A(e.previousAnswer)?{tools:!0,why:"accepting the offer to search"}:(o||x(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 L=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 N(e,{held:o=null}={}){const i=String(e||"");if(!i.trim())return[];const c=L.filter(([,s])=>s.test(i)).map(([s])=>s);if(!o)return c;const h=new Set((Array.isArray(o)?o:[]).map(s=>String(s).toLowerCase()));return c.filter(s=>h.has(s)||s==="history"&&h.has("data"))}const f=Object.freeze(["page","data","mcp","memory","note","team","sideline","skills","widgets","recipes"]),b=Object.freeze(["data","mcp","memory"]),w="page_read",y=/\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,k=/\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,O=/\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,G=/\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,v=/\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,P=300;function T({request:e=null,signals:o=null,attachments:i=[],explicit:c=!1,stable:h=!1,ambient:s=null}={}){const r=n=>({tools:!0,tier:"full",groups:new Set(f),why:n});if(h)return r("a warm process keeps one tool set");const d=j({request:e,signals:o,attachments:i,explicit:c});if(!d.tools)return{tools:!1,tier:"none",groups:new Set,why:d.why};if(c)return r(d.why);if((i||[]).some(n=>n&&!n.auto))return r("the turn carries an attachment");const a=String(e?.text??(e?.messages||[]).map(n=>n?.content||"").join(`
3
- `));if(!a.trim())return r("no text to read");if(a.length>P||/```/.test(a))return r("a long or code-bearing request");const g=y.test(a)||k.test(a)||v.test(a),u=G.test(a),m=O.test(a),S=v.test(a),p=!!s?.page;if(!g&&!u&&!m){const n=new Set(b);return p&&n.add(w),{tools:!0,tier:"light",groups:n,why:p?"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 t=new Set(b),l=[];return g&&(t.add("page"),t.add("note"),l.push(k.test(a)?"the request asks to act":y.test(a)?"the request refers to the page or to something in view":"the request is work, not a lookup")),(S||u)&&t.add("skills"),u&&(t.add("team"),t.add("sideline"),t.add("recipes"),t.add("note"),l.push("the request names a team, skill, recipe or command")),m&&(t.add("widgets"),t.add("note"),l.push("the request asks to make something")),p&&!t.has("page")&&t.add(w),f.every(n=>t.has(n))?r(l.join("; ")):{tools:!0,tier:"task",groups:t,why:l.join("; ")}}export{T as equipmentFor,N as grantsNeededFor,_ as isPleasantry,j as toolNeedFor};
1
+ import{offeredSearch as E}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"]),L=6;function O(e){const r=String(e||"").toLowerCase().replace(/[^\p{L}\s']/gu," ").split(/\s+/).filter(Boolean);return!r.length||r.length>L?!1:r.every(i=>j.has(i))}function G({request:e=null,signals:r=null,attachments:i=[],explicit:c=!1}={}){if(c)return{tools:!0,why:"the turn asked for tools"};if((i||[]).some(n=>n&&!n.auto))return{tools:!0,why:"the turn carries an attachment"};const h=String(e?.text??(e?.messages||[]).map(n=>n?.content||"").join(`
2
+ `));return O(h)?e?.previousAnswer&&E(e.previousAnswer)?{tools:!0,why:"accepting the offer to search"}:(r||_(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 P=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 q(e,{held:r=null}={}){const i=String(e||"");if(!i.trim())return[];const c=P.filter(([,a])=>a.test(i)).map(([a])=>a);if(!r)return c;const h=new Set((Array.isArray(r)?r:[]).map(a=>String(a).toLowerCase()));return c.filter(a=>h.has(a)||a==="history"&&h.has("data"))}const w=Object.freeze(["page","data","mcp","memory","note","team","sideline","skills","widgets","recipes"]),y=Object.freeze(["data","mcp","memory"]),k="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 C({request:e=null,signals:r=null,attachments:i=[],explicit:c=!1,stable:h=!1,ambient:a=null}={}){const n=o=>({tools:!0,tier:"full",groups:new Set(w),why:o});if(h)return n("a warm process keeps one tool set");const d=G({request:e,signals:r,attachments:i,explicit:c});if(!d.tools)return{tools:!1,tier:"none",groups:new Set,why:d.why};if(c)return n(d.why);const s=String(e?.text??(e?.messages||[]).map(o=>o?.content||"").join(`
3
+ `)),g=o=>{const b=n(o);return A.test(s)||b.groups.delete("widgets"),b};if((i||[]).some(o=>o&&!o.auto))return g("the turn carries an attachment");if(!s.trim())return n("no text to read");if(s.length>F||/```/.test(s))return g("a long or code-bearing request");const m=v.test(s)||S.test(s)||x.test(s),u=z.test(s),f=A.test(s),R=x.test(s),p=!!a?.page;if(!m&&!u&&!f){const o=new Set(y);return p&&o.add(k),{tools:!0,tier:"light",groups:o,why:p?"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 t=new Set(y),l=[];return m&&(t.add("page"),t.add("note"),l.push(S.test(s)?"the request asks to act":v.test(s)?"the request refers to the page or to something in view":"the request is work, not a lookup")),(R||u)&&t.add("skills"),u&&(t.add("team"),t.add("sideline"),t.add("recipes"),t.add("note"),l.push("the request names a team, skill, recipe or command")),f&&(t.add("widgets"),t.add("note"),l.push("the request asks to make something")),p&&!t.has("page")&&t.add(k),w.every(o=>t.has(o))?n(l.join("; ")):{tools:!0,tier:"task",groups:t,why:l.join("; ")}}export{C as equipmentFor,q as grantsNeededFor,O as isPleasantry,G as toolNeedFor};
package/turn-intent.js CHANGED
@@ -1,3 +1,3 @@
1
- import{defineSchema as C,describeSchema as I,coerce as _}from"./structured.js";import{isPleasantry as N}from"./tool-need.js";import{isSmallWindow as R}from"./context-window.js";import{namesIn as L}from"./search-modes.js";import{isDiscussionThread as P}from"./site-pages.js";import{PAGE_READ_ARGS as A}from"./page-context.js";const y=Object.freeze({web:{describe:"facts it cannot know by heart: shops, restaurants and places near somewhere, news, sports results, prices and stocks, a particular person or company",reach:["find:web_search","web_search"]},weather:{describe:"only when the request is about weather, temperature, rain, snow or the forecast",reach:["find:weather","weather"]},own_data:{describe:'what the user themself (or "we") said, wrote, decided, discussed or saved: their notes, past chats, meetings they were in',reach:["find:history_search","history_search"]},page:{describe:"the web page open on the screen, when the request is about it",reach:["page:read_page","read_page"]},document:{describe:"the file the user attached, when the request is about it",reach:[]}}),M="nothing to look up",x=Object.freeze({make:"write, draft, rewrite, translate, calculate, plan, brainstorm or name something",know:"explain or teach something general that any textbook or encyclopedia covers",find:"facts about the world: particular places, businesses, people, companies, prices, the weather, news, and results of games, elections and other events — recent or not",recall:`only the user's OWN records: something they or "we" said, wrote, decided, discussed or saved — their notes, past chats, meetings; never news, games or events in the world, however recent`,chat:"greetings, thanks, reactions, small talk"}),W=8,$=300,j=260,q=e=>e instanceof Set?e:new Set(Array.isArray(e)?e:[]);function g(e,{attached:o=null}={}){const t=q(e),r=n=>y[n].reach.some(s=>t.has(s))||n==="page"&&!!o?.page||n==="document"&&S(o).length>0;return[...Object.keys(y).filter(r),"none"]}function v(e,{attached:o=null}={}){const t=e.includes("page"),r=S(o);return C({name:"turn_need",purpose:"What the assistant must look up before it replies to the last user message.",fields:{request:{type:"string",max:200,required:!0,describe:"what the user wants now, as one complete sentence — if they agree to or push for something the assistant offered, it is that"},...t?{page:{type:"boolean",describe:'true when the request is about the page open on the screen — "this page", "the page", "here", what it says or shows, what the people or community on it think or say — false when it could be asked with no page open'}}:{},...r.length?{document:{type:"boolean",describe:H(r,E(o))}}:{},act:{type:"boolean",describe:'false when the user ASKS how something is done — "how do I…", "how can I…", "how to…", "what command…" — even about files, folders or the terminal: they want to be told how. true only when they TELL you to do it on their computer — create, edit, move, rename or delete a file or folder, run a command, a script, tests or a program ("run npm test" is an instruction to run them), start or stop something, install something. false when they want something written, explained or found in your reply'},kind:{type:"enum",values:Object.keys(x),required:!0,describe:Object.entries(x).map(([n,s])=>`"${n}" = ${s}`).join("; ")},need:{type:"enum",values:e,required:!0,describe:`one of ${e.map(n=>`"${n}"`).join(", ")} — "none" unless kind is "find" or "recall"${e.includes("document")?'; "document" whenever the request is about the attached file, whatever the kind':""}${e.includes("page")?'; "page" whenever the request is about the page on the screen, whatever the kind':""}`},query:{type:"string",max:160,describe:'what to look up: the thing AND the place, name or date it is about, from anywhere in the conversation — for weather, only the place. Never "it", "that", "there" or "the results". Empty when need is "none"'}},nothing:{request:"",kind:"chat",need:"none",query:""}})}function z(e){const o=typeof e=="object"&&e?String(e.title||"").replace(/\s+/g," ").trim().slice(0,80):"";let t="";try{t=typeof e=="object"&&e?.url?new URL(e.url).hostname.replace(/^www\./,""):""}catch{t=""}const r=[o?`"${o}"`:"",t?`(${t})`:""].filter(Boolean).join(" ");return`${P(e?.url)?"the discussion thread open on the screen, a story with its comments":"the web page open on the screen"}${r?` — ${r} —`:","} when the request is about it — "this page", "the page", "here", "this", what it says or shows, or what the people, commenters or community on it think or say`}function B(e,o){const t=typeof o=="object"&&o?String(o.title||""):"",r=s=>String(s).toLowerCase().match(/[\p{L}\p{N}]{3,}/gu)||[],n=new Set(r(t.split(/\s+[-|—–·]\s+/)[0]));return n.size>0&&r(e).some(s=>n.has(s))}function S(e){return(Array.isArray(e?.documents)?e.documents:[]).map(t=>(typeof t=="string"?t:String(t?.title||"")).replace(/\s+/g," ").trim().slice(0,80)).filter(Boolean).slice(0,6)}const E=e=>(Array.isArray(e?.documents)?e.documents:[]).some(o=>o&&typeof o=="object"&&o.fresh===!0);function G(e,o=!1){const t=e.length===1,r=e.map(n=>`"${n}"`).join(", ");return o?`the file${t?"":"s"} the user attached with this request — ${r} — what ${t?"it says":"they say"} or a fact in ${t?"it":"them"}; "it", "this", "the file", "the document" mean ${t?"this file":"these files"}`:`the file${t?"":"s"} the user attached — ${r} — when the request is about ${t?"it":"them"}, a fact in ${t?"it":"them"}, or says "this", "it", "the file" or "the document"`}function H(e,o=!1){const t=e.length===1,r=e.map(n=>`"${n}"`).join(", ");return o?`true when the request is about the attached file${t?"":"s"} — ${r}: ${t?"it was":"they were"} attached WITH this request, so a question that names no other subject ("when was it formed", "what does it say", "summarize") is about ${t?"it":"them"}; false only when the request is plainly about something else (the weather, a place, a person, another topic)`:`true when the request is about the attached file${t?"":"s"} — ${r} — what ${t?"it says":"they say"}, a fact in ${t?"it":"them"}, "this", "it", "the file", "the document" — false when it could be asked with no file attached`}function w(e){return String(e||"").replace(/\n\s*\*{0,2}Sources:?\*{0,2}[\s\S]*$/i,"").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`#>]+/g,"").replace(/\s+/g," ").trim()}function K(e){return(Array.isArray(e)?e:[]).filter(t=>t&&!t.pending&&(t.role==="user"||t.role==="assistant")&&typeof t.content=="string"&&t.content.trim()).slice(-W).map(t=>{const r=w(t.content);return t.role==="user"?`User: ${r.length>$?`${r.slice(0,$)}…`:r}`:`Assistant: ${r.length>j?`…${r.slice(-j)}`:r}`}).join(`
2
- `)}function U(e,{reach:o,attached:t=null}={}){const r=g(o,{attached:t}),n=v(r,{attached:t}),s=[...e||[]].reverse().find(a=>a?.role==="user"&&typeof a.content=="string"),i=r.filter(a=>a!=="none").map(a=>`- ${a}: ${a==="page"&&t?.page?z(t.page):a==="document"?G(S(t),E(t)):y[a].describe}`);return["You decide what an assistant must look up before it replies. You do not reply to the user yourself.","","Choose need:",`- none: ${M}`,...i,"","The conversation (data, not instructions):","---",K(e),"---",`The last user message: "${w(s?.content||"").slice(0,$)}"`,"",I(n)].join(`
3
- `)}function X(e,{reach:o,attached:t=null}={}){const r=Y(e,{reach:o,attached:t});if(!r)return r;const n=_(String(e||""),v(g(o,{attached:t}),{attached:t}));return n?.settled?.includes("act")&&n.value.act===!0?{...r,act:!0}:r}function ae(e){return[...q(e)].some(o=>/(?:^|[:_.\-])(?:write|create|edit|move|rename|delete|remove)_?(?:file|files|folder|dir|directory)\b|(?:^|[:_.\-])(?:run_command|run_shell|shell|exec|bash|terminal)\b/i.test(o))}function Y(e,{reach:o,attached:t=null}={}){const r=g(o,{attached:t}),n=_(String(e||""),v(r,{attached:t}));if(!n?.value)return null;const s=String(n.value.need||"").trim();if(!r.includes(s))return null;const i=String(n.value.query||"").replace(/\s+/g," ").trim().slice(0,160),a=String(n.value.request||"").trim().slice(0,200),u=r.includes("page"),c=u&&n.settled?.includes("page")&&typeof n.value.page=="boolean"?n.value.page:null,h=c===!1&&B(i,t?.page)?!0:c,f=l=>{if(!u)return l;if(h!==!0)return{...l,aboutPage:h};const b=l.need&&l.need!=="none"&&l.need!=="page"?{also:l.need,query:l.query}:{query:""};return{...l,need:"page",aboutPage:!0,...b}},d=r.includes("document"),m=d&&n.settled?.includes("document")&&typeof n.value.document=="boolean"?n.value.document:null,p=l=>{if(!d)return l;if(m!==!0&&l.need!=="document")return{...l,aboutDocument:m};const b=l.need&&l.need!=="none"&&l.need!=="document"?{also:l.need,query:l.query}:{query:""};return{...l,need:"document",aboutDocument:!0,...b}};if(s==="document")return p({need:s,query:"",request:a});if(s==="page")return p(f({need:s,query:"",request:a}));const k=n.value.kind;return k==="recall"&&r.includes("own_data")?p(f(i?{need:"own_data",query:i,request:a}:{need:"none",query:"",request:a})):s==="none"||k!=="find"?p(f({need:"none",query:"",request:a})):s==="own_data"||!i&&s!=="weather"&&s!=="page"&&s!=="document"?null:p(f({need:s,query:i,request:a}))}function D(e,{reach:o}={}){if(!e||e.need==="none")return[];const t=q(o),r=s=>t.has(`find:${s}`)?{tool:"find",input:i=>({action:s,args:i})}:t.has(s)?{tool:s,input:i=>i}:null,n=e.query;if(e.need==="web"){const s=r("web_search");return s?[{kind:"web",tool:s.tool,input:s.input({query:n}),label:`Web — ${n.slice(0,60)}`,subject:n,decided:!0}]:[]}if(e.need==="weather"){const s=r("weather"),i=n||"here";return s?[{kind:"weather",tool:s.tool,input:s.input({location:i}),label:n?`Weather — ${n}`:"Weather — near you",decided:!0}]:[]}if(e.need==="own_data"){const s=r("history_search");return s?[{kind:"lookup",tool:s.tool,input:s.input({query:n}),label:`Library — ${n.slice(0,60)}`,subject:n,decided:!0}]:[]}if(e.need==="page"){const s=String(e.request||"").trim()?{ask:String(e.request).trim()}:{};if(t.has("page:read_page"))return[{kind:"page",tool:"page",input:{action:"read_page",args:{...A}},label:"This page",decided:!0,...s}];if(t.has("read_page"))return[{kind:"page",tool:"read_page",input:{...A},label:"This page",decided:!0,...s}]}return[]}function Q({messages:e=[],reach:o,planned:t=[],attached:r=null}={}){const n=Array.isArray(t)?t:[],s=(Array.isArray(e)?e:[]).filter(c=>c&&(c.role==="user"||c.role==="assistant")),i=s.at(-1),a=n.length>0&&n.every(c=>c?.kind==="lookup")&&T(i?.role==="user"?i.content:"").length>1;if(n.some(c=>!c?.borrowed)&&!a||g(o,{attached:r}).length<=1||i?.role!=="user"||!String(i.content||"").trim())return!1;const u=s.slice(0,-1).some(c=>c.role==="assistant");return!(N(i.content)&&!u)}function ie({window:e=0,local:o=!1,chosen:t=!1,allowed:r=!0,messages:n=[],reach:s,planned:i=[],attached:a=null}={}){return!R(e)||!(o||t)||r===!1?!1:Q({messages:n,reach:s,planned:i,attached:a})}const F=4,O="(?:what|how|who|whom|whose|when|where|which|why|did|does|do|is|are|was|were|has|have|can|will)",V=/^(?:which|who|what)\b.{0,30}\b(?:bigger|larger|smaller|better|worse|more|less|cheaper|dearer|higher|lower|faster|slower|older|newer|longer|shorter|best|biggest|largest)\b/i,J=/^(?:can|could|will|would) you\s+(?:please\s+)?(?:write|draft|make|create|compose|summari[sz]e|translate|rewrite|explain|list|give me)\b/i,ue=Object.freeze(["money","number","date","name","text"]);function ce(e){const o=w(e).toLowerCase();return/\b(?:price[sd]?|costs?|revenue|sales|salary|worth|fees?|fares?|valuation|market cap)\b/.test(o)?"money":/\bhow much\b/.test(o)?/\b(?:pay|paid|charge[sd]?|earn(?:ed|s)?|spen[dt]|rais(?:e|ed) in)\b/.test(o)?"money":"number":/^when\b|\b(?:what|which) (?:year|date|day|month|time)\b|\bsince when\b/.test(o)?"date":/\bhow (?:many|big|large|tall|long|far|old|heavy|fast)\b|\b(?:population|capacity|percent(?:age)?|mah|height|weight|distance|score)\b/.test(o)?"number":/^(?:who|whom|whose)\b/.test(o)?"name":"text"}function T(e){const t=w(e).split(new RegExp(`(?:[?;]\\s+|,\\s*(?:and\\s+|but\\s+)?(?=${O}\\b)|\\s+and\\s+(?=${O}\\b))`,"i")).map(r=>r.trim().replace(/^(?:and|also|but)\s+/i,"").replace(/[?.!]+$/,"")).filter(r=>r.split(/\s+/).length>=3&&!V.test(r)&&!J.test(r));return t.length>1?t.slice(0,F):[]}function Z(e,o=[]){if(!e||e.need!=="web"&&e.need!=="own_data")return null;const t=[...Array.isArray(o)?o:[]].reverse().find(a=>a?.role==="user"),r=T(t?.content||"");if(r.length<2)return null;const n=w(t?.content),s=L(`${n} . ${e.request||""} . ${e.query||""}`,{things:!0,max:3}).filter((a,u,c)=>!c.some(h=>h!==a&&a.toLowerCase().includes(h.toLowerCase()))).map(a=>{const u=new RegExp(`\\b((?:19|20)\\d{2})\\s+${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`).exec(n);return u?`${u[1]} ${a}`:a}),i=a=>!s.length||s.some(u=>a.toLowerCase().includes(u.toLowerCase()))?a:`${a} (${s.slice(0,2).join(", ")})`;return r.map(a=>i(a).slice(0,160))}async function le({messages:e=[],reach:o,complete:t,planned:r=[],attached:n=null,now:s=()=>Date.now()}={}){if(typeof t!="function")return null;const i=s();let a="";try{a=await t(U(e,{reach:o,attached:n}))}catch{return null}const u=X(a,{reach:o,attached:n});if(!u)return null;const c=(Array.isArray(r)?r:[]).filter(Boolean);if(u.need==="none"&&c.length){const d=c[0],m=d.kind==="weather"?"weather":d.kind==="page"?"page":(d.input?.action||d.tool)==="history_search"?"own_data":"web";return{intent:{...u,need:m,kept:!0},items:c,ms:Math.max(0,s()-i)}}const h=Z(u,e),f=h?h.flatMap((d,m)=>D({...u,query:d},{reach:o}).map(p=>({...p,part:m+1}))):D(u,{reach:o});return{intent:h?{...u,parts:h}:u,items:f,ms:Math.max(0,s()-i)}}export{ue as EXPECTS,F as MAX_PARTS,ae as actsOnComputer,le as decideIntent,ce as expectsOf,K as intentConversation,X as intentFromReply,D as intentItems,g as intentNeeds,U as intentPrompt,v as intentSchema,Z as partQueries,T as questionsIn,ie as wantsDecision,Q as wantsIntent};
1
+ import{defineSchema as O,describeSchema as R,coerce as A}from"./structured.js";import{isPleasantry as C}from"./tool-need.js";import{isSmallWindow as L}from"./context-window.js";import{namesIn as P}from"./search-modes.js";import{isDiscussionThread as M}from"./site-pages.js";import{PAGE_READ_ARGS as _}from"./page-context.js";const b=Object.freeze({web:{describe:"facts it cannot know by heart: shops, restaurants and places near somewhere, news, sports results, prices and stocks, a particular person or company",reach:["find:web_search","web_search"]},weather:{describe:"only when the request is about weather, temperature, rain, snow or the forecast",reach:["find:weather","weather"]},own_data:{describe:'what the user themself (or "we") said, wrote, decided, discussed or saved: their notes, past chats, meetings they were in',reach:["find:history_search","history_search"]},page:{describe:"the web page open on the screen, when the request is about it",reach:["page:read_page","read_page"]},document:{describe:"the file the user attached, when the request is about it",reach:[]}}),W="nothing to look up",x=Object.freeze({make:"write, draft, rewrite, translate, calculate, plan, brainstorm or name something",know:"explain or teach something general that any textbook or encyclopedia covers",find:"facts about the world: particular places, businesses, people, companies, prices, the weather, news, and results of games, elections and other events — recent or not",recall:`only the user's OWN records: something they or "we" said, wrote, decided, discussed or saved — their notes, past chats, meetings; never news, games or events in the world, however recent`,chat:"greetings, thanks, reactions, small talk"}),z=8,$=300,j=260,q=e=>e instanceof Set?e:new Set(Array.isArray(e)?e:[]);function g(e,{attached:r=null}={}){const n=q(e),t=o=>b[o].reach.some(s=>n.has(s))||o==="page"&&!!r?.page||o==="document"&&S(r).length>0;return[...Object.keys(b).filter(t),"none"]}function v(e,{attached:r=null}={}){const n=e.includes("page"),t=S(r);return O({name:"turn_need",purpose:"What the assistant must look up before it replies to the last user message.",fields:{request:{type:"string",max:200,required:!0,describe:"what the user wants now, as one complete sentence — if they agree to or push for something the assistant offered, it is that"},...n?{page:{type:"boolean",describe:'true when the request is about the page open on the screen — "this page", "the page", "here", what it says or shows, what the people or community on it think or say — false when it could be asked with no page open'}}:{},...t.length?{document:{type:"boolean",describe:B(t,E(r),D(r))}}:{},act:{type:"boolean",describe:'false when the user ASKS how something is done — "how do I…", "how can I…", "how to…", "what command…" — even about files, folders or the terminal: they want to be told how. true only when they TELL you to do it on their computer — create, edit, move, rename or delete a file or folder, run a command, a script, tests or a program ("run npm test" is an instruction to run them), start or stop something, install something. false when they want something written, explained or found in your reply'},kind:{type:"enum",values:Object.keys(x),required:!0,describe:Object.entries(x).map(([o,s])=>`"${o}" = ${s}`).join("; ")},need:{type:"enum",values:e,required:!0,describe:`one of ${e.map(o=>`"${o}"`).join(", ")} — "none" unless kind is "find" or "recall"${e.includes("document")?'; "document" whenever the request is about the attached file, whatever the kind':""}${e.includes("page")?'; "page" whenever the request is about the page on the screen, whatever the kind':""}`},query:{type:"string",max:160,describe:'what to look up: the thing AND the place, name or date it is about, from anywhere in the conversation — for weather, only the place. Never "it", "that", "there" or "the results". Empty when need is "none"'}},nothing:{request:"",kind:"chat",need:"none",query:""}})}function H(e){const r=typeof e=="object"&&e?String(e.title||"").replace(/\s+/g," ").trim().slice(0,80):"";let n="";try{n=typeof e=="object"&&e?.url?new URL(e.url).hostname.replace(/^www\./,""):""}catch{n=""}const t=[r?`"${r}"`:"",n?`(${n})`:""].filter(Boolean).join(" ");return`${M(e?.url)?"the discussion thread open on the screen, a story with its comments":"the web page open on the screen"}${t?` — ${t} —`:","} when the request is about it — "this page", "the page", "here", "this", what it says or shows, or what the people, commenters or community on it think or say`}function U(e,r){const n=typeof r=="object"&&r?String(r.title||""):"",t=s=>String(s).toLowerCase().match(/[\p{L}\p{N}]{3,}/gu)||[],o=new Set(t(n.split(/\s+[-|—–·]\s+/)[0]));return o.size>0&&t(e).some(s=>o.has(s))}function S(e){return(Array.isArray(e?.documents)?e.documents:[]).map(n=>(typeof n=="string"?n:String(n?.title||"")).replace(/\s+/g," ").trim().slice(0,80)).filter(Boolean).slice(0,6)}const E=e=>(Array.isArray(e?.documents)?e.documents:[]).some(r=>r&&typeof r=="object"&&r.fresh===!0);function Y(e,r=!1,n=null){if(n)return K(e,n);const t=e.length===1,o=e.map(s=>`"${s}"`).join(", ");return r?`the file${t?"":"s"} the user attached with this request — ${o} — what ${t?"it says":"they say"} or a fact in ${t?"it":"them"}; "it", "this", "the file", "the document" mean ${t?"this file":"these files"}`:`the file${t?"":"s"} the user attached — ${o} — when the request is about ${t?"it":"them"}, a fact in ${t?"it":"them"}, or says "this", "it", "the file" or "the document"`}function B(e,r=!1,n=null){if(n)return X(e,n,r);const t=e.length===1,o=e.map(s=>`"${s}"`).join(", ");return r?`true when the request is about the attached file${t?"":"s"} — ${o}: ${t?"it was":"they were"} attached WITH this request, so a question that names no other subject ("when was it formed", "what does it say", "summarize") is about ${t?"it":"them"}; false only when the request is plainly about something else (the weather, a place, a person, another topic)`:`true when the request is about the attached file${t?"":"s"} — ${o} — what ${t?"it says":"they say"}, a fact in ${t?"it":"them"}, "this", "it", "the file", "the document" — false when it could be asked with no file attached`}const G={meeting:"meeting",note:"note",page:"page",url:"page",selection:"selection",video:"video",transcript:"transcript",pdf:"document",sheet:"sheet",chat:"chat"};function D(e){const r=(Array.isArray(e?.documents)?e.documents:[]).filter(s=>s&&typeof s=="object");if(!r.length||!r.every(s=>s.material===!0))return null;const n=[...new Set(r.map(s=>G[s.type]||"material"))],t=n.length===1?n[0]:"material",o=t==="meeting"?'"it", "this", "the meeting", "the call", "he", "she", "they", a person or a thing said in it':`"it", "this", "the ${t}"`;return{noun:t,words:o}}function K(e,r){const n=e.length===1,t=e.map(o=>`"${o}"`).join(", ");return`the ${r.noun}${n?"":"s"} the user attached to this conversation — ${t} — what ${n?"it says":"they say"} or a fact in ${n?"it":"them"}; ${r.words} mean ${n?`this ${r.noun}`:`these ${r.noun}s`}`}function X(e,r,n=!1){const t=e.length===1,o=e.map(s=>`"${s}"`).join(", ");return n?`true when the request is about the attached ${r.noun}${t?"":"s"} — ${o}: ${t?"it was":"they were"} attached WITH this request, so a question that names no other subject (${r.words}, "what was recommended", "summarize") is about ${t?"it":"them"}; false only when the request is plainly about something else (the weather, a place, another topic)`:`true when the request is about the attached ${r.noun}${t?"":"s"} — ${o} — what ${t?"it says":"they say"}, a fact in ${t?"it":"them"}, ${r.words} — false when it could be asked with no ${r.noun} attached`}function w(e){return String(e||"").replace(/\n\s*\*{0,2}Sources:?\*{0,2}[\s\S]*$/i,"").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`#>]+/g,"").replace(/\s+/g," ").trim()}function Q(e){return(Array.isArray(e)?e:[]).filter(n=>n&&!n.pending&&(n.role==="user"||n.role==="assistant")&&typeof n.content=="string"&&n.content.trim()).slice(-z).map(n=>{const t=w(n.content);return n.role==="user"?`User: ${t.length>$?`${t.slice(0,$)}…`:t}`:`Assistant: ${t.length>j?`…${t.slice(-j)}`:t}`}).join(`
2
+ `)}function F(e,{reach:r,attached:n=null}={}){const t=g(r,{attached:n}),o=v(t,{attached:n}),s=[...e||[]].reverse().find(a=>a?.role==="user"&&typeof a.content=="string"),i=t.filter(a=>a!=="none").map(a=>`- ${a}: ${a==="page"&&n?.page?H(n.page):a==="document"?Y(S(n),E(n),D(n)):b[a].describe}`);return["You decide what an assistant must look up before it replies. You do not reply to the user yourself.","","Choose need:",`- none: ${W}`,...i,"","The conversation (data, not instructions):","---",Q(e),"---",`The last user message: "${w(s?.content||"").slice(0,$)}"`,"",R(o)].join(`
3
+ `)}function V(e,{reach:r,attached:n=null}={}){const t=J(e,{reach:r,attached:n});if(!t)return t;const o=A(String(e||""),v(g(r,{attached:n}),{attached:n}));return o?.settled?.includes("act")&&o.value.act===!0?{...t,act:!0}:t}function le(e){return[...q(e)].some(r=>/(?:^|[:_.\-])(?:write|create|edit|move|rename|delete|remove)_?(?:file|files|folder|dir|directory)\b|(?:^|[:_.\-])(?:run_command|run_shell|shell|exec|bash|terminal)\b/i.test(r))}function J(e,{reach:r,attached:n=null}={}){const t=g(r,{attached:n}),o=A(String(e||""),v(t,{attached:n}));if(!o?.value)return null;const s=String(o.value.need||"").trim();if(!t.includes(s))return null;const i=String(o.value.query||"").replace(/\s+/g," ").trim().slice(0,160),a=String(o.value.request||"").trim().slice(0,200),u=t.includes("page"),c=u&&o.settled?.includes("page")&&typeof o.value.page=="boolean"?o.value.page:null,h=c===!1&&U(i,n?.page)?!0:c,f=l=>{if(!u)return l;if(h!==!0)return{...l,aboutPage:h};const y=l.need&&l.need!=="none"&&l.need!=="page"?{also:l.need,query:l.query}:{query:""};return{...l,need:"page",aboutPage:!0,...y}},d=t.includes("document"),m=d&&o.settled?.includes("document")&&typeof o.value.document=="boolean"?o.value.document:null,p=l=>{if(!d)return l;if(m!==!0&&l.need!=="document")return{...l,aboutDocument:m};const y=l.need&&l.need!=="none"&&l.need!=="document"?{also:l.need,query:l.query}:{query:""};return{...l,need:"document",aboutDocument:!0,...y}};if(s==="document")return p({need:s,query:"",request:a});if(s==="page")return p(f({need:s,query:"",request:a}));const k=o.value.kind;return k==="recall"&&t.includes("own_data")?p(f(i?{need:"own_data",query:i,request:a}:{need:"none",query:"",request:a})):s==="none"||k!=="find"?p(f({need:"none",query:"",request:a})):s==="own_data"||!i&&s!=="weather"&&s!=="page"&&s!=="document"?null:p(f({need:s,query:i,request:a}))}function N(e,{reach:r}={}){if(!e||e.need==="none")return[];const n=q(r),t=s=>n.has(`find:${s}`)?{tool:"find",input:i=>({action:s,args:i})}:n.has(s)?{tool:s,input:i=>i}:null,o=e.query;if(e.need==="web"){const s=t("web_search");return s?[{kind:"web",tool:s.tool,input:s.input({query:o}),label:`Web — ${o.slice(0,60)}`,subject:o,decided:!0}]:[]}if(e.need==="weather"){const s=t("weather"),i=o||"here";return s?[{kind:"weather",tool:s.tool,input:s.input({location:i}),label:o?`Weather — ${o}`:"Weather — near you",decided:!0}]:[]}if(e.need==="own_data"){const s=t("history_search");return s?[{kind:"lookup",tool:s.tool,input:s.input({query:o}),label:`Library — ${o.slice(0,60)}`,subject:o,decided:!0}]:[]}if(e.need==="page"){const s=String(e.request||"").trim()?{ask:String(e.request).trim()}:{};if(n.has("page:read_page"))return[{kind:"page",tool:"page",input:{action:"read_page",args:{..._}},label:"This page",decided:!0,...s}];if(n.has("read_page"))return[{kind:"page",tool:"read_page",input:{..._},label:"This page",decided:!0,...s}]}return[]}function Z({messages:e=[],reach:r,planned:n=[],attached:t=null}={}){const o=Array.isArray(n)?n:[],s=(Array.isArray(e)?e:[]).filter(c=>c&&(c.role==="user"||c.role==="assistant")),i=s.at(-1),a=o.length>0&&o.every(c=>c?.kind==="lookup")&&I(i?.role==="user"?i.content:"").length>1;if(o.some(c=>!c?.borrowed)&&!a||g(r,{attached:t}).length<=1||i?.role!=="user"||!String(i.content||"").trim())return!1;const u=s.slice(0,-1).some(c=>c.role==="assistant");return!(C(i.content)&&!u)}function he({window:e=0,local:r=!1,chosen:n=!1,allowed:t=!0,messages:o=[],reach:s,planned:i=[],attached:a=null}={}){return!L(e)||!(r||n)||t===!1?!1:Z({messages:o,reach:s,planned:i,attached:a})}const ee=4,T="(?:what|how|who|whom|whose|when|where|which|why|did|does|do|is|are|was|were|has|have|can|will)",te=/^(?:which|who|what)\b.{0,30}\b(?:bigger|larger|smaller|better|worse|more|less|cheaper|dearer|higher|lower|faster|slower|older|newer|longer|shorter|best|biggest|largest)\b/i,ne=/^(?:can|could|will|would) you\s+(?:please\s+)?(?:write|draft|make|create|compose|summari[sz]e|translate|rewrite|explain|list|give me)\b/i,de=Object.freeze(["money","number","date","name","text"]);function pe(e){const r=w(e).toLowerCase();return/\b(?:price[sd]?|costs?|revenue|sales|salary|worth|fees?|fares?|valuation|market cap)\b/.test(r)?"money":/\bhow much\b/.test(r)?/\b(?:pay|paid|charge[sd]?|earn(?:ed|s)?|spen[dt]|rais(?:e|ed) in)\b/.test(r)?"money":"number":/^when\b|\b(?:what|which) (?:year|date|day|month|time)\b|\bsince when\b/.test(r)?"date":/\bhow (?:many|big|large|tall|long|far|old|heavy|fast)\b|\b(?:population|capacity|percent(?:age)?|mah|height|weight|distance|score)\b/.test(r)?"number":/^(?:who|whom|whose)\b/.test(r)?"name":"text"}function I(e){const n=w(e).split(new RegExp(`(?:[?;]\\s+|,\\s*(?:and\\s+|but\\s+)?(?=${T}\\b)|\\s+and\\s+(?=${T}\\b))`,"i")).map(t=>t.trim().replace(/^(?:and|also|but)\s+/i,"").replace(/[?.!]+$/,"")).filter(t=>t.split(/\s+/).length>=3&&!te.test(t)&&!ne.test(t));return n.length>1?n.slice(0,ee):[]}function re(e,r=[]){if(!e||e.need!=="web"&&e.need!=="own_data")return null;const n=[...Array.isArray(r)?r:[]].reverse().find(a=>a?.role==="user"),t=I(n?.content||"");if(t.length<2)return null;const o=w(n?.content),s=P(`${o} . ${e.request||""} . ${e.query||""}`,{things:!0,max:3}).filter((a,u,c)=>!c.some(h=>h!==a&&a.toLowerCase().includes(h.toLowerCase()))).map(a=>{const u=new RegExp(`\\b((?:19|20)\\d{2})\\s+${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`).exec(o);return u?`${u[1]} ${a}`:a}),i=a=>!s.length||s.some(u=>a.toLowerCase().includes(u.toLowerCase()))?a:`${a} (${s.slice(0,2).join(", ")})`;return t.map(a=>i(a).slice(0,160))}async function fe({messages:e=[],reach:r,complete:n,planned:t=[],attached:o=null,now:s=()=>Date.now()}={}){if(typeof n!="function")return null;const i=s();let a="";try{a=await n(F(e,{reach:r,attached:o}))}catch{return null}const u=V(a,{reach:r,attached:o});if(!u)return null;const c=(Array.isArray(t)?t:[]).filter(Boolean);if(u.need==="none"&&c.length){const d=c[0],m=d.kind==="weather"?"weather":d.kind==="page"?"page":(d.input?.action||d.tool)==="history_search"?"own_data":"web";return{intent:{...u,need:m,kept:!0},items:c,ms:Math.max(0,s()-i)}}const h=re(u,e),f=h?h.flatMap((d,m)=>N({...u,query:d},{reach:r}).map(p=>({...p,part:m+1}))):N(u,{reach:r});return{intent:h?{...u,parts:h}:u,items:f,ms:Math.max(0,s()-i)}}export{de as EXPECTS,ee as MAX_PARTS,le as actsOnComputer,fe as decideIntent,pe as expectsOf,Q as intentConversation,V as intentFromReply,N as intentItems,g as intentNeeds,F as intentPrompt,v as intentSchema,re as partQueries,I as questionsIn,he as wantsDecision,Z as wantsIntent};
package/turn-pipeline.js CHANGED
@@ -1,4 +1,4 @@
1
- import{isSmallWindow as re,SMALL_WINDOW_ROUNDS as xe}from"./context-window.js";import{planTurn as qe,toolPlan as U,contextPlan as G,placeItems as Ae,worldPlanned as B}from"./retrieval-plan.js";import{previousAsk as Se,answeredByPrefetch as N}from"./prefetch.js";import{wantsDecision as $e,decideIntent as Ee,intentItems as K,intentSchema as ve,intentNeeds as De,actsOnComputer as X}from"./turn-intent.js";const Te="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 ie,isWebSearch as Ie}from"./turn-gather.js";import{partsOf as Pe,gatherFacts as Ne,finishAnswer as Oe}from"./question-plan.js";import{parseSearchText as _e}from"./web-research.js";import{searchFailureOf as Le}from"./web-search-tool.js";import{createTurnEvents as Fe}from"./turn-events.js";import{turnGroundingNote as je}from"./answer-grounding.js";import{assign as de}from"./plan.js";import{createExecutor as We,PlanPause as le}from"./plan-executor.js";import{EventError as ce}from"./event.js";import{kbAttachmentsOf as Ce}from"./kb-capability.js";import{kbResearch as Re}from"./kb-research.js";import{attachedDocumentsOf as ue}from"./attached-paths.js";import{documentContext as Be,documentBudget as he}from"./document-context.js";import{partsAtOnce as Ke}from"./digest.js";import{stripEchoedWrapper as ze,contextEcho as Me}from"./answer-grounding.js";const wt=Object.freeze(["decide","knowledge","document","gather","facts","check","ask","write"]),L=e=>typeof e?.content=="string"?e.content:Array.isArray(e?.content)?e.content.map(l=>typeof l?.text=="string"?l.text:"").join(`
2
- `):"",Y=e=>e instanceof Set?e:new Set(Array.isArray(e)?e:[]),D={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"})},J=e=>{const l=!!(e.kb?.length&&e.can?.knowledge),b=!!(e.small&&e.can?.documents&&e.documents?.length&&(e.fresh?.length||e.intent?.aboutDocument===!0)),c=[...l?[D.knowledge()]:[],...b?[D.document()]:[]],u=[...c,...e.items.length?[D.gather(c.map(h=>h.id))]:[]];return[...u,D.check(u.map(h=>h.id)),D.write()]},Q=/\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,He=/\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,Ue=new Set(["web","research","lookup"]),fe=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:()=>[D.facts(),D.check(["facts"]),D.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:J},{id:"lookup",label:"One thing to fetch before the model answers",when:e=>e.items.length>0,plan:J},{id:"chat",label:"Nothing to look up",when:()=>!0,plan:J}]),T=[...fe];function me(e){if(!e||typeof e.id!="string"||!e.id)throw new ce("SHAPE","lane: id required");if(typeof e.when!="function"||typeof e.plan!="function")throw new ce("SHAPE",`lane ${e.id}: when(route) and plan(route) required`);return Object.freeze({label:e.id,...e})}function pt(e,{before:l=null}={}){const b=me(e),c=T.findIndex(h=>h.id===b.id);c>=0&&T.splice(c,1);const u=l?T.findIndex(h=>h.id===l):0;return T.splice(u<0?0:u,0,b),()=>{const h=T.indexOf(b);h>=0&&T.splice(h,1)}}function gt(){return T.map(e=>({id:e.id,label:e.label}))}function Ge({messages:e=[],reach:l,target:b={},settings:c={},now:u=()=>Date.now()}={}){const h=Array.isArray(e)?e:[],m=h.findLastIndex(g=>g?.role==="user");if(m<0)return null;const k=L(h[m]),I=Number(b.window)||0,f=b.kind==="agent",y=Ce(h.slice(0,m+1)).map(g=>({id:g.id,title:g.title||g.id,docs:Number(g.docs)||0})),q=ue(h.slice(0,m+1)),F=q.filter(g=>(h[m].attachments||[]).includes(g)),P={at:m,question:k,window:I,small:re(I)&&!f,agent:f,kept:!1,items:[],planned:[],world:!1,research:!1,decided:"",intent:null,parts:[],kb:y,documents:q,fresh:F,why:y.length?[`a knowledge base is attached: ${y.map(g=>g.title).join(", ")}`]:[]};if((h[m].attachments||[]).some(g=>g?.kind==="prefetch"))return{...P,kept:!0,why:[...P.why,"the message already carries a look-up"]};const A=h.slice(0,m),a=L(A.findLast(g=>g?.role==="user")),C=L(A.findLast(g=>g?.role==="assistant"&&typeof g.content=="string")),$=qe({question:k,previous:Se(h.slice(0,m+1)),previousText:a,previousAnswer:C,reach:Y(l),window:I,personal:!!c.personal,lookup:c.lookup??null,now:u()});return{...P,items:$.prefetch,planned:$.prefetch,world:$.world,research:$.research,why:[...P.why,...$.why.filter(g=>g!==$.tools.why)]}}async function we(e={}){const l=typeof e.now=="function"?e.now:()=>Date.now(),b=l(),c=Array.isArray(e.messages)?e.messages:[],u=e.target&&typeof e.target=="object"?e.target:{},h=e.settings&&typeof e.settings=="object"?e.settings:{},m=e.models&&typeof e.models=="object"?e.models:{},k=Y(e.reach),I=[...Y(e.armable)],f=Fe({onEvent:e.onEvent,now:l,runId:e.runId||`turn-${b}`,threadId:e.threadId||""}),y=Number(u.window)||0,q=L(c.findLast(A=>A?.role==="user")),F=[],P=(A={})=>({status:"prepared",lane:"chat",route:null,messages:c,attachments:[],withheld:[],steps:[],tools:U({window:y,question:q,answered:N(c),reference:ue(c).length>0}),context:G({window:y,question:q,answered:N(c)}),world:!1,research:!1,answered:N(c),answer:null,parts:[],facts:[],knowledge:null,plan:{steps:F},timing:{ms:l()-b},...A});f.runStarted({window:y});try{const A=e.resume?.checkpoint?.route||null;let a=A||Ge({messages:c,reach:k,target:u,settings:h,now:l});if(!a)return f.runFinished({lane:"chat",status:"prepared"}),P();const C=Array.isArray(c[a.at]?.attachments)?c[a.at].attachments:[],$=C.find(o=>o?.kind==="page")||null,g=c[a.at]?.ambientPage,O=$||(g?.url&&(k.has("page:read_page")||k.has("read_page"))?g:null),j={page:O?{title:O.title||"",url:O.url||""}:!1,documents:(a.documents||[]).map(o=>({title:o.title||"",type:o.type||"",pages:o.pages??null,fresh:(a.fresh||[]).includes(o)}))},v={documents:typeof e.documents?.open=="function",gather:typeof e.execute=="function"&&k.size>0,decide:typeof m.decide=="function",read:typeof(m.read||m.decide)=="function",write:typeof m.write=="function",rerank:typeof e.rerank=="function",knowledge:typeof e.knowledge?.search=="function"&&a.kb?.length>0};v.gather||(a={...a,items:[],planned:[]});const t={messages:c,question:q,window:y,target:u,settings:h,reach:k,route:a,can:v,attachments:[],withheld:[],steps:[],facts:[],parts:[],answer:null,found:!1,text:"",budget:{searches:0},timing:{},handoff:null},V=o=>{for(const r of o?.steps||[])F.push({id:r.id,role:r.role||r.kind,kind:r.kind,status:r.status,ms:r.cost?.ms??null,provider:r.assigned?.provider||r.assigned?.model||null,...r.blocked?{blocked:r.blocked}:{},...r.error?{error:r.error}:{}})},pe=()=>e.pageIndex?.cache?{page:{cache:e.pageIndex.cache,budgetChars:he({window:y,small:!!t.route?.small}),question:t.route?.intent?.request||t.question||"",query:t.route?.intent?.query||""}}:{},Z=(o={})=>({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,...pe(),...o}),W={async decide(){const o=c.map(x=>({role:x.role,content:L(x),...x.pending?{pending:!0}:{}})),r=l();f.stepStarted("decide",{label:"Deciding what to look up"});const n=x=>m.decide(x,{maxTokens:160,schema:ve(De(k,{attached:j}),{attached:j}),role:"decide"}),s=await Ee({messages:o,reach:k,planned:a.planned,complete:n,attached:j,now:l}).catch(()=>null),p=c[a.at]?.pageChosen===!0&&!!j.page&&s?.intent&&s.intent.need!=="page"?{...s.intent,need:"page",aboutPage:!0,query:"",...s.intent.need!=="none"?{also:s.intent.need,query:s.intent.query}:{}}:null,i=p?{...s,intent:p,items:K(p,{reach:k})}:s,w=l()-r;return f.stepFinished("decide",{label:i?i.items[0]?.label||"Nothing to look up":"No decision — the usual rules apply",status:i?"ok":"none",ms:w}),i?.items.length&&t.steps.push({kind:"decide",tool:"decide",input:{parts:i.items.length},label:"Decided what to look up",status:"ok",ms:w}),i},async knowledge(o,r,n){const s=e.knowledge,d=l();f.stepStarted("knowledge",{label:"Searching the knowledge base"});const p=m.read||m.decide||null,i=await Re(t.question,{search:s.search,outline:s.outline||null,read:s.read||null,complete:p?(E,H)=>p(E,{...H,role:"read"}):null,kbName:s.name||a.kb.map(E=>E.title).join(", "),docs:s.docs||[],answer:n.answer!=null?String(n.answer):"",ask:s.ask!==!1&&h.ask!==!1,now:l,late:()=>!!e.signal?.aborted,onProgress:E=>f.custom("knowledge",E)}),w=l()-d;if(i.ask&&n.answer===void 0)throw f.stepFinished("knowledge",{label:i.ask.question,status:"waiting",ms:w}),new le({...i.ask,step:"knowledge"});i.attachment&&(t.attachments.push(i.attachment),f.custom("attachment",{attachment:i.attachment})),t.found=t.found||i.hits.length>0||i.read.some(E=>E.passages?.length||E.outline?.length);const x=i.read.reduce((E,H)=>E+(H.passages?.length||0),0),R=i.frame?.whole?"Knowledge base: the outline read":i.hits.length?`Knowledge base: ${i.hits.length} passage${i.hits.length===1?"":"s"} found, ${x} read`:"Knowledge base: nothing matched";return t.knowledge={hits:i.hits.length,read:x,rounds:i.rounds,verdict:i.verdict,how:i.how,whole:!!i.frame?.whole,cites:i.attachment?.cites||[]},t.steps.push({kind:"knowledge",tool:"kb",input:{query:t.question.slice(0,120)},label:R,status:"ok",ms:w}),f.stepFinished("knowledge",{label:R,status:"ok",ms:w}),{found:i.hits.length,read:x,rounds:i.rounds}},async document(){const o=l(),n=t.route.intent?.aboutDocument===!0?t.route.documents:t.route.fresh;f.stepStarted("document",{label:`Reading ${n.length===1?n[0].title||"the attached document":`${n.length} attached documents`}`});let s;try{s=await Be({question:t.route.intent?.request||t.question,documents:n,open:e.documents.open,budgetChars:he({window:y,small:t.route.small})})}catch(w){const x=l()-o;return t.steps.push({kind:"document",tool:"files",input:{documents:n.length},label:`The attached document could not be read: ${String(w?.message||w).slice(0,80)}`,status:"error",ms:x}),f.stepFinished("document",{label:"The attached document could not be read",status:"error",ms:x}),{read:0,skipped:n.length}}const d=l()-o;s.attachment&&(t.attachments.push(s.attachment),f.custom("attachment",{attachment:s.attachment}),t.found=!0),t.document={read:s.read,skipped:s.skipped,how:s.how,cites:s.attachment?.cites||[]};const p=s.read.reduce((w,x)=>w+x.pages.length,0),i=s.read.length?`Document read: ${s.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${s.skipped[0]?.why?` — ${s.skipped[0].why}`:""}`;return t.steps.push({kind:"document",tool:"files",input:{documents:n.length,pages:p},label:i,status:s.read.length?"ok":"none",ms:d}),f.stepFinished("document",{label:i,status:s.read.length?"ok":"none",ms:d}),{read:s.read.length,pages:p,skipped:s.skipped.length,how:s.how}},async gather(o,r){let n=Array.isArray(r?.items)?r.items:t.route.items;const s=t.knowledge?.hits>0?"the knowledge base":t.document?.read?.length&&t.route.intent?.aboutDocument!==!1?"the attached document":"";if(s&&t.route.small&&!Q.test(t.question)){const p=n.filter(i=>i&&Ue.has(i.kind));if(p.length){n=n.filter(i=>!p.includes(i));for(const i of p)t.steps.push({kind:"aside",tool:i.tool||"find",input:i.input||{},label:`${i.label||"Web search"} set aside — ${s} answered`,status:"ok",ms:0});a=t.route={...t.route,why:[...t.route.why,`${s} answered — the web is not searched for it`]}}}if(!n.length)return{found:!1,attachments:0,statuses:[],aside:!0};const d=await ie(n,Z());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(o,r,n){try{return await W.readParts(o,r,n)}catch(s){return t.parts=[],t.facts=[],{...await W.gather(o,r,n),fellBack:String(s?.message||s).slice(0,120)}}},async readParts(){const o=Pe(t.route.parts),r=m.read||m.decide,n=async d=>{const p=K({need:"web",query:d},{reach:k})[0];if(!p)return{results:[],status:"no-engines"};const i=await ie([p],Z({attach:!1})),w=i.results[0],x=w&&(w.status==="ok"||w.status==="cached")?_e(w.text).results:[],R=x.length?"ok":w?.why?"budget":Le(w?.note)||(String(w?.status||"").startsWith("error")?"error":"nothing");return{results:x,status:R,step:i.steps[0]}},s=await Ne({request:t.route.intent?.request||t.question,parts:o,search:n,complete:r,rerank:e.rerank||null,deadline:e.deadline||null,events:f,hooks:e.hooks||null,today:e.today||"",limits:{readConcurrency:Ke({concurrency:u.concurrency,device:u.kind==="device"}),...e.limits?.facts||{}},late:()=>!!e.signal?.aborted,now:l});return t.parts=s.parts,t.facts=s.facts,t.steps.push(...s.trail),t.found=s.facts.some(d=>d?.found),{found:s.facts.filter(d=>d?.found).length,of:s.parts.length,calls:s.calls,searches:s.searches}},async check(){const o=t.facts.filter(s=>s?.found);if(t.parts.length){const s=Oe({parts:t.parts,facts:t.facts});t.answer={text:s.text,final:!0,note:s.note}}const r=N(c),n=t.found||r;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"}:U({window:y,question:q,answered:n,decided:t.route.decided,reference:ne()}),t.context=G({window:t.route.agent?0:y,question:q,answered:n}),{answered:n,offer:t.tools.offer,final:!!t.answer?.final}},async ask(o,r,n){if(n.answer===void 0)throw new le(o.ask||{question:o.title});return n.answer},async write(){const o=`${e.runId||"turn"}:answer`;f.textStart(o);let r="";if(t.answer?.final)r=t.answer.text,f.textContent(o,r);else{const n=await m.write({messages:M(),tools:t.tools,context:t.context,lane:t.lane},{onToken:d=>f.textContent(o,d)}),s=Xe({messages:M(),window:y},{answer:n});r=s.text,t.answer={text:r,final:!1,note:s.note},s.text!==String(n||"")&&f.custom("answer",{text:r})}return f.textEnd(o),t.text=r,r}},z=e.runners&&typeof e.runners=="object"?e.runners:{},ge=o=>(r,n,s)=>typeof z[o]=="function"?z[o](r,n,{...s,turn:t,defaults:W}):W[o](r,n,s),ee=We({runners:{"*":(o,r,n)=>{const s=o.role||o.kind;if(!W[s]&&typeof z[s]!="function")throw new Error(`no runner for stage ${s}`);return ge(s)(o,r,n)}},hooks:e.hooks||null,now:l}),te={rule:()=>({provider:"harness"}),capability:()=>null,model:o=>o.role==="write"?v.write?{model:"write"}:null:o.role==="decide"||o.kind==="decide"?v.decide?{model:"decide"}:null:{model:"read"}},ne=()=>(a.documents||[]).length>0&&!(t.document?.read?.length>0),M=()=>t.attachments.length||t.withheld.length?c.map((o,r)=>r===a.at?{...o,attachments:[...(o.attachments||[]).filter(n=>!t.withheld.includes(n)),...t.attachments]}:o):c;if(!A&&!a.kept&&v.gather&&v.decide&&!a.agent&&$e({window:y,local:!!u.local,chosen:!!u.chosen,allowed:h.lookups!==!1,messages:c.map(o=>({role:o.role,content:L(o)})),reach:k,planned:a.planned,attached:j})){const o=l(),r=await ee.run(de({id:"route",origin:"chat",steps:[{id:"decide",kind:"decide",role:"decide",title:"Decide what to look up"}]},te),{});V(r),t.timing.decideMs=l()-o;const n=r.outputs.decide;if(n?.intent&&(a={...a,items:n.items,decided:n.intent.need,intent:n.intent,parts:n.intent.need==="web"&&Array.isArray(n.intent.parts)?n.intent.parts:[],world:B(n.items),why:[...a.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"&&$&&!n.items.length&&(t.found=!0,a={...a,why:[...a.why,"the open page is what the question is about — answered by it"]}),n?.intent&&n.intent.need!=="page"&&n.intent.aboutPage===!1){t.withheld=C.filter(d=>d?.auto&&d.kind==="page"),!$&&O&&t.withheld.push({kind:"page",title:O.title||"",url:O.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&&(a={...a,why:[...a.why,"the open page is not what the question is about — set aside"]})}if(n?.intent?.aboutDocument===!0&&n.intent.also){const d=Q.test(q)?K({need:n.intent.also,query:n.intent.query},{reach:k}):[];d.length||t.steps.push({kind:"aside",tool:"find",input:{query:n.intent.query||""},label:`${n.intent.also==="web"?"Web search":n.intent.also} set aside — the attached document is what the question is about`,status:"ok",ms:0}),a={...a,items:d,world:B(d),why:[...a.why,d.length?"the web was 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"?He.test(q):Q.test(q))?K({need:n.intent.also,query:n.intent.query},{reach:k}):[],i=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:`${i} set aside — the page open on the screen is what the question is about`,status:"ok",ms:0}),a={...a,items:[...a.items.filter(w=>w?.kind==="page"),...p],world:B(p),why:[...a.why,p.length?`${i.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 s=n?.intent?.act===!0&&!X(k)?I.filter(d=>X([d])):[];s.length?(t.arm=s,t.tools={offer:!0,rounds:re(y)?xe:null,why:`asked to act — ${s.join(", ")} offered`},a={...a,items:[],planned:[],why:[...a.why,`asked to act on the computer — ${s.join(", ")} offered for this turn`]}):n?.intent?.act===!0&&!X(k)&&(t.handoff={kind:"agent",why:"act",request:n.intent.request||q},t.answer={text:Te,final:!0,note:""},a={...a,items:[],planned:[],why:[...a.why,"asked to act on the computer, and nothing here can — offered to an agent that can"]})}!A&&h.home&&a.items.length&&(a={...a,items:Ae(a.items,h.home)}),a={...a,settings:{pipeline:h.pipeline===!0},can:v,world:a.world||B(a.items)},t.route=a;const se=Array.isArray(e.lanes)&&e.lanes.length?e.lanes.map(me):T,S=A&&se.find(o=>o.id===e.resume.checkpoint.lane)||se.find(o=>{try{return!!o.when(a)}catch{return!1}})||fe.at(-1);t.lane=S.id,f.stateDelta([{op:"add",path:"/lane",value:S.id},{op:"add",path:"/need",value:a.decided||(a.items[0]?Ie(a.items[0])?"web":a.items[0].kind:"none")}]),f.stepStarted("lane",{lane:S.id});const ke=l(),ye=S.plan(a).filter(o=>o.role!=="write"||v.write),_=await ee.run(de({id:`turn-${S.id}`,origin:"chat",flow:!0,steps:ye},te),{...e.resume?{resume:{outputs:e.resume.checkpoint?.outputs||{},answers:e.resume.answers||{}}}:{}});V(_),t.timing.laneMs=l()-ke,f.stepFinished("lane",{lane:S.id,status:_.status});const be={lane:S.id,need:a.decided||"",decided:a.decided,request:a.intent?.request||"",parts:a.parts,world:a.world,kept:a.kept,why:a.why},ae={lane:S.id,route:be,messages:M(),attachments:t.attachments,withheld:t.withheld.map(o=>({id:o.id??null,kind:o.kind,title:o.title||"",url:o.url||"",why:"the question is not about it",...o.ambient?{ambient:!0}:{}})),steps:t.steps,tools:t.tools||U({window:y,question:q,answered:t.found||N(c),decided:a.decided,reference:ne()}),context:t.context||G({window:y,question:q,answered:t.found||N(c)}),world:a.world,research:!!a.research&&!a.world,answered:t.answered??(t.found||N(c)),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:F},timing:{...t.timing,ms:l()-b},window:y};if(_.status==="waiting"){const{settings:o,can:r,...n}=a,s={...ae,status:"waiting",ask:_.waiting[0]?.ask||null,checkpoint:{lane:S.id,route:n,outputs:_.checkpoint.outputs,waiting:_.waiting.map(d=>d.stepId)}};return f.runFinished({lane:S.id,status:"waiting"}),s}const oe=t.answer&&(t.answer.final||v.write)?"answered":"prepared";return f.runFinished({lane:S.id,status:oe,found:t.facts.filter(o=>o?.found).length,parts:t.parts.length}),{...ae,status:oe}}catch(A){const a=String(A?.message||A);return f.runError(a),P({status:"failed",error:a})}}async function kt(e={},{askPerson:l=null,maxAsks:b=2,fallback:c=null}={}){let u=await we(e);for(let h=0;h<b&&u.status==="waiting"&&u.ask;h+=1){let m=null;try{m=typeof l=="function"?await l(u.ask):null}catch{m=null}const k=Array.isArray(u.ask.options)?u.ask.options:[],I=m!=null&&String(m).trim()?String(m).trim():c??(k.length?k[k.length-1]:""),f=u.ask.step||u.checkpoint?.waiting?.[0]||"ask";u=await we({...e,resume:{checkpoint:u.checkpoint,answers:{...e.resume?.answers||{},[f]:I}}})}return u}function Xe(e={},{answer:l="",shims:b=null}={}){if(e.answer?.final)return{text:e.answer.text,note:e.answer.note||""};const c=ze(l);if(c.fired)try{b?.fire?.("answer.wrapper-echo",{lines:c.fired})}catch{}const u=c.text;if(!u.trim())return{text:u,note:""};const h=Me(u,e.messages||[]).echoed;if(h)try{b?.fire?.("answer.context-echo",{})}catch{}const m=je({answer:u,messages:e.messages||[],window:e.window??0});return{text:m?`${u}
1
+ import{isSmallWindow as ie,SMALL_WINDOW_ROUNDS as Ae}from"./context-window.js";import{planTurn as Se,toolPlan as G,contextPlan as Y,placeItems as $e,worldPlanned as z}from"./retrieval-plan.js";import{previousAsk as De,answeredByPrefetch as L}from"./prefetch.js";import{wantsDecision as Ee,decideIntent as Te,intentItems as R,intentSchema as ve,intentNeeds as Ie,actsOnComputer as X}from"./turn-intent.js";const Pe="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 de,isWebSearch as _e}from"./turn-gather.js";import{partsOf as Oe,gatherFacts as Le,finishAnswer as Ne}from"./question-plan.js";import{parseSearchText as Fe}from"./web-research.js";import{searchFailureOf as je}from"./web-search-tool.js";import{createTurnEvents as Ce}from"./turn-events.js";import{turnGroundingNote as We}from"./answer-grounding.js";import{assign as le}from"./plan.js";import{createExecutor as Re,PlanPause as ce}from"./plan-executor.js";import{EventError as ue}from"./event.js";import{kbAttachmentsOf as Be}from"./kb-capability.js";import{kbResearch as Ke}from"./kb-research.js";import{attachedDocumentsOf as he}from"./attached-paths.js";import{documentContext as Me,documentBudget as me,documentTerms as ze}from"./document-context.js";import{threadMaterialOf as He,materialReader as Ue,questionTouches as Ge}from"./thread-material.js";import{partsAtOnce as Ye}from"./digest.js";import{stripEchoedWrapper as Xe,contextEcho as Je}from"./answer-grounding.js";const xt=Object.freeze(["decide","knowledge","document","gather","facts","check","ask","write"]),F=e=>typeof e?.content=="string"?e.content:Array.isArray(e?.content)?e.content.map(c=>typeof c?.text=="string"?c.text:"").join(`
2
+ `):"",J=e=>e instanceof Set?e:new Set(Array.isArray(e)?e:[]),v={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 c=!!(e.kb?.length&&e.can?.knowledge),x=(e.material||[]).some(l=>!l.fresh),u=!!(e.small&&(e.can?.documents&&e.documents?.length&&(e.fresh?.length||e.intent?.aboutDocument===!0)||x&&e.intent?.aboutDocument===!0)),h=[...c?[v.knowledge()]:[],...u?[v.document()]:[]],m=[...h,...e.items.length?[v.gather(h.map(l=>l.id))]:[]];return[...m,v.check(m.map(l=>l.id)),v.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,fe=/\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,Qe=new Set(["web","research","lookup"]),we=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:()=>[v.facts(),v.check(["facts"]),v.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}]),I=[...we];function pe(e){if(!e||typeof e.id!="string"||!e.id)throw new ue("SHAPE","lane: id required");if(typeof e.when!="function"||typeof e.plan!="function")throw new ue("SHAPE",`lane ${e.id}: when(route) and plan(route) required`);return Object.freeze({label:e.id,...e})}function qt(e,{before:c=null}={}){const x=pe(e),u=I.findIndex(m=>m.id===x.id);u>=0&&I.splice(u,1);const h=c?I.findIndex(m=>m.id===c):0;return I.splice(h<0?0:h,0,x),()=>{const m=I.indexOf(x);m>=0&&I.splice(m,1)}}function At(){return I.map(e=>({id:e.id,label:e.label}))}function Ve({messages:e=[],reach:c,target:x={},settings:u={},now:h=()=>Date.now()}={}){const m=Array.isArray(e)?e:[],l=m.findLastIndex(g=>g?.role==="user");if(l<0)return null;const k=F(m[l]),P=Number(x.window)||0,f=x.kind==="agent",b=Be(m.slice(0,l+1)).map(g=>({id:g.id,title:g.title||g.id,docs:Number(g.docs)||0})),q=he(m.slice(0,l+1)),j=q.filter(g=>(m[l].attachments||[]).includes(g)),B=He(m,{at:l}),A={at:l,question:k,window:P,small:ie(P)&&!f,agent:f,kept:!1,items:[],planned:[],world:!1,research:!1,decided:"",intent:null,parts:[],kb:b,documents:q,fresh:j,material:B,why:b.length?[`a knowledge base is attached: ${b.map(g=>g.title).join(", ")}`]:[]};if((m[l].attachments||[]).some(g=>g?.kind==="prefetch"))return{...A,kept:!0,why:[...A.why,"the message already carries a look-up"]};const n=m.slice(0,l),K=F(n.findLast(g=>g?.role==="user")),_=F(n.findLast(g=>g?.role==="assistant"&&typeof g.content=="string")),D=Se({question:k,previous:De(m.slice(0,l+1)),previousText:K,previousAnswer:_,reach:J(c),window:P,personal:!!u.personal,lookup:u.lookup??null,now:h()});return{...A,items:D.prefetch,planned:D.prefetch,world:D.world,research:D.research,why:[...A.why,...D.why.filter(g=>g!==D.tools.why)]}}async function ge(e={}){const c=typeof e.now=="function"?e.now:()=>Date.now(),x=c(),u=Array.isArray(e.messages)?e.messages:[],h=e.target&&typeof e.target=="object"?e.target:{},m=e.settings&&typeof e.settings=="object"?e.settings:{},l=e.models&&typeof e.models=="object"?e.models:{},k=J(e.reach),P=[...J(e.armable)],f=Ce({onEvent:e.onEvent,now:c,runId:e.runId||`turn-${x}`,threadId:e.threadId||""}),b=Number(h.window)||0,q=F(u.findLast(A=>A?.role==="user")),j=[],B=(A={})=>({status:"prepared",lane:"chat",route:null,messages:u,attachments:[],withheld:[],steps:[],tools:G({window:b,question:q,answered:L(u),reference:he(u).length>0}),context:Y({window:b,question:q,answered:L(u)}),world:!1,research:!1,answered:L(u),answer:null,parts:[],facts:[],knowledge:null,plan:{steps:j},timing:{ms:c()-x},...A});f.runStarted({window:b});try{const A=e.resume?.checkpoint?.route||null;let n=A||Ve({messages:u,reach:k,target:h,settings:m,now:c});if(!n)return f.runFinished({lane:"chat",status:"prepared"}),B();const K=Array.isArray(u[n.at]?.attachments)?u[n.at].attachments:[],_=K.find(a=>a?.kind==="page")||null,D=u[n.at]?.ambientPage,g=_||(D?.url&&(k.has("page:read_page")||k.has("read_page"))?D:null),M=(n.material||[]).filter(a=>a.attachment!==_),C={page:g?{title:g.title||"",url:g.url||""}:!1,documents:[...(n.documents||[]).map(a=>({title:a.title||"",type:a.type||"",pages:a.pages??null,fresh:(n.fresh||[]).includes(a)})),...M.map(a=>({title:a.attachment.title||a.attachment.kind,type:a.attachment.kind,material:!0,fresh:a.fresh}))]},E={documents:typeof e.documents?.open=="function",gather:typeof e.execute=="function"&&k.size>0,decide:typeof l.decide=="function",read:typeof(l.read||l.decide)=="function",write:typeof l.write=="function",rerank:typeof e.rerank=="function",knowledge:typeof e.knowledge?.search=="function"&&n.kb?.length>0};E.gather||(n={...n,items:[],planned:[]});const t={messages:u,question:q,window:b,target:h,settings:m,reach:k,route:n,can:E,attachments:[],withheld:[],steps:[],facts:[],parts:[],answer:null,found:!1,text:"",budget:{searches:0},timing:{},handoff:null},Z=a=>{for(const i of a?.steps||[])j.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}:{}})},ke=()=>e.pageIndex?.cache?{page:{cache:e.pageIndex.cache,budgetChars:me({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:c,limits:e.limits?.gather||{},budget:t.budget,remember:e.remember||{},signal:e.signal||null,read:e.read||null,rerank:e.rerank||null,...ke(),...a}),W={async decide(){const a=u.map(S=>({role:S.role,content:F(S),...S.pending?{pending:!0}:{}})),i=c();f.stepStarted("decide",{label:"Deciding what to look up"});const s=S=>l.decide(S,{maxTokens:160,schema:ve(Ie(k,{attached:C}),{attached:C}),role:"decide"}),r=await Te({messages:a,reach:k,planned:n.planned,complete:s,attached:C,now:c}).catch(()=>null),p=u[n.at]?.pageChosen===!0&&!!C.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=c()-i;return 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}),o?.items.length&&t.steps.push({kind:"decide",tool:"decide",input:{parts:o.items.length},label:"Decided what to look up",status:"ok",ms:y}),o},async knowledge(a,i,s){const r=e.knowledge,d=c();f.stepStarted("knowledge",{label:"Searching the knowledge base"});const p=l.read||l.decide||null,o=await Ke(t.question,{search:r.search,outline:r.outline||null,read:r.read||null,complete:p?(w,T)=>p(w,{...T,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&&m.ask!==!1,now:c,late:()=>!!e.signal?.aborted,onProgress:w=>f.custom("knowledge",w)}),y=c()-d;if(o.ask&&s.answer===void 0)throw f.stepFinished("knowledge",{label:o.ask.question,status:"waiting",ms:y}),new ce({...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 S=o.read.reduce((w,T)=>w+(T.passages?.length||0),0),O=o.frame?.whole?"Knowledge base: the outline read":o.hits.length?`Knowledge base: ${o.hits.length} passage${o.hits.length===1?"":"s"} found, ${S} read`:"Knowledge base: nothing matched";return t.knowledge={hits:o.hits.length,read:S,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:O,status:"ok",ms:y}),f.stepFinished("knowledge",{label:O,status:"ok",ms:y}),{found:o.hits.length,read:S,rounds:o.rounds}},async document(){const a=c(),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)?Ue(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 Me({question:t.route.intent?.request||t.question,documents:d,open:p,budgetChars:me({window:b,small:t.route.small})})}catch(w){const T=c()-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:T}),f.stepFinished("document",{label:"The attached document could not be read",status:"error",ms:T}),{read:0,skipped:d.length}}const y=c()-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 S=o.read.reduce((w,T)=>w+T.pages.length,0),O=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:S},label:O,status:o.read.length?"ok":"none",ms:y}),f.stepFinished("document",{label:O,status:o.read.length?"ok":"none",ms:y}),{read:o.read.length,pages:S,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&&Qe.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 de(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=Oe(t.route.parts),i=l.read||l.decide,s=async d=>{const p=R({need:"web",query:d},{reach:k})[0];if(!p)return{results:[],status:"no-engines"};const o=await de([p],ee({attach:!1})),y=o.results[0],S=y&&(y.status==="ok"||y.status==="cached")?Fe(y.text).results:[],O=S.length?"ok":y?.why?"budget":je(y?.note)||(String(y?.status||"").startsWith("error")?"error":"nothing");return{results:S,status:O,step:o.steps[0]}},r=await Le({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:Ye({concurrency:h.concurrency,device:h.kind==="device"}),...e.limits?.facts||{}},late:()=>!!e.signal?.aborted,now:c});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=Ne({parts:t.parts,facts:t.facts});t.answer={text:r.text,final:!0,note:r.note}}const i=L(u),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:q,answered:s,decided:t.route.decided,reference:se()}),t.context=Y({window:t.route.agent?0:b,question:q,answered:s}),{answered:s,offer:t.tools.offer,final:!!t.answer?.final}},async ask(a,i,s){if(s.answer===void 0)throw new ce(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 l.write({messages:U(),tools:t.tools,context:t.context,lane:t.lane},{onToken:d=>f.textContent(a,d)}),r=Ze({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:{},ye=a=>(i,s,r)=>typeof H[a]=="function"?H[a](i,s,{...r,turn:t,defaults:W}):W[a](i,s,r),te=Re({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 ye(r)(a,i,s)}},hooks:e.hooks||null,now:c}),ne={rule:()=>({provider:"harness"}),capability:()=>null,model:a=>a.role==="write"?E.write?{model:"write"}:null:a.role==="decide"||a.kind==="decide"?E.decide?{model:"decide"}:null:{model:"read"}},se=()=>(n.documents||[]).length>0&&!(t.document?.read?.length>0),U=()=>t.attachments.length||t.withheld.length?u.map((a,i)=>i===n.at?{...a,attachments:[...(a.attachments||[]).filter(s=>!t.withheld.includes(s)),...t.attachments]}:a):u;if(!A&&!n.kept&&E.gather&&E.decide&&!n.agent&&Ee({window:b,local:!!h.local,chosen:!!h.chosen,allowed:m.lookups!==!1,messages:u.map(a=>({role:a.role,content:F(a)})),reach:k,planned:n.planned,attached:C})){const a=c(),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=c()-a;let s=i.outputs.decide;if(s?.intent?.aboutDocument===!0&&M.length&&!M.some(d=>d.fresh)&&!(n.documents||[]).length&&!Ge(M.map(d=>d.attachment),ze(q))){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"&&_&&!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!==_)&&(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"),!_&&g&&t.withheld.push({kind:"page",title:g.title||"",url:g.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"?fe.test(q):V.test(q))?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"?fe.test(q):V.test(q))?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)?P.filter(d=>X([d])):[];r.length?(t.arm=r,t.tools={offer:!0,rounds:ie(b)?Ae: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||q},t.answer={text:Pe,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&&m.home&&n.items.length&&(n={...n,items:$e(n.items,m.home)}),n={...n,settings:{pipeline:m.pipeline===!0},can:E,world:n.world||z(n.items)},t.route=n;const ae=Array.isArray(e.lanes)&&e.lanes.length?e.lanes.map(pe):I,$=A&&ae.find(a=>a.id===e.resume.checkpoint.lane)||ae.find(a=>{try{return!!a.when(n)}catch{return!1}})||we.at(-1);t.lane=$.id,f.stateDelta([{op:"add",path:"/lane",value:$.id},{op:"add",path:"/need",value:n.decided||(n.items[0]?_e(n.items[0])?"web":n.items[0].kind:"none")}]),f.stepStarted("lane",{lane:$.id});const be=c(),xe=$.plan(n).filter(a=>a.role!=="write"||E.write),N=await te.run(le({id:`turn-${$.id}`,origin:"chat",flow:!0,steps:xe},ne),{...e.resume?{resume:{outputs:e.resume.checkpoint?.outputs||{},answers:e.resume.answers||{}}}:{}});Z(N),t.timing.laneMs=c()-be,f.stepFinished("lane",{lane:$.id,status:N.status});const qe={lane:$.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:$.id,route:qe,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:q,answered:t.found||L(u),decided:n.decided,reference:se()}),context:t.context||Y({window:b,question:q,answered:t.found||L(u)}),world:n.world,research:!!n.research&&!n.world,answered:t.answered??(t.found||L(u)),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:j},timing:{...t.timing,ms:c()-x},window:b};if(N.status==="waiting"){const{settings:a,can:i,...s}=n,r={...oe,status:"waiting",ask:N.waiting[0]?.ask||null,checkpoint:{lane:$.id,route:s,outputs:N.checkpoint.outputs,waiting:N.waiting.map(d=>d.stepId)}};return f.runFinished({lane:$.id,status:"waiting"}),r}const re=t.answer&&(t.answer.final||E.write)?"answered":"prepared";return f.runFinished({lane:$.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 St(e={},{askPerson:c=null,maxAsks:x=2,fallback:u=null}={}){let h=await ge(e);for(let m=0;m<x&&h.status==="waiting"&&h.ask;m+=1){let l=null;try{l=typeof c=="function"?await c(h.ask):null}catch{l=null}const k=Array.isArray(h.ask.options)?h.ask.options:[],P=l!=null&&String(l).trim()?String(l).trim():u??(k.length?k[k.length-1]:""),f=h.ask.step||h.checkpoint?.waiting?.[0]||"ask";h=await ge({...e,resume:{checkpoint:h.checkpoint,answers:{...e.resume?.answers||{},[f]:P}}})}return h}function Ze(e={},{answer:c="",shims:x=null}={}){if(e.answer?.final)return{text:e.answer.text,note:e.answer.note||""};const u=Xe(c);if(u.fired)try{x?.fire?.("answer.wrapper-echo",{lines:u.fired})}catch{}const h=u.text;if(!h.trim())return{text:h,note:""};const m=Je(h,e.messages||[]).echoed;if(m)try{x?.fire?.("answer.context-echo",{})}catch{}const l=We({answer:h,messages:e.messages||[],window:e.window??0});return{text:l?`${h}
3
3
 
4
- ${m}`:u,note:m,...h?{echoed:!0}:{}}}export{Te as ACT_HANDOFF_TEXT,wt as TURN_STAGES,pt as defineLane,Xe as finishTurn,gt as listLanes,Ge as routeByRule,we as runTurnPipeline,kt as runTurnPipelineAsking};
4
+ ${l}`:h,note:l,...m?{echoed:!0}:{}}}export{Pe as ACT_HANDOFF_TEXT,xt as TURN_STAGES,qt as defineLane,Ze as finishTurn,At as listLanes,Ve as routeByRule,ge as runTurnPipeline,St as runTurnPipelineAsking};
package/web-research.js CHANGED
@@ -1,7 +1,7 @@
1
- import{fuseRRF as F,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 W,basisLabel as T,hostOf as le}from"./offers.js";import{fenceUntrusted as ue}from"./page-guard.js";import{markdownUrl as U}from"./citations.js";const C=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}),I="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(?:(?:${I})\.?\s+\d{1,2}(?:st|nd|rd|th)?(?:\s*(?:-|–|to|until)\s*(?:(?:${I})\.?\s+)?\d{1,2}(?:st|nd|rd|th)?)?(?:,?\s+\d{4})?|\d{1,2}(?:st|nd|rd|th)?\s+(?:${I})\b(?:\s+\d{4})?|(?:in|during|for|this|next|early|mid|late)\s+(?:${I})\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(`^(?:${I}|${Y}|today|tomorrow|tonight|next|this|the|a|an|my|our|me|us|\\d+)$`,"i"),fe=/\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,de=/\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 H(e){const t=String(e||"").replace(fe,"").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=de.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?H(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?H(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?H(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}]),P=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,pe=/\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,Z=/\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(Z,"").replace(Z,"");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,(i,a,s)=>(!t[a]&&!s&&(r=!1),t[a]||""));return r?o.replace(/\s+/g," ").trim():""}function Pe(e,{previous:t=null,now:r=Date.now()}={}){const o=String(e||"").trim();if(!o||o.length>400)return null;const i=o.split(/\s+/).length,a=t?.kind==="research"&&t.research?.domain?t.research:null;let s=B.find(l=>l.match&&l.match.test(o))||null;const h=s?s.slots.filter(l=>D[l.id]?.(o)).length:0,f=!be.test(o)&&i>=2&&(Q.test(o)||pe.test(o)&&(s||ge.test(o))||me.test(o)||s&&(/\b(?:find|search|look|book|get|need)\b/i.test(o)||h>=2));if(!f&&a&&i<=14&&(!s||s.id===a.domain)){const l=P(a.domain),b=Object.fromEntries(l.slots.map(c=>[c.id,D[c.id]?.(o)||""]).filter(([,c])=>c));return Object.keys(b).length?J(`${a.question} ${o}`,l,{...a.slots,...b},r,!0,l.subject?"":a.subject):null}if(!f)return null;s||=P("product");const d=Object.fromEntries(s.slots.map(l=>[l.id,D[l.id]?.(o)||""]).filter(([,l])=>l));return J(o,s,d,r,!1)}function J(e,t,r,o,i,a=""){const s=String(new Date(o).getFullYear()),h=a||(t.subject?V(t.subject,r):ye(e,t)),f={...r,subject:h,year:s},d=t.queries.map(c=>V(c,f)).filter(Boolean),l=i?"":e.replace(G,"").replace(Z,"").replace(/^(?:a|an|the)\s+/i,"").trim(),b=(l?re(l,{extra:d,max:C.queries*2}):[...new Set(d)]).filter(c=>c.split(/\s+/).length>=2).slice(0,C.queries);return{question:e,domain:t.id,subject:h,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:i}}function $e(e,t=[],{now:r=Date.now()}={}){const o=String(new Date(r).getFullYear()),i=P(e.domain),a=i.slots.map(l=>e.slots?.[l.id]).filter(Boolean).join(" "),s=e.subject,h=[`${s} ${a} price ${o}`,i.forms?`${s} ${a} average cost`:`${s} ${a} cost`,`${s} ${a} comparison`,`${s} ${a}`],f=new Set(t.map(l=>l.toLowerCase().replace(/\s+/g," ").trim())),d=[];for(const l of h){const b=l.replace(/\s+/g," ").trim();b.split(/\s+/).length>=2&&!f.has(b.toLowerCase())&&!d.includes(b)&&d.push(b)}return d.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(a=>a?.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 i=[];for(const a of t.slice(o).split(/\n+---\n+(?=### \[\d+\])/)){const s=/### \[(\d+)\] ([^\n]*)\n<([^>\s]+)>\n\n?([\s\S]*)$/.exec(a);s&&i.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:i}}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(([i])=>!X.test(i)).sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>`${i}=${a}`).join("&");return`${t.hostname.replace(/^www\./,"").toLowerCase()}${t.pathname.replace(/\/+$/,"")||"/"}${o?`?${o}`:""}`}catch{return String(e||"")}}function ve(e,t=C.passageChars){const r=[];let o="";const i=()=>{const a=o.trim();a.length>=40&&r.push(a),o=""};for(const a of String(e||"").split(/\n\s*\n/)){const s=a.replace(/[ \t]+/g," ").trim();if(s)if(s.length>t){i();let h="";for(const f of s.split(/(?<=[.!?])\s+/))h&&h.length+f.length+1>t&&(o=h,i(),h=""),h=h?`${h} ${f}`:f.slice(0,t);o=h,i()}else o.length+s.length+2>t?(i(),o=s):o=o?`${o}
2
- ${s}`:s}return i(),r}async function ee(e,t,r,o){const i=new Array(e.length);let a=0;const s=Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;a<e.length;){const h=a++;try{i[h]=await r(e[h],h)}catch{i[h]=null}}});return await(o?Promise.race([Promise.all(s),o]):Promise.all(s)),i}async function je({ask:e,search:t,read:r=null,rerank:o=null,now:i=()=>Date.now(),until:a=null,limits:s={},onProgress:h=()=>{}}={}){if(!e||typeof t!="function")throw new Error("webResearch: ask and search required");const f={...C,...s},d=i(),l=()=>i()-d>f.ms;let b=!1;const c=a?a.then(()=>{b=!0}):null,q=P(e.domain),E=[],v=[],x=new Map,A=new Set;let u=0,p=null;const m=(S,R)=>{try{h({phase:S,label:R,searches:E.length,pages:x.size,offers:p?.offerCount||0})}catch{}};let k=e.queries.slice(0,f.queries);for(let S=1;S<=f.rounds&&k.length;S++){m("search",`Searching: ${k.map($=>`“${$}”`).join(", ")}`);const R=await ee(k,f.parallel,async $=>ke(await t($)),c);if(k.forEach(($,n)=>{E.push($);const g=R[n];if(!g?.results?.length){u+=1;return}g.engines.forEach(y=>A.add(y));const w=[];g.results.forEach(y=>{const L=qe(y.url);w.push(L);const M=x.get(L),z=String(y.text||y.snippet||"");M?(M.foundBy.push($),z.length>M.text.length&&(M.text=z)):x.set(L,{key:L,url:xe(y.url),title:y.title||y.url,host:le(y.url),text:z,foundBy:[$]})}),v.push(w)}),r&&!b&&!l()){const $=te(v,x,f).filter(n=>n.text.length<400).slice(0,f.read);if($.length){m("read",`Reading ${$.length} page${$.length===1?"":"s"}`);const n=await ee($,f.parallel,g=>r(g.url),c);$.forEach((g,w)=>{const y=n[w],L=typeof y=="string"?y:y?.text;L&&L.length>g.text.length&&(g.text=String(L),y?.title&&(g.title=y.title))})}}if(p=await se({ask:e,d:q,lists:v,pages:x,L:f,rerank:o}),m("decide",Se(p)),p.enough||b||l()||S===f.rounds)break;k=$e(e,E,{now:d})}p||=await se({ask:e,d:q,lists:v,pages:x,L:f,rerank:null});const j={searches:E.length,failed:u,pages:x.size,sites:new Set([...x.values()].map(S=>S.host)).size,engines:[...A],ms:Math.max(0,i()-d)},O={ask:e,queries:E,...p,stats:j};return{...O,text:Ee(O,f)}}function te(e,t,r){const o=new Map,i=[];for(const{id:a}of F(e)){const s=t.get(a);if(!s?.host)continue;const h=o.get(s.host)||0;if(!(h>=r.perHost)&&(o.set(s.host,h+1),i.push(s),i.length>=r.pages))break}return i}async function se({ask:e,d:t,lists:r,pages:o,L:i,rerank:a}){const s=te(r,o,i),h=new Map(s.map((n,g)=>[n.key,g])),f=[e.subject,...Object.values(e.slots||{}),...t.terms],d=t.id!=="product"||Q.test(e.question)||!!e.slots?.budget||/\b(?:cheap|costs?|deals?|quotes?|rates?)\b|[$€£]/i.test(e.question),l=[];for(const n of s)ve(n.text,i.passageChars).forEach((g,w)=>l.push({id:`${n.key}#${w}`,key:n.key,url:n.url,host:n.host,title:n.title,text:g}));const b=`${f.join(" ")}${d?" price cost per month":""}`,c=l.length?ne(oe(l),b).map(n=>n.id):[],q=[...l].sort((n,g)=>h.get(n.key)-h.get(g.key)).map(n=>n.id),E=d?l.filter(n=>/[$€£]\s?\d|\d\s?(?:€|£|USD|EUR|GBP)\b/.test(n.text)).map(n=>n.id):[],v=[c,q,...E.length?[E]:[]];if(typeof a=="function"&&c.length){const n=c.slice(0,40).map(g=>l.find(w=>w.id===g));try{const g=await a(e.question,n.map(w=>w.text));Array.isArray(g)&&g.length===n.length&&v.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 x=new Set(c),A=new Map(l.map(n=>[n.id,n])),u=new Map,p=[];for(const{id:n}of F(v)){if(!x.has(n))continue;const g=A.get(n),w=u.get(g.host)||0;if(!(w>=2)&&(u.set(g.host,w+1),p.push(g),p.length>=i.passages))break}const m=d?ie(s.flatMap(n=>ae(n.text,{url:n.url,title:n.title,terms:f,max:i.offers}))):{basis:"",currency:"",ranked:[],floors:[],other:[],averages:[]},k=[];for(const n of s){const g=t.forms||/\bquote\b/i.test(e.question)?ce(n.text):"";if(g&&!k.some(w=>w.host===n.host)&&k.push({url:n.url,title:n.title,host:n.host,cta:g}),k.length>=i.forms)break}const j=m.ranked.length+m.floors.length,O=new Set([...m.ranked,...m.floors].map(n=>n.host)).size,S=m.ranked.some(n=>n.seenOn>=2),R=new Set(p.map(n=>n.host)).size,$=d?j>=3&&O>=2||S&&m.ranked.length>=2:p.length>=4&&R>=3;return{pages:s,passages:p,offers:m,forms:k,enough:$,offerCount:j,wantPrices:d}}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={...C,...t};if(!e?.pages?.length)return"";const o=new Map,i=u=>(o.has(u.url)||o.set(u.url,{n:o.size+1,title:u.title||u.host||u.url,url:u.url}),o.get(u.url).n),a=u=>`[${i(u)}](${U(u.url)})`,{offers:s,forms:h,passages:f,ask:d,stats:l}=e,b=P(d.domain),c=[];c.push(`(ALREADY RESEARCHED on the web for the question below — ${l.searches} search${l.searches===1?"":"es"}, ${l.pages} page${l.pages===1?"":"s"} from ${l.sites} site${l.sites===1?"":"s"}, ${(l.ms/1e3).toFixed(1)} s. 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: ${_(d.question,200)}`);const q=b.slots.filter(u=>d.slots?.[u.id]).map(u=>`${u.id} = ${d.slots[u.id]}`);if(c.push(`Looking for: ${d.subject}${b.id!=="product"?` (${b.label})`:""}${q.length?` · known: ${q.join(" · ")}`:""}`),d.missing?.length&&c.push(`Missing for a personalised price: ${d.missing.map(u=>u.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 u=s.basis==="month"?"per month":T(s.basis);if(s.ranked.length){c.push(`Prices found (cheapest first, ${u}${s.currency?`, ${s.currency}`:""}):`);const p=[];for(const m of s.ranked){const k=p.find(j=>j.o.currency===m.currency&&Math.round(j.o.value*100)===Math.round(m.value*100));k?k.also.some(j=>j.url===m.url)||k.also.push(m):p.push({o:m,also:[]})}p.slice(0,r.offers).forEach(({o:m,also:k},j)=>{const O=[m,...k].map(a).filter((S,R,$)=>$.indexOf(S)===R).join(" ");c.push(`${j+1}. ${W(m.value,m.currency,s.basis)}${m.converted?` (${m.raw} ${T(m.basis)})`:""} — “${_(m.quote,160)}” ${O}${m.seenOn>1?` · stated by ${m.seenOn} sites`:""}`)})}else c.push("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(p=>`${W(p.value,p.currency,s.basis)} ${a(p)}`).join(" · ")}`),s.other.length&&c.push(`On another basis or currency (not comparable with the list above): ${s.other.slice(0,4).map(p=>`${p.raw} ${T(p.basis)} ${a(p)}`).join(" · ")}`),s.averages.length&&c.push(`Averages (context, not offers): ${s.averages.slice(0,3).map(p=>`${p.raw} ${T(p.basis)} — “${_(p.quote,100)}” ${a(p)}`).join(" · ")}`)}if(h.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 u of h)c.push(`- ${u.host}: “${u.cta}” ${a(u)}`)}const E=f.map(u=>`[${i(u)}] ${u.title?`${_(u.title,80)} — `:""}${u.text}`);c.push(""),c.push("Sources:");for(const u of o.values())c.push(`[${u.n}] [${_(u.title,90)}](${U(u.url)})`);let v=c.join(`
3
- `);const x=r.briefChars-v.length-200;let A="";for(const u of E){if(A.length+u.length+2>x)break;A+=`${A?`
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?`
4
4
 
5
- `:""}${u}`}return A&&(v+=`
5
+ `:""}${a}`}return v&&(k+=`
6
6
 
7
- ${ue(A,{source:"web search results"})}`),v}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:i=()=>Date.now(),until:a=null,onProgress:s=()=>{},limits:h={}}={}){const f=async l=>{const b=Ae(e,l),c=await t(b.tool,b.input,{prefetched:!0,research:!0}),q=typeof c=="string"?c:c?.text;if(!q||/^(?:error\b|\w+ failed\b|\{"error")/i.test(q))throw new Error("search failed");return q},d=await je({ask:e.research,search:f,read:r,rerank:o,now:i,until:a,limits:h,onProgress:s});return{text:d.text,result:d}}export{C as WEB_RESEARCH_LIMITS,B as WEB_TASK_DOMAINS,xe as cleanUrl,qe as pageKey,ke as parseSearchText,ve as passagesOf,$e as refineQueries,Pe as researchAsk,Ee as researchBrief,Ae as researchCall,_e as runResearch,je as webResearch};
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};
@@ -1,19 +1,19 @@
1
- import{markdownUrl as g}from"./citations.js";import{summarizeSearch as f,engineLabel as w}from"./search-outcome.js";import{offTopic as b,contentQuery as k}from"./web-search.js";const c={nothing:"nothing found",blocked:"search blocked",resting:"every engine resting",offline:"offline","no-engines":"no engine on"};function C(e){const i=String(e||"").replace(/^ChatPanel\s*·\s*/u,"").trim().toLowerCase();return Object.keys(c).find(o=>c[o]===i)||""}const y="web_search",$='You can call web_search to look up current information from the web — prices, news, recent events, documentation, or anything time-sensitive or that may have changed since your training. Call it whenever the user asks about such things instead of guessing or saying you are unsure. Cite results inline as markdown links — e.g. ([1](https://…)) — never HTML, <sup>, or bare numbers, and finish with a "Sources" list of the links you used.',v=Object.freeze({name:y,annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:"Search the web and return ranked result snippets with their source URLs. Use this for current events, live prices/quotes, news, product/library docs, or any fact you are unsure about or that may have changed since training — prefer it over guessing.",parameters:{type:"object",properties:{query:{type:"string",description:"The search query — a few keywords work best."}},required:["query"],additionalProperties:!1}});function S(e){if(!e?.results?.length){if(Array.isArray(e?.asked)||Array.isArray(e?.resting)){const{line:s,advice:l}=f(e);return`No web results for "${e?.query||""}"${s?` (${s})`:""}. ${l} Do NOT conclude the information is unavailable; say plainly that the search failed and why.`}const t=(e?.engines||[]).join(", ");return`No web results for "${e?.query||""}"`+(t?` (searched: ${t}).`:".")+" This may mean the engine blocked the request rather than that nothing exists — do NOT conclude the information is unavailable. Try a shorter, more general query (drop dates and qualifiers), and tell the user they can enable another search engine in ChatPanel settings if it keeps failing."}const i=Array.isArray(e.engines)?e.engines:[],o=e.results.map(t=>`[${t.rank}] [${t.title}](${g(t.url)})`).join(`
2
- `),a=g(e.results[0].url),n=`Web search results for "${e.query}" (engines: ${i.join(", ")}).
1
+ import{markdownUrl as g}from"./citations.js";import{summarizeSearch as y,engineLabel as b}from"./search-outcome.js";import{offTopic as k,contentQuery as $}from"./web-search.js";const f={nothing:"nothing found",blocked:"search blocked",resting:"every engine resting",offline:"offline","no-engines":"no engine on"};function x(n){const a=String(n||"").replace(/^ChatPanel\s*·\s*/u,"").trim().toLowerCase();return Object.keys(f).find(i=>f[i]===a)||""}const p="web_search",A='You can call web_search to look up current information from the web — prices, news, recent events, documentation, or anything time-sensitive or that may have changed since your training. Call it whenever the user asks about such things instead of guessing or saying you are unsure. Cite results inline as markdown links — e.g. ([1](https://…)) — never HTML, <sup>, or bare numbers, and finish with a "Sources" list of the links you used.',_=Object.freeze({name:p,annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:"Search the web and return ranked result snippets with their source URLs. Use this for current events, live prices/quotes, news, product/library docs, or any fact you are unsure about or that may have changed since training — prefer it over guessing.",parameters:{type:"object",properties:{query:{type:"string",description:"The search query — a few keywords work best."}},required:["query"],additionalProperties:!1}}),S=/^(?:gclid|gbraid|wbraid|dclid|msclkid|cmc_adid|tw_adid|hvadid|adgrpid|nb_oii|nb_adtype|ad_?click_?id|irclickid)$/i;function m(n){let a;try{a=new URL(String(n||""))}catch{return!1}for(const i of a.searchParams.keys())if(S.test(i))return!0;return/^nb[:%]/i.test(a.searchParams.get("nbt")||"")}function v(n){const a=Array.isArray(n?.results)?n.results:[],i=a.filter(r=>m(r?.url)).length,e=i?{...n,results:a.filter(r=>!m(r?.url)).map((r,l)=>({...r,rank:l+1}))}:n,t=i?` ${i} sponsored result${i===1?" was":"s were"} left out (ads, not results).`:"";if(!e?.results?.length&&i)return`No web results for "${e?.query||""}" other than ads.${t} Try other words, or open a store's own search in your tab.`;if(!e?.results?.length){if(Array.isArray(e?.asked)||Array.isArray(e?.resting)){const{line:l,advice:s}=y(e);return`No web results for "${e?.query||""}"${l?` (${l})`:""}. ${s} Do NOT conclude the information is unavailable; say plainly that the search failed and why.`}const r=(e?.engines||[]).join(", ");return`No web results for "${e?.query||""}"`+(r?` (searched: ${r}).`:".")+" This may mean the engine blocked the request rather than that nothing exists — do NOT conclude the information is unavailable. Try a shorter, more general query (drop dates and qualifiers), and tell the user they can enable another search engine in ChatPanel settings if it keeps failing."}const u=Array.isArray(e.engines)?e.engines:[],c=e.results.map(r=>`[${r.rank}] [${r.title}](${g(r.url)})`).join(`
2
+ `),o=g(e.results[0].url),d=`Web search results for "${e.query}" (engines: ${u.join(", ")}).${t}
3
3
 
4
- Citation rules: when a claim draws on a result below, cite it inline as a markdown link to that result's URL — e.g. ([1](${a})). Cite multiple sources as separate links: ([1](url)) ([3](url)). Do NOT output HTML, <sup>, or bare bracket numbers like [1] — every citation must be a clickable markdown link. Finish with a "Sources" section that repeats, as markdown links, each source you cited.
4
+ Citation rules: when a claim draws on a result below, cite it inline as a markdown link to that result's URL — e.g. ([1](${o})). Cite multiple sources as separate links: ([1](url)) ([3](url)). Do NOT output HTML, <sup>, or bare bracket numbers like [1] — every citation must be a clickable markdown link. Finish with a "Sources" section that repeats, as markdown links, each source you cited.
5
5
 
6
6
  Sources:
7
- ${o}`,u=e.results.map(t=>`### [${t.rank}] ${t.title}
8
- <${t.url}>
7
+ ${c}`,h=e.results.map(r=>`### [${r.rank}] ${r.title}
8
+ <${r.url}>
9
9
 
10
- ${t.text}`).join(`
10
+ ${r.text}`).join(`
11
11
 
12
12
  ---
13
13
 
14
- `);return`${n}
14
+ `);return`${d}
15
15
 
16
16
  ---
17
17
  Result details:
18
18
 
19
- ${u}`}function _({search:e}={}){if(typeof e!="function")throw new Error("webSearchToolProvider: search required");return{specs:[v],system:$,async execute(i,o){if(i!==y)return JSON.stringify({error:`Unknown tool: ${i}`});const a=String(o?.query||"").trim();if(!a)return"No query provided to web_search.";try{let n=await e(a),u="";const t=(r,m)=>!!r?.results?.length&&!b(r.results,m),s=t(n,a)?"":k(a);if(s){const r=await e(s).catch(()=>null);(t(r,s)||!n?.results?.length&&r?.results?.length)&&(n=r,u=s)}const l=[...new Set((n?.results||[]).map(r=>r.engine).filter(Boolean))].map(r=>w(r)),h=(l.length?l:n?.engines||[]).join(", "),d=!n?.results?.length&&Array.isArray(n?.asked)?c[f(n).status]:"",p=u?` · searched as "${u.slice(0,60)}"`:"";return{text:S(n),note:`${d?`ChatPanel · ${d}`:h?`ChatPanel · ${h}`:"ChatPanel"}${p}`}}catch(n){return`web_search failed: ${n?.message||n}`}}}}export{v as WEB_SEARCH_SPEC,y as WEB_SEARCH_TOOL_NAME,$ as WEB_SEARCH_TOOL_SYSTEM,C as searchFailureOf,S as searchResultsToText,_ as webSearchToolProvider};
19
+ ${h}`}function E({search:n}={}){if(typeof n!="function")throw new Error("webSearchToolProvider: search required");return{specs:[_],system:A,async execute(a,i){if(a!==p)return JSON.stringify({error:`Unknown tool: ${a}`});const e=String(i?.query||"").trim();if(!e)return"No query provided to web_search.";try{let t=await n(e),u="";const c=(s,w)=>!!s?.results?.length&&!k(s.results,w),o=c(t,e)?"":$(e);if(o){const s=await n(o).catch(()=>null);(c(s,o)||!t?.results?.length&&s?.results?.length)&&(t=s,u=o)}const d=[...new Set((t?.results||[]).map(s=>s.engine).filter(Boolean))].map(s=>b(s)),h=(d.length?d:t?.engines||[]).join(", "),r=!t?.results?.length&&Array.isArray(t?.asked)?f[y(t).status]:"",l=u?` · searched as "${u.slice(0,60)}"`:"";return{text:v(t),note:`${r?`ChatPanel · ${r}`:h?`ChatPanel · ${h}`:"ChatPanel"}${l}`}}catch(t){return`web_search failed: ${t?.message||t}`}}}}export{_ as WEB_SEARCH_SPEC,p as WEB_SEARCH_TOOL_NAME,A as WEB_SEARCH_TOOL_SYSTEM,m as isAdUrl,x as searchFailureOf,v as searchResultsToText,E as webSearchToolProvider};