@chatpanel/events 0.433.0 → 0.446.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sideline.js CHANGED
@@ -1,21 +1,21 @@
1
- import{approxTokens as y,queryTerms as k}from"./sources-retrieval.js";const I=Object.freeze(["sideline","breakout"]),L="bringback",m="thread";import{SIDELINE_SLASH_ITEMS as W}from"./slash-commands.js";function O(t){const e=/^\/(sideline|breakout)\b\s*([\s\S]*)$/i.exec(String(t||"").trim());if(!e)return null;let i=e[2].trim(),n=null;const r=/^@(?:(team|agent|cli|model):)?(?:"([^"]+)"|([^\s]+))\s*/i.exec(i);return r&&(n={kind:r[1]?r[1].toLowerCase():null,name:(r[2]||r[3]||"").trim()},i=i.slice(r[0].length).trim()),{question:i,target:n}}function j(t){const e=/^\/bringback\b\s*(full|brief)?\s*$/i.exec(String(t||"").trim());return e?{mode:e[1]?e[1].toLowerCase():"brief"}:null}function C(t,{teams:e=[],agents:i=[],clis:n=[],models:r=[]}={}){if(!t?.name)return null;const a=t.name.toLowerCase(),o=s=>String(s||"").toLowerCase()===a,l=[["team",e,s=>o(s.name)||o(s.id)],["agent",i,s=>o(s.name)||o(s.id)],["cli",n,s=>o(s.id)||o(s.label)||o(s.name)],["model",r,s=>o(s.id)||o(s.label)||o(s.model)||o(s.name)]];for(const[s,u,c]of l){if(t.kind&&t.kind!==s)continue;const h=(u||[]).find(d=>d&&c(d));if(h)return{kind:s,ref:h}}return null}function N(t=[]){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"))}const p=Object.freeze({chat:"message",sideline:"message",note:"section",meeting:"segment",run:"post",text:"part"});function x(t=""){const e=[];let i=null;const n=()=>{i&&i.text.trim()&&e.push({label:i.label,text:i.text.trim()}),i=null};for(const r of String(t||"").split(`
1
+ import{approxTokens as y,queryTerms as k}from"./sources-retrieval.js";const I=Object.freeze(["sideline","breakout"]),L="bringback",m="thread";import{SIDELINE_SLASH_ITEMS as G}from"./slash-commands.js";function O(t){const e=/^\/(sideline|breakout)\b\s*([\s\S]*)$/i.exec(String(t||"").trim());if(!e)return null;let i=e[2].trim(),n=null;const r=/^@(?:(team|agent|cli|model):)?(?:"([^"]+)"|([^\s]+))\s*/i.exec(i);return r&&(n={kind:r[1]?r[1].toLowerCase():null,name:(r[2]||r[3]||"").trim()},i=i.slice(r[0].length).trim()),{question:i,target:n}}function j(t){const e=/^\/bringback\b\s*(full|brief)?\s*$/i.exec(String(t||"").trim());return e?{mode:e[1]?e[1].toLowerCase():"brief"}:null}function C(t,{teams:e=[],agents:i=[],clis:n=[],models:r=[]}={}){if(!t?.name)return null;const a=t.name.toLowerCase(),o=s=>String(s||"").toLowerCase()===a,l=[["team",e,s=>o(s.name)||o(s.id)],["agent",i,s=>o(s.name)||o(s.id)],["cli",n,s=>o(s.id)||o(s.label)||o(s.name)||o(s.bridgeAgent)],["model",r,s=>o(s.id)||o(s.label)||o(s.model)||o(s.name)]];for(const[s,d,c]of l){if(t.kind&&t.kind!==s)continue;const h=(d||[]).find(u=>u&&c(u));if(h)return{kind:s,ref:h}}return null}function N(t=[]){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"))}const p=Object.freeze({chat:"message",sideline:"message",note:"section",meeting:"segment",run:"post",text:"part"});function x(t=""){const e=[];let i=null;const n=()=>{i&&i.text.trim()&&e.push({label:i.label,text:i.text.trim()}),i=null};for(const r of String(t||"").split(`
2
2
  `)){const a=/^(#{1,6})\s+(.*)$/.exec(r);if(a){n(),i={label:a[2].trim().slice(0,80)||"section",text:""};continue}if(!r.trim()){i&&!i.label?n():i&&(i.text+=`
3
3
  `);continue}i||(i={label:"",text:""}),i.text+=(i.text?`
4
- `:"")+r}return n(),e.map((r,a)=>({n:a+1,label:r.label||`paragraph ${a+1}`,text:r.text}))}function g(t){if(!t)return{kind:"text",title:"",units:[],focus:"",sources:[]};if(Array.isArray(t.units))return{kind:t.kind||"text",title:t.title||"",units:t.units,focus:t.focus||"",sources:t.sources||[]};const e=t.body||t,n=!!(t.sidelineOf||t.meta?.sidelineOf)?"sideline":t.kind||(Array.isArray(e.messages)?"chat":e.markdown!=null?"note":Array.isArray(e.segments)?"meeting":"text"),r=t.title||"",a=(e.attachments||[]).filter(o=>o&&o.kind!=="image"&&(o.title||o.url));if(n==="chat"||n==="sideline"){const o=N(e.messages||[]),l=[...o].reverse().find(u=>u.role==="user"),s=(e.messages||[]).flatMap(u=>(u.attachments||[]).filter(c=>c&&c.kind!=="image"&&c.kind!=="sideline"&&(c.title||c.url)));return{kind:n,title:r,sources:[...a,...s],units:o.map((u,c)=>({n:c+1,label:u.role,text:String(u.content||"")})),focus:String(l?.content||"")}}if(n==="note")return{kind:n,title:r,sources:a,units:x(e.markdown??e.text??""),focus:""};if(n==="meeting"){const o=Array.isArray(e.segments)?e.segments:[],l=o.length?o.map((s,u)=>({n:u+1,label:s.speaker||s.who||"speaker",text:String(s.text||"")})):x(e.summary?`# Summary
4
+ `:"")+r}return n(),e.map((r,a)=>({n:a+1,label:r.label||`paragraph ${a+1}`,text:r.text}))}function g(t){if(!t)return{kind:"text",title:"",units:[],focus:"",sources:[]};if(Array.isArray(t.units))return{kind:t.kind||"text",title:t.title||"",units:t.units,focus:t.focus||"",sources:t.sources||[]};const e=t.body||t,n=!!(t.sidelineOf||t.meta?.sidelineOf)?"sideline":t.kind||(Array.isArray(e.messages)?"chat":e.markdown!=null?"note":Array.isArray(e.segments)?"meeting":"text"),r=t.title||"",a=(e.attachments||[]).filter(o=>o&&o.kind!=="image"&&(o.title||o.url));if(n==="chat"||n==="sideline"){const o=N(e.messages||[]),l=[...o].reverse().find(d=>d.role==="user"),s=(e.messages||[]).flatMap(d=>(d.attachments||[]).filter(c=>c&&c.kind!=="image"&&c.kind!=="sideline"&&(c.title||c.url)));return{kind:n,title:r,sources:[...a,...s],units:o.map((d,c)=>({n:c+1,label:d.role,text:String(d.content||"")})),focus:String(l?.content||"")}}if(n==="note")return{kind:n,title:r,sources:a,units:x(e.markdown??e.text??""),focus:""};if(n==="meeting"){const o=Array.isArray(e.segments)?e.segments:[],l=o.length?o.map((s,d)=>({n:d+1,label:s.speaker||s.who||"speaker",text:String(s.text||"")})):x(e.summary?`# Summary
5
5
  ${e.summary}
6
6
 
7
7
  ${e.text||e.transcript||""}`:e.text||e.transcript||"");return{kind:n,title:r,sources:a,units:l,focus:String(e.summary||"").slice(0,240)}}if(n==="run"||Array.isArray(e.posts)){const o=e.posts||e.steps||[];return{kind:"run",title:r,sources:a,units:o.map((l,s)=>({n:s+1,label:l.actor||l.by||l.role||"post",text:String(l.text||l.content||"")})),focus:String(e.goal||e.request||"")}}return{kind:"text",title:r,sources:a,units:x(e.text||e.markdown||""),focus:""}}function A(t={}){const e=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages,attachments:t.sources}}:t),i=p[e.kind]||"part",n=e.kind==="note"?"Main note":e.kind==="meeting"?"Meeting":e.kind==="run"?"Team run":"Main thread",r=String(e.focus||"").replace(/\s+/g," ").trim().slice(0,240),a=(e.sources||[]).map(l=>l?.title||l?.url).filter(Boolean).slice(0,6);return[`${n}${e.title?`: "${e.title}"`:""} — ${e.units.length} ${i}${e.units.length===1?"":"s"}, ~${y(e.units.map(l=>l.text).join(" "))} tokens.`,r?e.kind==="meeting"?`Summary: "${r}${r.length===240?"…":""}"`:`It is currently working on: "${r}${r.length===240?"…":""}"`:"",a.length?`Attached there: ${a.join(" · ")}.`:"",`Its content is NOT in this conversation. Call \`${m}\` to search it or read a range of ${i}s when the question depends on it — and only then.`].filter(Boolean).join(`
8
- `)}const q=Object.freeze({name:m,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Search or read what this sideline branched from — the main thread, note, meeting or run. Its content is not in this conversation; use this when the question depends on what was said or found there.",parameters:{type:"object",properties:{action:{type:"string",enum:["search","read","latest"],description:"search: parts matching a query (numbered). read: parts from..to by number. latest: the last n parts."},query:{type:"string",description:"For search: what you are looking for."},from:{type:"integer",description:"For read: first part number (1 = oldest)."},to:{type:"integer",description:"For read: last part number (inclusive)."},n:{type:"integer",description:"For latest: how many (default 4)."}},required:["action"],additionalProperties:!1}}),S=320;function T(t,e){const i=String(t||"").replace(/\s+/g," ").trim();if(i.length<=S)return i;const n=i.toLowerCase();let r=-1;for(const o of e)if(r=n.indexOf(o),r>=0)break;const a=Math.max(0,r-80);return`${a?"…":""}${i.slice(a,a+S)}…`}function $(t={},e={}){const i=t.units?t:g(t.messages?{kind:"chat",body:{messages:t.messages}}:t),n=i.units.map(o=>({n:o.n,role:o.label,text:String(o.text||"")})),r=String(e?.action||"latest");if(r==="search"){const o=k(e?.query);if(!o.length)return{error:"search needs a query."};const l=n.map(s=>({...s,score:o.reduce((u,c)=>u+(s.text.toLowerCase().includes(c)?Math.min(3,c.length/4):0),0)})).filter(s=>s.score>0).sort((s,u)=>u.score-s.score||s.n-u.n).slice(0,6).sort((s,u)=>s.n-u.n).map(s=>({n:s.n,role:s.role,snippet:T(s.text,o)}));return{of:n.length,hits:l,note:l.length?'Read a range with action "read" for the full text.':"Nothing there mentions that."}}if(r==="read"){const o=Math.max(1,Number(e?.from)||1),l=Math.min(n.length,Number(e?.to)||o);if(o>n.length)return{error:`There are ${n.length} ${p[i.kind]||"part"}s.`};const s=n.filter(d=>d.n>=o&&d.n<=l);let u=2e3*4;const c=[];let h=!1;for(const d of s){if(u<=0){h=!0;break}const f=d.text.length>u?`${d.text.slice(0,u)}…`:d.text;f.length<d.text.length&&(h=!0),u-=f.length,c.push({n:d.n,role:d.role,text:f})}return{of:n.length,from:o,to:l,messages:c,truncated:h}}const a=Math.max(1,Math.min(12,Number(e?.n)||4));return{of:n.length,messages:n.slice(-a).map(o=>({n:o.n,role:o.role,text:o.text.length>1600?`${o.text.slice(0,1600)}…`:o.text}))}}function _(t={},e="",{maxChars:i=2400}={}){const n=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages}}:t),r=n.units.filter(c=>String(c.text||"").trim());if(!r.length)return"";const a=r.slice(-2).reverse().map(c=>c.n);if(k(e).length)for(const c of $(n,{action:"search",query:e}).hits||[])a.push(c.n);const o=new Map(r.map(c=>[c.n,c])),l=[];let s=0;for(const c of[...new Set(a)]){const h=o.get(c);if(!h)continue;const d=i-s;if(d<160)break;const f=String(h.text).replace(/\s+\n/g,`
9
- `).trim(),b=f.length>d?`${f.slice(0,d-1)}…`:f;l.push({n:c,label:h.label,text:b}),s+=b.length}l.sort((c,h)=>c.n-h.n);const u=p[n.kind]||"part";return[`From the main thread${n.title?` "${n.title}"`:""} — ${l.length} of its ${r.length} ${u}${r.length===1?"":"s"}: the latest, and what mentions this question. Answer the side question with this in mind${r.length>l.length?`; \`${m}\` reads the rest`:""}.`,...l.map(c=>`[${c.n}] ${c.label}: ${c.text}`)].join(`
10
- `)}function v(t={}){const e=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages,attachments:t.sources}}:t),i=A(e);return{specs:[{...q}],system:i,systemParts:{thread:y(i)},async execute(n,r){if(n!==m)return JSON.stringify({error:`Unknown tool: ${n}`});const a=typeof r=="string"?JSON.parse(r||"{}"):r||{};return JSON.stringify($(e,a))}}}function P({title:t="",turns:e=[]}={}){const i=(e||[]).filter(n=>n&&(n.role==="user"||n.role==="assistant")).map(n=>`${n.role==="user"?"Asked":"Answered"}: ${String(n.content||"").trim()}`).join(`
8
+ `)}const q=Object.freeze({name:m,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Search or read what this sideline branched from — the main thread, note, meeting or run. Its content is not in this conversation; use this when the question depends on what was said or found there.",parameters:{type:"object",properties:{action:{type:"string",enum:["search","read","latest"],description:"search: parts matching a query (numbered). read: parts from..to by number. latest: the last n parts."},query:{type:"string",description:"For search: what you are looking for."},from:{type:"integer",description:"For read: first part number (1 = oldest)."},to:{type:"integer",description:"For read: last part number (inclusive)."},n:{type:"integer",description:"For latest: how many (default 4)."}},required:["action"],additionalProperties:!1}}),S=320;function T(t,e){const i=String(t||"").replace(/\s+/g," ").trim();if(i.length<=S)return i;const n=i.toLowerCase();let r=-1;for(const o of e)if(r=n.indexOf(o),r>=0)break;const a=Math.max(0,r-80);return`${a?"…":""}${i.slice(a,a+S)}…`}function $(t={},e={}){const i=t.units?t:g(t.messages?{kind:"chat",body:{messages:t.messages}}:t),n=i.units.map(o=>({n:o.n,role:o.label,text:String(o.text||"")})),r=String(e?.action||"latest");if(r==="search"){const o=k(e?.query);if(!o.length)return{error:"search needs a query."};const l=n.map(s=>({...s,score:o.reduce((d,c)=>d+(s.text.toLowerCase().includes(c)?Math.min(3,c.length/4):0),0)})).filter(s=>s.score>0).sort((s,d)=>d.score-s.score||s.n-d.n).slice(0,6).sort((s,d)=>s.n-d.n).map(s=>({n:s.n,role:s.role,snippet:T(s.text,o)}));return{of:n.length,hits:l,note:l.length?'Read a range with action "read" for the full text.':"Nothing there mentions that."}}if(r==="read"){const o=Math.max(1,Number(e?.from)||1),l=Math.min(n.length,Number(e?.to)||o);if(o>n.length)return{error:`There are ${n.length} ${p[i.kind]||"part"}s.`};const s=n.filter(u=>u.n>=o&&u.n<=l);let d=2e3*4;const c=[];let h=!1;for(const u of s){if(d<=0){h=!0;break}const f=u.text.length>d?`${u.text.slice(0,d)}…`:u.text;f.length<u.text.length&&(h=!0),d-=f.length,c.push({n:u.n,role:u.role,text:f})}return{of:n.length,from:o,to:l,messages:c,truncated:h}}const a=Math.max(1,Math.min(12,Number(e?.n)||4));return{of:n.length,messages:n.slice(-a).map(o=>({n:o.n,role:o.role,text:o.text.length>1600?`${o.text.slice(0,1600)}…`:o.text}))}}function _(t={},e="",{maxChars:i=2400}={}){const n=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages}}:t),r=n.units.filter(c=>String(c.text||"").trim());if(!r.length)return"";const a=r.slice(-2).reverse().map(c=>c.n);if(k(e).length)for(const c of $(n,{action:"search",query:e}).hits||[])a.push(c.n);const o=new Map(r.map(c=>[c.n,c])),l=[];let s=0;for(const c of[...new Set(a)]){const h=o.get(c);if(!h)continue;const u=i-s;if(u<160)break;const f=String(h.text).replace(/\s+\n/g,`
9
+ `).trim(),b=f.length>u?`${f.slice(0,u-1)}…`:f;l.push({n:c,label:h.label,text:b}),s+=b.length}l.sort((c,h)=>c.n-h.n);const d=p[n.kind]||"part";return[`From the main thread${n.title?` "${n.title}"`:""} — ${l.length} of its ${r.length} ${d}${r.length===1?"":"s"}: the latest, and what mentions this question. Answer the side question with this in mind${r.length>l.length?`; \`${m}\` reads the rest`:""}.`,...l.map(c=>`[${c.n}] ${c.label}: ${c.text}`)].join(`
10
+ `)}function P(t={}){const e=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages,attachments:t.sources}}:t),i=A(e);return{specs:[{...q}],system:i,systemParts:{thread:y(i)},async execute(n,r){if(n!==m)return JSON.stringify({error:`Unknown tool: ${n}`});const a=typeof r=="string"?JSON.parse(r||"{}"):r||{};return JSON.stringify($(e,a))}}}function v({title:t="",turns:e=[]}={}){const i=(e||[]).filter(n=>n&&(n.role==="user"||n.role==="assistant")).map(n=>`${n.role==="user"?"Asked":"Answered"}: ${String(n.content||"").trim()}`).join(`
11
11
 
12
12
  `);return[`This was a side conversation${t?` about "${t}"`:""}, held apart from a main thread that is still being worked on. Write the brief the main thread should receive.`,"Rules: at most 120 words. State what was asked, the answer, any decision or recommendation, and anything still open. Plain prose or up to four short bullets. No preamble, no headings, no restating the main thread.","",i].join(`
13
- `)}function B({sideline:t,mode:e="brief",brief:i="",now:n=Date.now,newId:r=()=>`sl_${Math.random().toString(36).slice(2,10)}`}={}){const a=(t?.turns||[]).filter(u=>u&&(u.role==="user"||u.role==="assistant")),o=a.map(u=>`${u.role==="user"?"Asked":"Answered"}: ${String(u.content||"").trim()}`).join(`
13
+ `)}function B({sideline:t,mode:e="brief",brief:i="",now:n=Date.now,newId:r=()=>`sl_${Math.random().toString(36).slice(2,10)}`}={}){const a=(t?.turns||[]).filter(d=>d&&(d.role==="user"||d.role==="assistant")),o=a.map(d=>`${d.role==="user"?"Asked":"Answered"}: ${String(d.content||"").trim()}`).join(`
14
14
 
15
- `),l=e==="full"?o:String(i||"").trim()||o,s=`From Sideline ${t?.index||1}${t?.model?` · ${t.model}`:""}`;return{id:r(),role:"note",kind:"sideline",ts:n(),content:l,sideline:{id:t?.id||null,index:t?.index||1,model:t?.model||"",turns:a.length,mode:e,broughtBackAt:n()},attachments:[{kind:"sideline",title:s,text:l}]}}function D(t=[]){const e=Array.isArray(t)?t:[];if(!e.some(r=>r?.role==="note"))return e;const i=[];let n=[];for(const r of e){if(r?.role==="note"){n.push(...r.attachments||[]);continue}if(r?.role==="user"&&n.length){i.push({...r,attachments:[...n,...r.attachments||[]]}),n=[];continue}i.push(r)}return i}function J(t=[]){return(t||[]).reduce((e,i)=>Math.max(e,Number(i?.index)||0),0)+1}function F(t,e){const i=[];let n=t,r=0;for(;n&&(n.sideline||n.meta?.sideline)&&r++<16;)i.unshift((n.sideline||n.meta?.sideline)?.index||1),n=e?.(n)||null;return i.join(".")}function U(t,e){if(t==="note"){const i=e.attachments?.[0]?.title||`From Sideline ${e.sideline?.index||1}`,n=String(e.content||"").trim().split(`
15
+ `),l=e==="full"?o:String(i||"").trim()||o,s=`From Sideline ${t?.index||1}${t?.model?` · ${t.model}`:""}`;return{id:r(),role:"note",kind:"sideline",ts:n(),content:l,sideline:{id:t?.id||null,index:t?.index||1,model:t?.model||"",turns:a.length,mode:e,broughtBackAt:n()},attachments:[{kind:"sideline",title:s,text:l}]}}function D(t=[]){const e=Array.isArray(t)?t:[];if(!e.some(r=>r?.role==="note"))return e;const i=[];let n=[];for(const r of e){if(r?.role==="note"){n.push(...r.attachments||[]);continue}if(r?.role==="user"&&n.length){i.push({...r,attachments:[...n,...r.attachments||[]]}),n=[];continue}i.push(r)}return i}function F(t=[]){return(t||[]).reduce((e,i)=>Math.max(e,Number(i?.index)||0),0)+1}function J(t,e){const i=[];let n=t,r=0;for(;n&&(n.sideline||n.meta?.sideline)&&r++<16;)i.unshift((n.sideline||n.meta?.sideline)?.index||1),n=e?.(n)||null;return i.join(".")}function H(t,e){if(t==="note"){const i=e.attachments?.[0]?.title||`From Sideline ${e.sideline?.index||1}`,n=String(e.content||"").trim().split(`
16
16
  `).map(r=>`> ${r}`).join(`
17
17
  `);return{kind:"markdown",markdown:`
18
18
 
19
19
  > **${i}**
20
20
  ${n}
21
- `}}return{kind:"message",message:e}}const w="sideline",E=Object.freeze({name:w,annotations:{readOnlyHint:!1,idempotentHint:!1},description:"Open a SIDELINE — a separate conversation about one question, apart from this one — and get its brief back. Use it to fork a sub-question to a team, an agent or another model without cluttering this thread; the sideline can search or read this thread with its own `thread` tool. Returns the brief (or the full text) when it is done.",parameters:{type:"object",properties:{question:{type:"string",description:"The question or task for the sideline, self-contained."},target:{type:"string",description:"Optional: who answers — a team name, an agent name, a CLI agent or a model id. Omit for the same model as this conversation."},bring:{type:"string",enum:["brief","full"],description:"What comes back: a brief (default) or the full exchange."}},required:["question"],additionalProperties:!1}});function H({run:t,depth:e=0,maxDepth:i=3}={}){if(typeof t!="function")throw new Error("sidelineToolProvider: run required");return{id:"sideline",specs:[{...E}],system:"You may fork a sub-question into a `sideline` (a team, an agent or a model works on it apart from this thread and you get the brief back). Use it for work that would otherwise clutter this thread; do not use it for a question you can answer directly.",async execute(n,r){if(n!==w)return JSON.stringify({error:`Unknown tool: ${n}`});const a=typeof r=="string"?JSON.parse(r||"{}"):r||{},o=String(a.question||"").trim();if(!o)return JSON.stringify({error:"question is required."});if(e>=i)return JSON.stringify({error:`Sidelines nest at most ${i} deep; answer this one here.`});const l=a.target&&O(`/sideline @${/\s/.test(String(a.target))?`"${a.target}"`:a.target} x`)?.target||null;try{const s=await t({question:o,target:l,bring:a.bring==="full"?"full":"brief"});return JSON.stringify({sideline:s?.index!=null?`Sideline ${s.index}`:"sideline",id:s?.id||null,model:s?.model||"",brief:String(s?.brief||"")})}catch(s){return JSON.stringify({error:`The sideline failed: ${s?.message||s}`})}}}}export{L as BRINGBACK_COMMAND,I as SIDELINE_COMMANDS,W as SIDELINE_SLASH_ITEMS,w as SIDELINE_TOOL_NAME,E as SIDELINE_TOOL_SPEC,m as THREAD_TOOL_NAME,q as THREAD_TOOL_SPEC,P as briefPrompt,U as foldBackFor,B as foldBackNote,D as foldNotes,J as nextSidelineIndex,x as noteUnits,j as parseBringBack,O as parseSideline,$ as readThread,C as resolveSidelineTarget,_ as sidelineExcerpt,F as sidelinePath,H as sidelineToolProvider,g as sourceOf,A as threadManifest,v as threadToolProvider};
21
+ `}}return{kind:"message",message:e}}const w="sideline",E=Object.freeze({name:w,annotations:{readOnlyHint:!1,idempotentHint:!1},description:"Get work that needs code done (python, a script, an xlsx/docx/pdf/pptx file) by a coding agent here — or hand any task to another agent, team or model — in a SIDELINE apart from this thread, and get its brief back. For code, target claude, codex or opencode with the whole task. Also forks a sub-question without cluttering this thread; the sideline can search or read this thread with its own `thread` tool. Returns the brief (or the full text) when it is done.",parameters:{type:"object",properties:{question:{type:"string",description:"The question or task for the sideline, self-contained."},target:{type:"string",description:"Optional: who answers — a team name, an agent name, a CLI agent or a model id. Omit for the same model as this conversation."},bring:{type:"string",enum:["brief","full"],description:"What comes back: a brief (default) or the full exchange."}},required:["question"],additionalProperties:!1}});function R({run:t,depth:e=0,maxDepth:i=3}={}){if(typeof t!="function")throw new Error("sidelineToolProvider: run required");return{id:"sideline",specs:[{...E}],system:"You may fork a sub-question into a `sideline` (a team, an agent or a model works on it apart from this thread and you get the brief back). Use it for work that would otherwise clutter this thread; do not use it for a question you can answer directly.",async execute(n,r){if(n!==w)return JSON.stringify({error:`Unknown tool: ${n}`});const a=typeof r=="string"?JSON.parse(r||"{}"):r||{},o=String(a.question||"").trim();if(!o)return JSON.stringify({error:"question is required."});if(e>=i)return JSON.stringify({error:`Sidelines nest at most ${i} deep; answer this one here.`});const l=a.target&&O(`/sideline @${/\s/.test(String(a.target))?`"${a.target}"`:a.target} x`)?.target||null;try{const s=await t({question:o,target:l,bring:a.bring==="full"?"full":"brief"});return JSON.stringify({sideline:s?.index!=null?`Sideline ${s.index}`:"sideline",id:s?.id||null,model:s?.model||"",brief:String(s?.brief||"")})}catch(s){return JSON.stringify({error:`The sideline failed: ${s?.message||s}`})}}}}export{L as BRINGBACK_COMMAND,I as SIDELINE_COMMANDS,G as SIDELINE_SLASH_ITEMS,w as SIDELINE_TOOL_NAME,E as SIDELINE_TOOL_SPEC,m as THREAD_TOOL_NAME,q as THREAD_TOOL_SPEC,v as briefPrompt,H as foldBackFor,B as foldBackNote,D as foldNotes,F as nextSidelineIndex,x as noteUnits,j as parseBringBack,O as parseSideline,$ as readThread,C as resolveSidelineTarget,_ as sidelineExcerpt,J as sidelinePath,R as sidelineToolProvider,g as sourceOf,A as threadManifest,P as threadToolProvider};
package/skill-files.js CHANGED
@@ -1,7 +1,13 @@
1
- import{skillHandle as y,skillPackageFiles as k}from"./skill-runtime.js";const u=24e3,g="skill_file";function x({skillRun:e,read:l}){return!(Array.isArray(e?.files)?e.files.filter(Boolean):[]).length||!e?.origin?.source||typeof l!="function"?null:{id:"skill-files",specs:[{name:g,description:"Read one reference file that the active skill ships. Only the exact paths listed in the skill instructions are available. Read one at a time, and only when the task needs it.",input_schema:{type:"object",properties:{path:{type:"string",description:"A reference path this skill's instructions point at, e.g. references/auth.md or foundry-agent/deploy/deploy.md"}},required:["path"]}}],async execute(h,d){if(h!==g)return null;const n=String(d?.path||"").trim();if(n.split("/")[0]==="scripts")return`${n} is a script — it runs, it is not read as text.`;try{const s=await l(e.origin,n),a=String(s?.text??"");return a.trim()?a.length>u?`${a.slice(0,u)}
1
+ import{skillHandle as x,skillPackageFiles as L,skillsNamed as k}from"./skill-runtime.js";const y=24e3,A="skill_file";function E({skillRun:e,read:i}){return!(Array.isArray(e?.files)?e.files.filter(Boolean):[]).length||!e?.origin?.source||typeof i!="function"?null:{id:"skill-files",specs:[{name:A,description:"Read one reference file that the active skill ships. Only the exact paths listed in the skill instructions are available. Read one at a time, and only when the task needs it.",input_schema:{type:"object",properties:{path:{type:"string",description:"A reference path this skill's instructions point at, e.g. references/auth.md or foundry-agent/deploy/deploy.md"}},required:["path"]}}],async execute(r,c){if(r!==A)return null;const p=String(c?.path||"").trim();if(p.split("/")[0]==="scripts")return`${p} is a script — it runs, it is not read as text.`;try{const l=await i(e.origin,p),o=String(l?.text??"");return o.trim()?o.length>y?`${o.slice(0,y)}
2
2
 
3
- …[truncated — ${a.length-u} more characters]`:a:`${n} is empty.`}catch(s){return`Could not read ${n}: ${s?.message||s}`}}}}function _(e,{prompt:l=e?.prompt??null}={}){return{command:y(e),name:e?.name||y(e),description:e?.description||"",files:k(e),origin:e?.origin?.source?{source:e.origin.source,id:e.origin.id||""}:null,prompt:l}}function L({entries:e=[],loadPrompt:l,read:m}){const h=e.filter(i=>i&&i.command);if(!h.length)return null;const d=new Map(h.map(i=>[i.command,i])),n=new Map,s=[{name:"skill_open",description:"Load a skill from the SKILLS AVAILABLE list to get its full instructions. Open one only when the request clearly matches it, then follow what it returns.",input_schema:{type:"object",properties:{name:{type:"string",enum:[...d.keys()].slice(0,60)}},required:["name"]}}];return typeof m=="function"&&h.some(i=>i.files?.length)&&s.push({name:"skill_file",description:"Read one reference file from a skill you have opened with skill_open.",input_schema:{type:"object",properties:{skill:{type:"string"},path:{type:"string"}},required:["skill","path"]}}),{id:"skill-discovery",specs:s,async execute(i,c){if(i==="skill_open"){const p=String(c?.name??c?.skill??c?.id??c?.command??"").trim().toLowerCase(),t=d.get(p);if(!t)return`No such skill. Available: ${[...d.keys()].join(", ")}`;n.set(t.command,t);let o="";try{o=await l(t)||""}catch(f){return`Could not load ${t.name}: ${f?.message||f}`}let r=o.trim()||"(this skill has no extra instructions — just apply it.)";return r+=`
3
+ …[truncated — ${o.length-y} more characters]`:o:`${p} is empty.`}catch(l){return`Could not read ${p}: ${l?.message||l}`}}}}function I(e,{prompt:i=e?.prompt??null}={}){return{command:x(e),name:e?.name||x(e),description:e?.description||"",files:L(e),scripts:(Array.isArray(e?.files?.scripts)?e.files.scripts:[]).filter(t=>typeof t=="string"&&t).slice(0,20),origin:e?.origin?.source?{source:e.origin.source,id:e.origin.id||""}:null,prompt:i}}const j={claude:"claude",codex:"codex",opencode:"opencode",copilot:"copilot",gemini:"antigravity",kiro:"kiro",pi:"pi",hermes:"hermes"};function N({entries:e=[],userText:i="",armed:t=!1,runsCode:r=!0,codingAgents:c=[],loadPrompt:p,read:l}={}){const o=k(e,i).map(g=>g.command);if(!e.length||!t&&!o.length)return{provider:null,named:o,handoff:!1};const f=q({entries:e,loadPrompt:p,read:l,runsCode:r,codingAgents:c,quiet:!t});return{provider:f,named:o,handoff:!!f&&S({entries:e,runsCode:r,codingAgents:c})}}function S({entries:e=[],runsCode:i=!0,codingAgents:t=[]}={}){return!i&&Array.isArray(t)&&t.length>0&&e.some(r=>r?.scripts?.length)}function B(e=[]){const i=(Array.isArray(e)?e:[]).filter(t=>t&&(t.viaBridge===!0||t.providerType==="agent"||t.provider_type==="agent")&&t.available!==!1).map(t=>String(t.bridgeAgent||t.id||"")).filter(Boolean);return[...new Set(i)]}function D(e,{entries:i=[],runsCode:t=!0,codingAgents:r=[]}={}){return!e||!S({entries:i,runsCode:t,codingAgents:r})?null:{...e,quiet:!0,system:""}}function T(e,i=[]){const t=(Array.isArray(i)?i:[]).filter(c=>typeof c=="string"&&c),r=j[String(e||"")];return(r&&t.includes(r)?r:t[0])||""}function q({entries:e=[],loadPrompt:i,read:t,runsCode:r=!0,quiet:c=!1,codingAgents:p=[]}){const l=e.filter(s=>s&&s.command);if(!l.length)return null;const o=new Map(l.map(s=>[s.command,s])),f=new Map,g=[{name:"skill_open",description:"Load a skill from the SKILLS AVAILABLE list to get its full instructions. Open one only when the request clearly matches it, then follow what it returns.",input_schema:{type:"object",properties:{name:{type:"string",enum:[...o.keys()].slice(0,60)},from:{type:"string",description:"Only when the person names another agent's copy: claude, codex, opencode, copilot, gemini, kiro, pi or hermes."}},required:["name"]}}];typeof t=="function"&&l.some(s=>s.files?.length)&&g.push({name:"skill_file",description:"Read one reference file from a skill you have opened with skill_open.",input_schema:{type:"object",properties:{skill:{type:"string"},path:{type:"string"}},required:["skill","path"]}});const _=s=>k(l,s).map(a=>a.command);function b(s){const a=k(l,s).slice(0,2);return a.length?`[Chap] The installed skill ${a.map(n=>`\`${n.command}\`${n.origin?.source?` (${n.origin.source})`:""}`).join(", ")} fits this message. Through \`tools\`: {"action":"skill_open","args":{"name":"${a[0].command}"}} loads its instructions; the conversation above is the material to use.`:""}return{id:"skill-discovery",...c?{quiet:!0}:{},hint:b,named:_,specs:g,async execute(s,a){if(s==="skill_open"){const u=String(a?.name??a?.skill??a?.id??a?.command??"").trim().toLowerCase(),n=o.get(u);if(!n)return`No such skill. Available: ${[...o.keys()].join(", ")}`;const h=String(a?.from??"").trim().toLowerCase(),d=!r&&n.scripts?.length?T(n.origin?.source,p):"",m=!r&&n.scripts?.length?d?`This skill runs scripts (${n.scripts.join(", ")}), and you do not run code yourself — you hand the job to a coding agent on this machine, which has this skill: call \`tools\` with {"action":"sideline","args":{"target":"${d}","question":"Use the ${n.command} skill to … — <the whole task, with every value it needs from this conversation>. Save the file in ~/Downloads and reply with its path."}}. When it answers, tell the person what was made and where. Never say a script ran unless the sideline says so.`:`This skill's scripts (${n.scripts.join(", ")}) run only where code runs — in a coding agent, and none is reachable from this chat right now. Do not say they ran: do what the instructions allow without them, and say plainly what would need them.`:"";if(m&&f.has(n.command)&&(f.get(n.command).from||"")===h)return`You opened \`${n.command}\` already — its instructions are above.${m?` Next: ${m}`:" Apply them now."}`;f.set(n.command,h?{...n,from:h}:n);let $="";try{$=await i(n,{from:h})||""}catch(v){return`Could not load ${n.name}: ${v?.message||v}`}let w=$.trim()||"(this skill has no extra instructions — just apply it.)";return w+=`
4
4
 
5
- To read a reference file this skill points at, call skill_file with skill="${t.command}" and the path exactly as written in the instructions above.`,r}if(i==="skill_file"){const p=n.get(String(c?.skill||"").trim().toLowerCase());if(!p)return"Open the skill first with skill_open, then read its files.";const t=String(c?.path||"").trim();if(t.split("/")[0]==="scripts")return`${t} is a script — it runs, it is not read as text.`;if(!p.origin?.source)return`${p.name} has no package files on disk.`;try{const o=await m(p.origin,t),r=String(o?.text??"");return r.trim()?r.length>u?`${r.slice(0,u)}
5
+ To read a reference file this skill points at, call skill_file with skill="${n.command}" and the path exactly as written in the instructions above.`,m&&(w=`${m}
6
6
 
7
- …[truncated — ${r.length-u} more characters]`:r:`${t} is empty.`}catch(o){return`Could not read ${t}: ${o?.message||o}`}}return null}}}export{g as SKILL_FILE_TOOL,L as skillDiscoveryProvider,_ as skillEntry,x as skillFileProvider};
7
+ ---
8
+
9
+ ${w}
10
+
11
+ ${m}`),w}if(s==="skill_file"){const u=f.get(String(a?.skill||"").trim().toLowerCase());if(!u)return"Open the skill first with skill_open, then read its files.";const n=String(a?.path||"").trim();if(n.split("/")[0]==="scripts")return`${n} is a script — it runs, it is not read as text.`;if(!u.origin?.source)return`${u.name} has no package files on disk.`;try{const h=await t(u.origin,n,{from:u.from||""}),d=String(h?.text??"");return d.trim()?d.length>y?`${d.slice(0,y)}
12
+
13
+ …[truncated — ${d.length-y} more characters]`:d:`${n} is empty.`}catch(h){return`Could not read ${n}: ${h?.message||h}`}}return null}}}export{A as SKILL_FILE_TOOL,B as codingAgentsIn,T as handoffAgent,D as handoffSideline,S as needsHandoff,N as skillDiscoveryForTurn,q as skillDiscoveryProvider,I as skillEntry,E as skillFileProvider};
package/skill-runtime.js CHANGED
@@ -1,5 +1,5 @@
1
- import{sourceCitationSystem as g}from"./tool-hints.js";function y(e){const t=String(e||"none").toLowerCase();return t==="chat"||t==="chats"?"chats":t==="meeting"||t==="meetings"?"meetings":t==="all"||t==="both"||t==="history"?"all":"none"}function w(e){const t=String(e||"none").toLowerCase();return t==="none"||t==="off"?"none":t==="selected"||t==="select"?"selected":"default"}function S(e){return(e||[]).filter(t=>t&&t.enabled!==!1&&(t.url||t.command||t.tools?.length))}function b(e){return!!e&&e.enabled!==!1}function d(e){return(Array.isArray(e)?e:[]).filter(b)}function I(e={},{includeMeetings:t=!1}={}){const o=y(e.historyContext);let s=null;if(o!=="none"){const n=o==="meetings"||o==="all",r=n&&!t?"meetings":"";s={enabled:!r,scope:o,includeMeetings:n&&!!t,requested:o,...r?{blocked:r}:{}}}return{skillId:e.id||"",history:s,mcp:{mode:w(e.mcpMode),serverIds:Array.isArray(e.mcpServerIds)?e.mcpServerIds.filter(Boolean):[]},files:C(e),origin:e.origin&&e.origin.source?{source:e.origin.source,id:e.origin.id||""}:null,hosts:Array.isArray(e.sandboxHosts)?e.sandboxHosts.filter(n=>typeof n=="string"&&n):[]}}function C(e){const t=e?.files;if(!t||typeof t!="object")return[];const o=[];for(const s of["references","assets","templates","examples"])for(const n of Array.isArray(t[s])?t[s]:[])typeof n=="string"&&n&&o.push(`${s}/${n}`);return o.slice(0,60)}function x(e,t){const o=S(e),s=t?.mcp?.mode||"none";if(s==="none")return[];if(s!=="selected")return o;const n=new Set(t?.mcp?.serverIds||[]);return n.size?o.filter(r=>n.has(r.id)):[]}function $(e){const t=(e.tools||[]).map(o=>o.name).filter(Boolean).slice(0,12);return t.length?`${e.name||e.id}: ${t.join(", ")}`:`${e.name||e.id}`}function j(e,t=[]){if(!e)return"";const o=[];if(e.history?.enabled){const s=e.history.scope==="all"?"chat and meeting history":e.history.scope==="meetings"?"meeting history":"chat history";o.push(`This skill has ${s} tools available. Use history_search first when prior local context would improve the answer, then history_get_source or history_related when useful.`)}if(e.history?.blocked==="meetings"&&o.push("Meeting history was requested for this skill, but it is not available for the current plan."),e.files?.length&&o.push(`This skill ships reference files: ${e.files.join(", ")}. Their contents are NOT included above. Call skill_file with one of those exact paths to read one, and only when the task needs it — read the smallest set that answers the question.`),e.mcp?.mode==="none")o.push("MCP tools are disabled for this skill.");else if(e.mcp?.mode==="selected"){const s=x(t,e);s.length?o.push(`This skill is scoped to these MCP servers/tools: ${s.map($).join(" | ")}. Prefer these tools when they help complete the skill.`):o.push("This skill selected MCP tools, but none of the selected MCP servers are currently enabled.")}return(e.history?.enabled||e.mcp?.mode==="selected"||e.mcp?.mode==="default")&&o.push(g()),o.join(`
2
- `)}function u(e){return String(e?.command||e?.name||"").trim().toLowerCase()}const A=14;function L(e,t){if(!t.size)return 0;const o=`${e.name} ${e.command} ${e.description||""}`.toLowerCase(),s=new Set(o.split(/\W+/).filter(r=>r.length>3));let n=0;for(const r of t)s.has(r)&&(n+=1);return n}function v(e,t=""){const o=d(e),s=new Set(String(t||"").toLowerCase().split(/\W+/).filter(n=>n.length>3));return o.map((n,r)=>({s:n,i:r,score:L(n,s)})).sort((n,r)=>r.score-n.score||n.i-r.i).map(n=>n.s)}const M=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e;function P(e,{userText:t="",cap:o=A}={}){const s=d(e),n=v(e,t);if(!n.length)return"";let r=n.slice(0,o);const c=String(t||"").toLowerCase();if(c){const i=n.filter(l=>{const f=u(l),h=String(l.name||"").toLowerCase();return f&&c.includes(f)||h.length>2&&c.includes(h)});for(const l of i)r.includes(l)||(r=[l,...r].slice(0,o))}const a=new Map(s.map((i,l)=>[i,l]));r=[...r].sort((i,l)=>(a.get(i)??0)-(a.get(l)??0));const m=i=>`- ${u(i)||i.name}: ${M(String(i.description||i.name),90)}`,p=n.length>r.length?`
3
- (+${n.length-r.length} more — the user can type /command to run any skill directly.)`:"";return["SKILLS AVAILABLE — reusable procedures the user has set up. If the request clearly matches one, call skill_open with its name to load its full instructions, then follow them. For a simple or unrelated request, answer directly and do not open a skill.",r.map(m).join(`
4
- `)+p].join(`
5
- `)}export{d as enabledSkills,x as filterMcpServersForSkill,b as isSkillEnabled,v as rankSkills,P as skillCatalogSystem,u as skillHandle,C as skillPackageFiles,I as skillRunFromSkill,j as skillToolSystem};
1
+ import{sourceCitationSystem as u}from"./tool-hints.js";function p(e){const t=String(e||"none").toLowerCase();return t==="chat"||t==="chats"?"chats":t==="meeting"||t==="meetings"?"meetings":t==="all"||t==="both"||t==="history"?"all":"none"}function g(e){const t=String(e||"none").toLowerCase();return t==="none"||t==="off"?"none":t==="selected"||t==="select"?"selected":"default"}function y(e){return(e||[]).filter(t=>t&&t.enabled!==!1&&(t.url||t.command||t.from||t.tools?.length))}function S(e){return!!e&&e.enabled!==!1}function h(e){return(Array.isArray(e)?e:[]).filter(S)}function I(e={},{includeMeetings:t=!1}={}){const n=p(e.historyContext);let s=null;if(n!=="none"){const o=n==="meetings"||n==="all",r=o&&!t?"meetings":"";s={enabled:!r,scope:n,includeMeetings:o&&!!t,requested:n,...r?{blocked:r}:{}}}return{skillId:e.id||"",history:s,mcp:{mode:g(e.mcpMode),serverIds:Array.isArray(e.mcpServerIds)?e.mcpServerIds.filter(Boolean):[]},files:w(e),origin:e.origin&&e.origin.source?{source:e.origin.source,id:e.origin.id||""}:null,hosts:Array.isArray(e.sandboxHosts)?e.sandboxHosts.filter(o=>typeof o=="string"&&o):[]}}function w(e){const t=e?.files;if(!t||typeof t!="object")return[];const n=[];for(const s of["references","assets","templates","examples"])for(const o of Array.isArray(t[s])?t[s]:[])typeof o=="string"&&o&&n.push(`${s}/${o}`);return n.slice(0,60)}function b(e,t){const n=y(e),s=t?.mcp?.mode||"none";if(s==="none")return[];if(s!=="selected")return n;const o=new Set(t?.mcp?.serverIds||[]);return o.size?n.filter(r=>o.has(r.id)):[]}function x(e){const t=(e.tools||[]).map(n=>n.name).filter(Boolean).slice(0,12);return t.length?`${e.name||e.id}: ${t.join(", ")}`:`${e.name||e.id}`}function T(e,t=[]){if(!e)return"";const n=[];if(e.history?.enabled){const s=e.history.scope==="all"?"chat and meeting history":e.history.scope==="meetings"?"meeting history":"chat history";n.push(`This skill has ${s} tools available. Use history_search first when prior local context would improve the answer, then history_get_source or history_related when useful.`)}if(e.history?.blocked==="meetings"&&n.push("Meeting history was requested for this skill, but it is not available for the current plan."),e.files?.length&&n.push(`This skill ships reference files: ${e.files.join(", ")}. Their contents are NOT included above. Call skill_file with one of those exact paths to read one, and only when the task needs it — read the smallest set that answers the question.`),e.mcp?.mode==="none")n.push("MCP tools are disabled for this skill.");else if(e.mcp?.mode==="selected"){const s=b(t,e);s.length?n.push(`This skill is scoped to these MCP servers/tools: ${s.map(x).join(" | ")}. Prefer these tools when they help complete the skill.`):n.push("This skill selected MCP tools, but none of the selected MCP servers are currently enabled.")}return(e.history?.enabled||e.mcp?.mode==="selected"||e.mcp?.mode==="default")&&n.push(u()),n.join(`
2
+ `)}function m(e){return String(e?.command||e?.name||"").trim().toLowerCase()}const C=14;function A(e,t){if(!t.size)return 0;const n=`${e.name} ${e.command} ${e.description||""}`.toLowerCase(),s=new Set(n.split(/\W+/).filter(r=>r.length>3));let o=0;for(const r of t)s.has(r)&&(o+=1);return o}function $(e,t=""){const n=h(e),s=new Set(String(t||"").toLowerCase().split(/\W+/).filter(o=>o.length>3));return n.map((o,r)=>({s:o,i:r,score:A(o,s)})).sort((o,r)=>r.score-o.score||o.i-r.i).map(o=>o.s)}function L(e,t=""){const n=String(t||"").toLowerCase();if(!n)return[];const s=new Set(n.split(/[^a-z0-9_-]+/).filter(Boolean)),o=(l,i)=>{if(l.length!==i.length||i.length<4||l===i)return!1;const c=[...l].findIndex((d,a)=>d!==i[a]);return c>=0&&c<l.length-1&&l[c]===i[c+1]&&l[c+1]===i[c]&&l.slice(c+2)===i.slice(c+2)},r=l=>[m(l),String(l?.command||""),String(l?.name||"")].map(i=>i.toLowerCase()).filter(i=>i.length>2);return(Array.isArray(e)?e:[]).filter(l=>r(l).some(i=>(/[^a-z0-9]/.test(i)?n.includes(i)||n.includes(i.replace(/[-_]+/g," ")):s.has(i))||[...s].some(c=>o(c,i))))}const v=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e;function _(e,{userText:t="",cap:n=C}={}){const s=h(e),o=$(e,t);if(!o.length)return"";let r=o.slice(0,n);const l=new Set(L(o,t));for(const a of o.filter(f=>l.has(f)))r.includes(a)||(r=[a,...r].slice(0,n));const i=new Map(s.map((a,f)=>[a,f]));r=[...r].sort((a,f)=>(i.get(a)??0)-(i.get(f)??0));const c=a=>`- ${m(a)||a.name}: ${v(String(a.description||a.name),90)}`,d=o.length>r.length?`
3
+ (+${o.length-r.length} more — the user can type /command to run any skill directly.)`:"";return["SKILLS AVAILABLE — reusable procedures the user has set up. If the request clearly matches one, call skill_open with its name to load its full instructions, then follow them. For a simple or unrelated request, answer directly and do not open a skill.",r.map(c).join(`
4
+ `)+d].join(`
5
+ `)}export{h as enabledSkills,b as filterMcpServersForSkill,S as isSkillEnabled,$ as rankSkills,_ as skillCatalogSystem,m as skillHandle,w as skillPackageFiles,I as skillRunFromSkill,T as skillToolSystem,L as skillsNamed};
package/slash-commands.js CHANGED
@@ -1 +1 @@
1
- function f(e){return String(e||"").toLowerCase().replace(/^\//,"").replace(/\s+/g," ")}function g(e){return{type:"skill",command:e.command||"",icon:e.icon||"🎓",description:e.description||e.name||"",skill:e}}function h(e){return{type:"recipe",command:e.name||"",icon:"🧩",description:e.description||"Saved recipe",recipe:e}}function S(e){const n=!!e.origin?.agent;return{type:"team",command:e.name||"",icon:n?"🧑‍💻":"🧑‍🤝‍🧑",description:e.description||(n?"Agent":"Agent team"),team:e,...n?{agent:e.origin.agent}:{}}}function x(e){return!!e&&e.enabled!==!1}function s(e){return(Array.isArray(e)?e:[]).filter(x)}function w({builtins:e=[],skills:n=[],recipes:t=[],teams:i=[],prefix:o="",skillsAllowed:c=!1,features:m={}}={}){const a=f(o),u=(Array.isArray(e)?e:[]).map(r=>({type:"builtin",...r,locked:!!r.feature&&!m[r.feature]})),l=c?s(n).map(g):[],d=(t||[]).filter(r=>r&&r.enabled!==!1&&r.name).map(h),p=(i||[]).filter(r=>r&&r.enabled!==!1&&r.name).map(S);return[...u,...l,...d,...p].filter(r=>!(r.typed&&!a)).filter(r=>r.command&&r.command.toLowerCase().startsWith(a)).slice(0,12)}const b=Object.freeze([{command:"sideline",icon:"⇲",description:"Ask on the side without stopping this thread — @ a team, agent or model to hand it elsewhere"},{command:"bringback",icon:"⇱",description:'Fold the open sideline into this thread as a brief (or "full")'},{command:"breakout",icon:"⇲",description:"Same as /sideline"}]),$=Object.freeze([{command:"new",icon:"✚",description:"Start a new chat — this one stays in history"},{command:"clear",icon:"✚",description:"Same as /new"}]);function I(e){const n=/^\/(new|clear)\s*$/i.exec(String(e||"").trim());return n?{command:n[1].toLowerCase()}:null}const L=Object.freeze([{command:"bug",icon:"🐞",description:"Report a problem — a GitHub issue with this app’s diagnostics, shown to you first",typed:!0}]);function _(e){const n=/^\/bug(?:\s+([\s\S]*))?$/i.exec(String(e||"").trim());return n?{title:(n[1]||"").trim().replace(/\s+/g," ")}:null}const y=/^\/([a-z0-9_-]*(?:\s+[a-z0-9_-]*)?)$/i;function A(e,n=[]){const t=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!t)return null;const i=s(n).find(o=>String(o.command||"").toLowerCase()===t[1].toLowerCase());return i?{skill:i,args:t[2].trim()}:null}function C(e,n=[]){const t=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!t)return null;const i=(n||[]).find(o=>o&&o.enabled!==!1&&String(o.name||"").toLowerCase()===t[1].toLowerCase());return i?{recipe:i,args:t[2].trim()}:null}function z(e,n=""){const t=String(n||"").trim();return`Run the saved recipe "${e.name}"${t?` with this input: ${t}`:""}. Use the recipe tool; if a parameter is missing, ask for it.`}function E(e,n=[]){const t=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!t)return null;const i=(n||[]).find(o=>o&&o.enabled!==!1&&String(o.name||"").toLowerCase()===t[1].toLowerCase());return i?{team:i,args:t[2].trim()}:null}function T(e,n=""){const t=String(n||"").trim();return e.origin?.agent?`Run the agent "${e.name}" (a one-role team of that name)${t?` on this request: ${t}`:""}. Use the team tool; if the request is unclear, ask first.`:`Run the saved team "${e.name}"${t?` on this request: ${t}`:""}. Use the team tool; if the request is unclear, ask first.`}function R(e){return e?.command?`/${e.command} `:"/"}function k(e,n=""){return e?.command?{command:e.command,args:String(n||"").trim(),name:e.name||"",icon:e.icon||"🎓"}:null}function H(e){return e?.command?`/${e.command}${e.args?` ${e.args}`:""}`:""}export{L as BUG_REPORT_SLASH_ITEMS,$ as NEW_THREAD_SLASH_ITEMS,b as SIDELINE_SLASH_ITEMS,y as SLASH_TYPING_RE,s as enabledSkills,x as isSkillEnabled,C as matchSlashRecipe,A as matchSlashSkill,E as matchSlashTeam,_ as parseBugCommand,I as parseNewThread,z as recipeInvocationText,H as skillInvocationLabel,k as skillInvocationOf,R as slashCommandInsert,w as slashCommandItems,T as teamInvocationText};
1
+ function x(e){return String(e||"").toLowerCase().replace(/^\//,"").replace(/\s+/g," ")}function c(e){return{type:"skill",command:e.command||"",icon:e.icon||"🎓",description:e.description||e.name||"",skill:e}}function w(e){return{type:"recipe",command:e.name||"",icon:"🧩",description:e.description||"Saved recipe",recipe:e}}function b(e){const t=!!e.origin?.agent;return{type:"team",command:e.name||"",icon:t?"🧑‍💻":"🧑‍🤝‍🧑",description:e.description||(t?"Agent":"Agent team"),team:e,...t?{agent:e.origin.agent}:{}}}function I(e){return!!e&&e.enabled!==!1}function m(e){return(Array.isArray(e)?e:[]).filter(I)}function $({builtins:e=[],skills:t=[],recipes:o=[],teams:a=[],prefix:r="",skillsAllowed:d=!1,features:u={},machineSkills:l=[]}={}){const i=x(r),p=(Array.isArray(e)?e:[]).map(n=>({type:"builtin",...n,locked:!!n.feature&&!u[n.feature]})),s=d?m(t).map(c):[],f=new Set(s.map(n=>n.command)),h=(l||[]).filter(n=>n?.command&&n.enabled!==!1&&!f.has(n.command)).map(n=>({...c(n),machine:!0,icon:"🧰"})),S=(o||[]).filter(n=>n&&n.enabled!==!1&&n.name).map(w),g=(a||[]).filter(n=>n&&n.enabled!==!1&&n.name).map(b);return[...p,...s,...S,...g,...h].filter(n=>!(n.typed&&!i)).filter(n=>n.command&&n.command.toLowerCase().startsWith(i)).slice(0,12)}const L=Object.freeze([{command:"sideline",icon:"⇲",description:"Ask on the side without stopping this thread — @ a team, agent or model to hand it elsewhere"},{command:"bringback",icon:"⇱",description:'Fold the open sideline into this thread as a brief (or "full")'},{command:"breakout",icon:"⇲",description:"Same as /sideline"}]),_=Object.freeze([{command:"new",icon:"✚",description:"Start a new chat — this one stays in history"},{command:"clear",icon:"✚",description:"Same as /new"}]);function y(e){const t=/^\/(new|clear)\s*$/i.exec(String(e||"").trim());return t?{command:t[1].toLowerCase()}:null}const C=Object.freeze([{command:"bug",icon:"🐞",description:"Report a problem — a GitHub issue with this app’s diagnostics, shown to you first",typed:!0}]);function A(e){const t=/^\/bug(?:\s+([\s\S]*))?$/i.exec(String(e||"").trim());return t?{title:(t[1]||"").trim().replace(/\s+/g," ")}:null}const z=/^\/([a-z0-9_-]*(?:\s+[a-z0-9_-]*)?)$/i;function E(e,t=[]){const o=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!o)return null;const a=m(t).find(r=>String(r.command||"").toLowerCase()===o[1].toLowerCase());return a?{skill:a,args:o[2].trim()}:null}function T(e,t=[]){const o=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!o)return null;const a=(t||[]).find(r=>r&&r.enabled!==!1&&String(r.name||"").toLowerCase()===o[1].toLowerCase());return a?{recipe:a,args:o[2].trim()}:null}function R(e,t=""){const o=String(t||"").trim();return`Run the saved recipe "${e.name}"${o?` with this input: ${o}`:""}. Use the recipe tool; if a parameter is missing, ask for it.`}function H(e,t=[]){const o=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!o)return null;const a=(t||[]).find(r=>r&&r.enabled!==!1&&String(r.name||"").toLowerCase()===o[1].toLowerCase());return a?{team:a,args:o[2].trim()}:null}function k(e,t=""){const o=String(t||"").trim();return e.origin?.agent?`Run the agent "${e.name}" (a one-role team of that name)${o?` on this request: ${o}`:""}. Use the team tool; if the request is unclear, ask first.`:`Run the saved team "${e.name}"${o?` on this request: ${o}`:""}. Use the team tool; if the request is unclear, ask first.`}function O(e){return e?.command?`/${e.command} `:"/"}function q(e,t=""){return e?.command?{command:e.command,args:String(t||"").trim(),name:e.name||"",icon:e.icon||"🎓"}:null}function v(e){return e?.command?`/${e.command}${e.args?` ${e.args}`:""}`:""}export{C as BUG_REPORT_SLASH_ITEMS,_ as NEW_THREAD_SLASH_ITEMS,L as SIDELINE_SLASH_ITEMS,z as SLASH_TYPING_RE,m as enabledSkills,I as isSkillEnabled,T as matchSlashRecipe,E as matchSlashSkill,H as matchSlashTeam,A as parseBugCommand,y as parseNewThread,R as recipeInvocationText,v as skillInvocationLabel,q as skillInvocationOf,O as slashCommandInsert,$ as slashCommandItems,k as teamInvocationText};
package/tool-hub.js CHANGED
@@ -1,17 +1,20 @@
1
- import{findToolsResult as C,oneLiner as L}from"./tool-discovery.js";import{validateAction as D}from"./tool-dispatch.js";import{isPermissionTool as Y}from"./agent-permission.js";import{CONTEXT_TAGS as k}from"./context-attachments.js";const _="tools",v="find",y="describe",O=6,K=5,X=2,Q=new Set("mcp server api tool tools app apps the and for with data cloud online local remote connector integration a an of to in on my go is it by or at".split(" "));function Z(t){const i=(String(t?.name||"").match(/^mcp_(.+?)__/)||[])[1]||"",o=(String(t?.description||"").match(/^\[([^\]]+)\]/)||[])[1]||"";return[...new Set(`${i.replace(/_/g," ")} ${o}`.toLowerCase().match(/[a-z][a-z0-9]+/g)||[])].filter(e=>!Q.has(e))}function ee(t,i){const o=new Set(String(t||"").toLowerCase().match(/[a-z][a-z0-9]+/g)||[]);return Z(i).some(e=>o.has(e))}const J=t=>{const i=t?.parameters||t?.inputSchema;return Array.isArray(i?.required)?i.required.map(String):[]},R=t=>`${t.name}(${J(t).join(", ")})`,z=t=>L(String(t||"").split(/\n\s*\n/)[0],140);function te(){return{name:_,description:`Every action Chap gives you — the user's own data, their connected integrations, the browser tab — in one tool. Run one: {"action":"<name>","args":{…}}. Not sure which: {"action":"find","query":"<what you need>"}. Its arguments: {"action":"describe","tool":"<name>"}.`,parameters:{type:"object",properties:{action:{type:"string",description:'The action to run — a name from the catalog, a hint or a find — or "find" / "describe".'},args:{type:"object",additionalProperties:!0,description:"The action's own arguments, verbatim. {} when it takes none."},query:{type:"string",description:'With action "find": what you need to do, in words.'},tool:{type:"string",description:'With action "describe": the action to describe.'}},required:["action"],additionalProperties:!0}}}const N=t=>Y(t);function ne(t){const i=t.hiddenVia instanceof Map?t.hiddenVia:new Map,o=new Set(i.values()),e=new Map;for(const n of t.reach||[])n?.name&&!N(n.name)&&!e.has(n.name)&&e.set(n.name,n);for(const n of t.specs||[])n?.name&&!N(n.name)&&!o.has(n.name)&&!e.has(n.name)&&e.set(n.name,n);return{leaves:e,hiddenVia:i,groups:o}}function re(t,i){const o=n=>t.some(a=>n.test(a)),e=[];return o(/^(history_|recall$|memory_recall$|meeting_)/)&&e.push("You HAVE access to the user's own Chap data — past chats, notes, meeting transcripts and summaries — here. For anything they discussed or wrote, search it FIRST (`history_search`) and answer from it; never say you cannot access their meetings, notes or history."),o(/^(weather|web_search)$/)&&e.push("For anything current — weather, prices, news — use `weather` / `web_search` here, not a search tool of your own; the user sees these calls as steps. A [prefetch] block in the message IS that call, already made: answer from it, no call."),i.size&&e.push("The user's connected integrations are here too — when a request matches one, call it rather than saying it is unavailable."),o(/^read_page$/)&&e.push("The browser tab the user is looking at can be read and acted on here — `read_page` first."),e}function oe(t,i,o){const e=new Map;for(const[a,d]of o)i.has(a)&&(e.get(d)||e.set(d,[]).get(d)).push(a);const n=[];for(const a of t.specs||[]){const d=e.get(a.name);if(d?.length){const w=d.slice(0,O).join(", "),g=d.length>O?`, … (+${d.length-O} — find them)`:"";n.push(`- ${z(a.description)} — ${w}${g}`)}else i.has(a.name)&&n.push(`- ${R(a)}: ${z(a.description)}`)}return n}function ue(t,{rank:i,providerSystem:o=""}={}){if(!t||typeof t.execute!="function")return null;const{leaves:e,hiddenVia:n}=ne(t);if(!e.size)return null;const a=t.residents instanceof Map?t.residents:new Map,d=r=>n.get(r)||r,w=r=>{const s=new Set(r instanceof Set?r:[]);for(const[c,l]of n)s.has(l)&&s.add(c);return s},g=w(t.remoteTools),B=w(t.serialTools),j=[...e.keys()],F=re(j,new Set(j.filter(r=>g.has(r)))),H=new Set(n.values()),E=[...new Set([...a].filter(([r])=>e.has(r)&&!H.has(r)).map(([,r])=>r.trim()).filter(Boolean))],A=['Everything below is reached through ONE tool, `tools`: {"action":"<name>","args":{…}}. Not sure which action? {"action":"find","query":"<what you need>"} searches all of them. Not sure of its arguments? {"action":"describe","tool":"<name>"}.',...F,`Available:
2
- ${oe(t,e,n).join(`
1
+ import{findToolsResult as L,oneLiner as k}from"./tool-discovery.js";import{validateAction as Y}from"./tool-dispatch.js";import{isPermissionTool as K}from"./agent-permission.js";import{CONTEXT_TAGS as B}from"./context-attachments.js";const v="tools",O="find",S="describe",j=6,X=5,Q=2,Z=new Set("mcp server api tool tools app apps the and for with data cloud online local remote connector integration a an of to in on my go is it by or at".split(" "));function ee(e){const i=(String(e?.name||"").match(/^mcp_(.+?)__/)||[])[1]||"",o=(String(e?.description||"").match(/^\[([^\]]+)\]/)||[])[1]||"";return[...new Set(`${i.replace(/_/g," ")} ${o}`.toLowerCase().match(/[a-z][a-z0-9]+/g)||[])].filter(t=>!Z.has(t))}function te(e,i){const o=new Set(String(e||"").toLowerCase().match(/[a-z][a-z0-9]+/g)||[]);return ee(i).some(t=>o.has(t))}const J=e=>{const i=e?.parameters||e?.inputSchema;return Array.isArray(i?.required)?i.required.map(String):[]},R=e=>`${e.name}(${J(e).join(", ")})`,z=e=>k(String(e||"").split(/\n\s*\n/)[0],140);function ne(){return{name:v,description:`Every action Chap gives you — the user's own data, their connected integrations, the browser tab — in one tool. Run one: {"action":"<name>","args":{…}}. Not sure which: {"action":"find","query":"<what you need>"}. Its arguments: {"action":"describe","tool":"<name>"}.`,parameters:{type:"object",properties:{action:{type:"string",description:'The action to run — a name from the catalog, a hint or a find — or "find" / "describe".'},args:{type:"object",additionalProperties:!0,description:"The action's own arguments, verbatim. {} when it takes none."},query:{type:"string",description:'With action "find": what you need to do, in words.'},tool:{type:"string",description:'With action "describe": the action to describe.'}},required:["action"],additionalProperties:!0}}}const N=e=>K(e);function re(e){const i=e.hiddenVia instanceof Map?e.hiddenVia:new Map,o=new Set(i.values()),t=new Map;for(const n of e.reach||[])n?.name&&!N(n.name)&&!t.has(n.name)&&t.set(n.name,n);for(const n of e.specs||[])n?.name&&!N(n.name)&&!o.has(n.name)&&!t.has(n.name)&&t.set(n.name,n);return{leaves:t,hiddenVia:i,groups:o}}function oe(e,i){const o=n=>e.some(g=>n.test(g)),t=[];return o(/^(history_|recall$|memory_recall$|meeting_)/)&&t.push("You HAVE access to the user's own Chap data — past chats, notes, meeting transcripts and summaries — here. For anything they discussed or wrote, search it FIRST (`history_search`) and answer from it; never say you cannot access their meetings, notes or history."),o(/^(weather|web_search)$/)&&t.push("For anything current — weather, prices, news — use `weather` / `web_search` here, not a search tool of your own; the user sees these calls as steps. A [prefetch] block in the message IS that call, already made: answer from it, no call."),i.size&&t.push("The user's connected integrations are here too — when a request matches one, call it rather than saying it is unavailable."),o(/^read_page$/)&&t.push("The browser tab the user is looking at can be read and acted on here — `read_page` first."),t}function ie(e,i,o){const t=new Map;for(const[l,p]of o)i.has(l)&&(t.get(p)||t.set(p,[]).get(p)).push(l);const n=[],g=e.quietTools instanceof Set?e.quietTools:new Set;for(const l of e.specs||[]){if(g.has(l.name))continue;const p=t.get(l.name);if(p?.length){const A=p.slice(0,j).join(", "),w=p.length>j?`, … (+${p.length-j} — find them)`:"";n.push(`- ${z(l.description)} — ${A}${w}`)}else i.has(l.name)&&n.push(`- ${R(l)}: ${z(l.description)}`)}return n}function he(e,{rank:i,providerSystem:o=""}={}){if(!e||typeof e.execute!="function")return null;const{leaves:t,hiddenVia:n}=re(e);if(!t.size)return null;const g=e.residents instanceof Map?e.residents:new Map,l=Array.isArray(e.hinters)?e.hinters.filter(r=>typeof r=="function"):[],p=r=>n.get(r)||r,A=r=>{const s=new Set(r instanceof Set?r:[]);for(const[u,h]of n)s.has(h)&&s.add(u);return s},w=A(e.remoteTools),F=A(e.serialTools),q=[...t.keys()],H=oe(q,new Set(q.filter(r=>w.has(r)))),P=new Set(n.values()),E=[...new Set([...g].filter(([r])=>t.has(r)&&!P.has(r)).map(([,r])=>r.trim()).filter(Boolean))],$=['Everything below is reached through ONE tool, `tools`: {"action":"<name>","args":{…}}. Not sure which action? {"action":"find","query":"<what you need>"} searches all of them. Not sure of its arguments? {"action":"describe","tool":"<name>"}.',...H,`Available:
2
+ ${ie(e,t,n).join(`
3
3
  `)}`,...E.length?[`Every tool the notes below name is an action of \`tools\`: call it as {"action":"<name>","args":{…}}.
4
4
 
5
5
  ${E.join(`
6
6
 
7
7
  `)}`]:[]].join(`
8
- `),$=String(t.system||""),P=o&&$.includes(o)?$.replace(o,A):[$,A].filter(Boolean).join(`
8
+ `),x=String(e.system||""),V=o&&x.includes(o)?x.replace(o,$):[x,$].filter(Boolean).join(`
9
9
 
10
- `),q=(r,s,c)=>{const l=n.get(r);return l?t.execute(l,{action:r,args:s},c):t.execute(r,s,c)},T=r=>Object.hasOwn(k,r)?JSON.stringify({error:`"${r}" is not an action.`,what:k[r],hint:'{"action":"find","query":"<what you need>"} lists the actions.'}):null;async function V(r){const s=e.get(r);if(!s)return T(r)??JSON.stringify({error:`Unknown action "${r}".`,hint:'{"action":"find","query":"<what you need>"} lists what exists.'});const c=[a.get(d(r))];if(n.has(r))try{const l=JSON.parse(await t.execute(n.get(r),{action:y,args:{tool:r}},{}));l?.guidance&&c.push(l.guidance)}catch{}return JSON.stringify({name:s.name,description:s.description||"",parameters:s.parameters||s.inputSchema||{type:"object",properties:{}},...c.filter(Boolean).length?{guidance:c.filter(Boolean).join(`
10
+ `),I=(r,s,u)=>{const h=n.get(r);return h?e.execute(h,{action:r,args:s},u):e.execute(r,s,u)},_=r=>Object.hasOwn(B,r)?JSON.stringify({error:`"${r}" is not an action.`,what:B[r],hint:'{"action":"find","query":"<what you need>"} lists the actions.'}):null;async function G(r){const s=t.get(r);if(!s)return _(r)??JSON.stringify({error:`Unknown action "${r}".`,hint:'{"action":"find","query":"<what you need>"} lists what exists.'});const u=[g.get(p(r))];if(n.has(r))try{const h=JSON.parse(await e.execute(n.get(r),{action:S,args:{tool:r}},{}));h?.guidance&&u.push(h.guidance)}catch{}return JSON.stringify({name:s.name,description:s.description||"",parameters:s.parameters||s.inputSchema||{type:"object",properties:{}},...u.filter(Boolean).length?{guidance:u.filter(Boolean).join(`
11
11
 
12
- `)}:{},callAs:{action:s.name,args:"<the properties above>"}})}async function I(r,s,c={}){const l=s&&typeof s=="object"?s:{};if(r!==_)return e.has(r)&&!n.has(r)?t.execute(r,l,c):n.has(r)?q(r,l,c):t.execute(r,l,c);const{action:x,args:u,...b}=l,f=String(x||""),p={...b,...u&&typeof u=="object"?u:{}},h=u&&typeof u=="object"?String(u.action||""):"";if(f===v&&h&&h!==v&&h!==y&&e.has(h))return I(_,{action:h,args:u.args&&typeof u.args=="object"?u.args:{}},c);if(f===v)return C([...e.values()],String(p.query??p.tool??""),{rank:i,describeAction:y});if(f===y)return V(String(p.tool||p.name||p.action||""));const m=e.get(f);if(!m&&T(f))return T(f);if(!m){const U=JSON.parse(await C([...e.values()],f.replace(/[_-]+/g," "),{rank:i,describeAction:y,limit:5}));return JSON.stringify({error:`Unknown action "${f}".`,didYouMean:U.matches.map(W=>W.name),hint:'Call one of those, or {"action":"find","query":"<what you need>"}.'})}const S=typeof u=="string"&&u.trim()?J(m):[];S.length===1&&p[S[0]]==null&&[void 0,"string"].includes(m.parameters?.properties?.[S[0]]?.type)&&(p[S[0]]=u.trim(),c?.shims?.fire?.("hub.args-text",{tool:f}));const M=D(m,p,{envelope:u});return M?JSON.stringify(M):q(f,p,c)}function G(r,{score:s,limit:c=K,minScore:l=X,small:x=!1}={}){const u=String(r||"").trim();if(!u||typeof s!="function")return"";let b;try{b=s([...e.values()],u)}catch{return""}const f=h=>!x||!g.has(h.name)||ee(u,h),p=(b||[]).filter(h=>h&&h.n>l&&f(h.s)).slice(0,c).map(h=>h.s);return p.length?`[Chap] Likely useful for this message, through \`tools\`: ${p.map(h=>`${R(h)} — ${L(h.description,90)}`).join("; ")}.`:""}return{...t,specs:[te(),...(t.specs||[]).filter(r=>N(r?.name))],system:P,systemParts:{tools:Math.round(A.length/4)},remoteTools:g,serialTools:B,execute:I,hub:{leaves:[...e.keys()],hintFor:G,groupOf:d}}}function he(t){for(let i=(t||[]).length-1;i>=0;i--){const o=t[i];if(o?.role==="user")return typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.filter(e=>e?.type==="text").map(e=>e.text||"").join(`
13
- `):""}return""}function le(t,i){const o=Array.isArray(t)?t:[];if(!i)return o;let e=o.length-1;for(;e>=0&&o[e]?.role!=="user";)e--;if(e<0)return o;const n=o[e],a=typeof n.content=="string"?`${n.content}
12
+ `)}:{},callAs:{action:s.name,args:"<the properties above>"}})}async function M(r,s,u={}){const h=s&&typeof s=="object"?s:{};if(r!==v)return t.has(r)&&!n.has(r)?e.execute(r,h,u):n.has(r)?I(r,h,u):e.execute(r,h,u);const{action:T,args:a,...b}=h,f=String(T||""),d={...b,...a&&typeof a=="object"?a:{}},m=a&&typeof a=="object"?String(a.action||""):"";if(f===O&&m&&m!==O&&m!==S&&t.has(m))return M(v,{action:m,args:a.args&&typeof a.args=="object"?a.args:{}},u);if(f===O)return L([...t.values()],String(d.query??d.tool??""),{rank:i,describeAction:S});if(f===S)return G(String(d.tool||d.name||d.action||""));const y=t.get(f);if(!y&&_(f))return _(f);if(!y){const W=JSON.parse(await L([...t.values()],f.replace(/[_-]+/g," "),{rank:i,describeAction:S,limit:5}));return JSON.stringify({error:`Unknown action "${f}".`,didYouMean:W.matches.map(D=>D.name),hint:'Call one of those, or {"action":"find","query":"<what you need>"}.'})}const c=typeof a=="string"&&a.trim()?J(y):[];c.length===1&&d[c[0]]==null&&[void 0,"string"].includes(y.parameters?.properties?.[c[0]]?.type)&&(d[c[0]]=a.trim(),u?.shims?.fire?.("hub.args-text",{tool:f}));const C=Y(y,d,{envelope:a});return C?JSON.stringify(C):I(f,d,u)}function U(r,{score:s,limit:u=X,minScore:h=Q,small:T=!1}={}){const a=String(r||"").trim();if(!a)return"";const b=l.map(c=>{try{return String(c(a,{small:T})||"")}catch{return""}}).filter(Boolean);if(typeof s!="function")return b.join(`
13
+ `);let f;try{f=s([...t.values()],a)}catch{return b.join(`
14
+ `)}const d=c=>!T||!w.has(c.name)||te(a,c),m=(f||[]).filter(c=>c&&c.n>h&&d(c.s)).slice(0,u).map(c=>c.s);return[m.length?`[Chap] Likely useful for this message, through \`tools\`: ${m.map(c=>`${R(c)} — ${k(c.description,90)}`).join("; ")}.`:"",...b].filter(Boolean).join(`
15
+ `)}return{...e,specs:[ne(),...(e.specs||[]).filter(r=>N(r?.name))],system:V,systemParts:{tools:Math.round($.length/4)},remoteTools:w,serialTools:F,execute:M,hub:{leaves:[...t.keys()],hintFor:U,groupOf:p}}}function fe(e){for(let i=(e||[]).length-1;i>=0;i--){const o=e[i];if(o?.role==="user")return typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.filter(t=>t?.type==="text").map(t=>t.text||"").join(`
16
+ `):""}return""}function le(e,i){const o=Array.isArray(e)?e:[];if(!i)return o;let t=o.length-1;for(;t>=0&&o[t]?.role!=="user";)t--;if(t<0)return o;const n=o[t],g=typeof n.content=="string"?`${n.content}
14
17
 
15
- ${i}`:Array.isArray(n.content)?[...n.content,{type:"text",text:i}]:n.content;return[...o.slice(0,e),{...n,content:a},...o.slice(e+1)]}function fe(t,i){const o=Array.isArray(t)?t:[];if(!i)return o;let e=o.length-1;for(;e>=0&&o[e]?.role!=="user";)e--;if(e<0)return o;const n=o[e],a=typeof n.content=="string"?`${i}
18
+ ${i}`:Array.isArray(n.content)?[...n.content,{type:"text",text:i}]:n.content;return[...o.slice(0,t),{...n,content:g},...o.slice(t+1)]}function pe(e,i){const o=Array.isArray(e)?e:[];if(!i)return o;let t=o.length-1;for(;t>=0&&o[t]?.role!=="user";)t--;if(t<0)return o;const n=o[t],g=typeof n.content=="string"?`${i}
16
19
 
17
- ${n.content}`:Array.isArray(n.content)?[{type:"text",text:i},...n.content]:n.content;return[...o.slice(0,e),{...n,content:a},...o.slice(e+1)]}export{_ as HUB_TOOL_NAME,te as hubSpec,he as lastUserText,ue as makeToolHub,ee as namesIntegration,le as withHint,fe as withLead};
20
+ ${n.content}`:Array.isArray(n.content)?[{type:"text",text:i},...n.content]:n.content;return[...o.slice(0,t),{...n,content:g},...o.slice(t+1)]}export{v as HUB_TOOL_NAME,ne as hubSpec,fe as lastUserText,he as makeToolHub,te as namesIntegration,le as withHint,pe as withLead};
package/tool-need.js CHANGED
@@ -1,3 +1,3 @@
1
- import{offeredSearch as O}from"./prefetch.js";import{signalsFrom as _}from"./router.js";const j=new Set(["hi","hii","hiya","hey","heya","hello","helo","yo","sup","howdy","greetings","good","morning","afternoon","evening","night","day","thanks","thank","thankyou","thx","tnx","ty","cheers","appreciated","ok","okay","k","kk","got","sounds","perfect","great","cool","nice","awesome","lol","haha","hah","hehe","nvm","yep","yeah","yes","no","nope","sure","bye","goodbye","later","ya","cya","ciao","welcome","worries","problem","np","please","there","again","all","everyone","team","friend","mate","buddy","you","u","so","much","very","well","and","a","the"]),q=6;function L(e){const o=String(e||"").toLowerCase().replace(/[^\p{L}\s']/gu," ").split(/\s+/).filter(Boolean);return!o.length||o.length>q?!1:o.every(a=>j.has(a))}function P({request:e=null,signals:o=null,attachments:a=[],explicit:c=!1}={}){if(c)return{tools:!0,why:"the turn asked for tools"};if((a||[]).some(s=>s&&!s.auto))return{tools:!0,why:"the turn carries an attachment"};const r=String(e?.text??(e?.messages||[]).map(s=>s?.content||"").join(`
2
- `));return L(r)?e?.previousAnswer&&O(e.previousAnswer)?{tools:!0,why:"accepting the offer to search"}:(o||_(e||{})).smalltalk?{tools:!1,why:"a greeting — nothing to look up"}:{tools:!0,why:"the request may need something fetched"}:{tools:!0,why:"the request may need something fetched"}}const G=Object.freeze([["web",/\b(search|google|look ?up|latest|current|recent|today|this (week|month|year)|news|price|prices|pricing|cost of|quote|stock|market|website|url|online|web|docs?umentation|release notes|changelog|versions?)\b/i],["history",/\b(our (meeting|call|notes?|chats?|conversation)|what (did|was) (we|i)|we (decided|agreed|discussed|said)|in (my|our) (notes?|meetings?|history|chats?)|past (chats?|meetings?|notes?)|earlier (meeting|conversation|chat|note)|transcript|standup|retro)\b/i],["data",/\b(attached|attachment|this (page|document|file|pdf|spreadsheet|sheet)|the (document|file|pdf|spreadsheet) (above|provided|attached))\b/i]]);function U(e,{held:o=null}={}){const a=String(e||"");if(!a.trim())return[];const c=G.filter(([,t])=>t.test(a)).map(([t])=>t);if(!o)return c;const r=new Set((Array.isArray(o)?o:[]).map(t=>String(t).toLowerCase()));return c.filter(t=>r.has(t)||t==="history"&&r.has("data"))}const u=Object.freeze(["page","data","mcp","memory","note","team","sideline","skills","widgets","recipes"]),k=Object.freeze(["data","mcp","memory"]),f="page_read",v=/\b(this|the|current|open|active|that|my) (page|tab|site|website|article|post|thread|document|doc|file|pdf|sheet|spreadsheet|form|canvas|board|diagram|screen|window|video|table|cell|button|field|link|image)\b|\bon (the|this) (page|screen|tab)\b|\bhere\b|\bthis\b(?!\s+(morning|afternoon|evening|week|weekend|month|year|time|is (a|the|my))\b)|\bthese\b|\bthose\b/i,S=/\b(click|tap|press|type|fill|enter|select|scroll|drag|draw|paint|sketch|navigate|go to|open|close|submit|upload|download|play|pause|screenshot|inspect|read (the|this)|zoom|highlight|copy|paste|log ?in|sign ?in|sign ?up|checkout|add to cart|search (on|in) (the|this)|watch|browse)\b/i,A=/\b(build|make|create|write|generate|draft|code|design|implement|prototype)\b[^.?!]{0,40}\b(app|widget|tool|timer|calculator|tracker|checklist|game|dashboard|form|page|site|script|component|converter|counter|scoreboard|clock|note|dice)\b|\b(widget|app)\b/i,z=/\b(run|use|ask|start|save|create|make|set ?up|open|launch|kick ?off|assign|delegate)\b[^.?!]{0,30}\b(team|teams|agent|agents|skill|skills|recipe|recipes|sideline|project)\b|\b(the|my|our|this|that)\s+(\w+[\s-]+)?(team|agent|skill|recipe|sideline|project)\b|\bask (the|our|my) \w+ (to|for)\b|\b(executive|breakout|workflow)\b|remember this|save (this|that) as|^\s*\//i,x=/\b(summar\w*|analy[sz](?:e|es|ed|ing|is)|review|edit|rewrite|fix|refactor|debug|translate|convert|extract|compare|explain (this|that|the)|proofread|format|organi[sz]e|plan)\b/i,F=300;function $({request:e=null,signals:o=null,attachments:a=[],explicit:c=!1,stable:r=!1,ambient:t=null}={}){const s=R({request:e,signals:o,attachments:a,explicit:c,stable:r,ambient:t});return N(s,e,t)}function N(e,o,a){const c=String(o?.previousRequest||"").trim();if(!e.tools||e.tier==="full"||!c)return e;const r=R({request:{text:c},ambient:a});if(!r.tools||r.tier==="light"||r.tier==="none")return e;const t=new Set([...e.groups,...r.groups]);return t.has("page")&&t.delete(f),u.every(s=>t.has(s))?{tools:!0,tier:"full",groups:new Set(u),why:`${e.why}; carried from the request before: ${r.why}`}:{tools:!0,tier:"task",groups:t,why:`${e.why}; carried from the request before: ${r.why}`}}function R({request:e=null,signals:o=null,attachments:a=[],explicit:c=!1,stable:r=!1,ambient:t=null}={}){const s=i=>({tools:!0,tier:"full",groups:new Set(u),why:i});if(r)return s("a warm process keeps one tool set");const d=P({request:e,signals:o,attachments:a,explicit:c});if(!d.tools)return{tools:!1,tier:"none",groups:new Set,why:d.why};if(c)return s(d.why);const l=String(e?.text??(e?.messages||[]).map(i=>i?.content||"").join(`
3
- `)),m=i=>{const y=s(i);return A.test(l)||y.groups.delete("widgets"),y};if((a||[]).some(i=>i&&!i.auto))return m("the turn carries an attachment");if(!l.trim())return s("no text to read");if(l.length>F||/```/.test(l))return m("a long or code-bearing request");const b=v.test(l)||S.test(l)||x.test(l),p=z.test(l),w=A.test(l),E=x.test(l),g=!!t?.page;if(!b&&!p&&!w){const i=new Set(k);return g&&i.add(f),{tools:!0,tier:"light",groups:i,why:g?"a lookup, asked from a readable tab — the user's data, the web, and a reader for the tab":"a lookup — the user's data and the web are enough"}}const n=new Set(k),h=[];return b&&(n.add("page"),n.add("note"),h.push(S.test(l)?"the request asks to act":v.test(l)?"the request refers to the page or to something in view":"the request is work, not a lookup")),(E||p)&&n.add("skills"),p&&(n.add("team"),n.add("sideline"),n.add("recipes"),n.add("note"),h.push("the request names a team, skill, recipe or command")),w&&(n.add("widgets"),n.add("note"),h.push("the request asks to make something")),g&&!n.has("page")&&n.add(f),u.every(i=>n.has(i))?s(h.join("; ")):{tools:!0,tier:"task",groups:n,why:h.join("; ")}}export{$ as equipmentFor,U as grantsNeededFor,L as isPleasantry,P as toolNeedFor};
1
+ import{offeredSearch as E}from"./prefetch.js";import{signalsFrom as O}from"./router.js";const P=new Set(["hi","hii","hiya","hey","heya","hello","helo","yo","sup","howdy","greetings","good","morning","afternoon","evening","night","day","thanks","thank","thankyou","thx","tnx","ty","cheers","appreciated","ok","okay","k","kk","got","sounds","perfect","great","cool","nice","awesome","lol","haha","hah","hehe","nvm","yep","yeah","yes","no","nope","sure","bye","goodbye","later","ya","cya","ciao","welcome","worries","problem","np","please","there","again","all","everyone","team","friend","mate","buddy","you","u","so","much","very","well","and","a","the"]),_=6;function q(e){const r=String(e||"").toLowerCase().replace(/[^\p{L}\s']/gu," ").split(/\s+/).filter(Boolean);return!r.length||r.length>_?!1:r.every(s=>P.has(s))}function L({request:e=null,signals:r=null,attachments:s=[],explicit:n=!1}={}){if(n)return{tools:!0,why:"the turn asked for tools"};if((s||[]).some(a=>a&&!a.auto))return{tools:!0,why:"the turn carries an attachment"};const o=String(e?.text??(e?.messages||[]).map(a=>a?.content||"").join(`
2
+ `));return q(o)?e?.previousAnswer&&E(e.previousAnswer)?{tools:!0,why:"accepting the offer to search"}:(r||O(e||{})).smalltalk?{tools:!1,why:"a greeting — nothing to look up"}:{tools:!0,why:"the request may need something fetched"}:{tools:!0,why:"the request may need something fetched"}}const G=Object.freeze([["web",/\b(search|google|look ?up|latest|current|recent|today|this (week|month|year)|news|price|prices|pricing|cost of|quote|stock|market|website|url|online|web|docs?umentation|release notes|changelog|versions?)\b/i],["history",/\b(our (meeting|call|notes?|chats?|conversation)|what (did|was) (we|i)|we (decided|agreed|discussed|said)|in (my|our) (notes?|meetings?|history|chats?)|past (chats?|meetings?|notes?)|earlier (meeting|conversation|chat|note)|transcript|standup|retro)\b/i],["data",/\b(attached|attachment|this (page|document|file|pdf|spreadsheet|sheet)|the (document|file|pdf|spreadsheet) (above|provided|attached))\b/i]]);function U(e,{held:r=null}={}){const s=String(e||"");if(!s.trim())return[];const n=G.filter(([,t])=>t.test(s)).map(([t])=>t);if(!r)return n;const o=new Set((Array.isArray(r)?r:[]).map(t=>String(t).toLowerCase()));return n.filter(t=>o.has(t)||t==="history"&&o.has("data"))}const d=Object.freeze(["page","data","mcp","memory","note","team","sideline","skills","widgets","recipes"]),k=Object.freeze(["data","mcp","memory"]),f="page_read",v=/\b(this|the|current|open|active|that|my) (page|tab|site|website|article|post|thread|document|doc|file|pdf|sheet|spreadsheet|form|canvas|board|diagram|screen|window|video|table|cell|button|field|link|image)\b|\bon (the|this) (page|screen|tab)\b|\bhere\b|\bthis\b(?!\s+(morning|afternoon|evening|week|weekend|month|year|time|is (a|the|my))\b)|\bthese\b|\bthose\b/i,S=/\b(click|tap|press|type|fill|enter|select|scroll|drag|draw|paint|sketch|navigate|go to|open|close|submit|upload|download|play|pause|screenshot|inspect|read (the|this)|zoom|highlight|copy|paste|log ?in|sign ?in|sign ?up|checkout|add to cart|search (on|in) (the|this)|watch|browse)\b/i,A=/\b(build|make|create|write|generate|draft|code|design|implement|prototype)\b[^.?!]{0,40}\b(app|widget|tool|timer|calculator|tracker|checklist|game|dashboard|form|page|site|script|component|converter|counter|scoreboard|clock|note|dice)\b|\b(widget|app)\b/i,z=/\b(run|use|ask|start|save|create|make|set ?up|open|launch|kick ?off|assign|delegate)\b[^.?!]{0,30}\b(team|teams|agent|agents|skill|skills|recipe|recipes|sideline|project)\b|\b(the|my|our|this|that)\s+(\w+[\s-]+)?(team|agent|skill|recipe|sideline|project)\b|\bask (the|our|my) \w+ (to|for)\b|\b(executive|breakout|workflow)\b|remember this|save (this|that) as|^\s*\//i,x=/\b(summar\w*|analy[sz](?:e|es|ed|ing|is)|review|edit|rewrite|fix|refactor|debug|translate|convert|extract|compare|explain (this|that|the)|proofread|format|organi[sz]e|plan)\b/i,F=300;function D({request:e=null,signals:r=null,attachments:s=[],explicit:n=!1,stable:o=!1,ambient:t=null,pinned:a=[]}={}){const h=R({request:e,signals:r,attachments:s,explicit:n,stable:o,ambient:t});return $(N(h,e,t),a)}function $(e,r){const s=(Array.isArray(r)?r:[]).filter(o=>typeof o=="string"&&o);if(!s.length||e.tier==="full")return e;const n=new Set([...e.tools?e.groups:[],...s]);return{tools:!0,tier:e.tools&&e.tier!=="none"?e.tier==="light"?"task":e.tier:"task",groups:n,why:`${e.why}; picked: ${s.join(", ")}`}}function N(e,r,s){const n=String(r?.previousRequest||"").trim();if(!e.tools||e.tier==="full"||!n)return e;const o=R({request:{text:n},ambient:s});if(!o.tools||o.tier==="light"||o.tier==="none")return e;const t=new Set([...e.groups,...o.groups]);return t.has("page")&&t.delete(f),d.every(a=>t.has(a))?{tools:!0,tier:"full",groups:new Set(d),why:`${e.why}; carried from the request before: ${o.why}`}:{tools:!0,tier:"task",groups:t,why:`${e.why}; carried from the request before: ${o.why}`}}function R({request:e=null,signals:r=null,attachments:s=[],explicit:n=!1,stable:o=!1,ambient:t=null}={}){const a=l=>({tools:!0,tier:"full",groups:new Set(d),why:l});if(o)return a("a warm process keeps one tool set");const h=L({request:e,signals:r,attachments:s,explicit:n});if(!h.tools)return{tools:!1,tier:"none",groups:new Set,why:h.why};if(n)return a(h.why);const c=String(e?.text??(e?.messages||[]).map(l=>l?.content||"").join(`
3
+ `)),m=l=>{const y=a(l);return A.test(c)||y.groups.delete("widgets"),y};if((s||[]).some(l=>l&&!l.auto))return m("the turn carries an attachment");if(!c.trim())return a("no text to read");if(c.length>F||/```/.test(c))return m("a long or code-bearing request");const b=v.test(c)||S.test(c)||x.test(c),p=z.test(c),w=A.test(c),j=x.test(c),g=!!t?.page;if(!b&&!p&&!w){const l=new Set(k);return g&&l.add(f),{tools:!0,tier:"light",groups:l,why:g?"a lookup, asked from a readable tab — the user's data, the web, and a reader for the tab":"a lookup — the user's data and the web are enough"}}const i=new Set(k),u=[];return b&&(i.add("page"),i.add("note"),u.push(S.test(c)?"the request asks to act":v.test(c)?"the request refers to the page or to something in view":"the request is work, not a lookup")),(j||p)&&i.add("skills"),p&&(i.add("team"),i.add("sideline"),i.add("recipes"),i.add("note"),u.push("the request names a team, skill, recipe or command")),w&&(i.add("widgets"),i.add("note"),u.push("the request asks to make something")),g&&!i.has("page")&&i.add(f),d.every(l=>i.has(l))?a(u.join("; ")):{tools:!0,tier:"task",groups:i,why:u.join("; ")}}export{D as equipmentFor,U as grantsNeededFor,q as isPleasantry,L as toolNeedFor};
package/toolset.js CHANGED
@@ -1,3 +1,3 @@
1
- const w=/^mcp[_-]/i;function x(S,{mcpSystem:f=""}={}){const a=(S||[]).filter(e=>e&&e.specs?.length);if(!a.length)return;const r=[],m=new Map,u=new Set,l=new Map,g=new Set,h=[],o=new Map,M=new Map;for(const e of a){const s=e.remote===!0;if(e.traits instanceof Map)for(const[n,t]of e.traits)l.has(n)||l.set(n,t);const i=e.hiddenVia instanceof Map;if(i){const n=new Map((Array.isArray(e.reach)?e.reach:[]).filter(t=>t?.name).map(t=>[t.name,t]));for(const[t,y]of e.hiddenVia)o.has(t)||!e.specs.some(E=>E?.name===y)||(o.set(t,y),n.has(t)&&h.push(n.get(t)))}else if(Array.isArray(e.reach)&&e.specs.length===1)for(const n of e.reach)n?.name&&!o.has(n.name)&&(o.set(n.name,e.specs[0].name),h.push(n));const c=e.remoteTools instanceof Set?e.remoteTools:null,A=e.serialTools instanceof Set?e.serialTools:null;for(const n of e.specs){if(m.has(n.name))continue;r.push(n),m.set(n.name,e.execute);const t=i&&e.residents instanceof Map?e.residents.get(n.name):e.system;t&&M.set(n.name,String(t)),(s||c?.has(n.name)||w.test(String(n.name||"")))&&u.add(n.name),(e.serial===!0||A?.has(n.name))&&g.add(n.name)}}if(!r.length)return;const p=r.some(e=>w.test(String(e?.name||"")))?String((typeof f=="function"?f():f)||""):"",T=[p,...a.map(e=>e.system)].map(e=>String(e||"").trim()).filter(Boolean).join(`
1
+ const A=/^mcp[_-]/i;function V(g,{mcpSystem:h=""}={}){const i=(g||[]).filter(e=>e&&e.specs?.length);if(!i.length)return;const r=[],u=new Map,y=new Set,p=new Map,M=new Set,l=[],o=new Map,S=new Map,w=new Set,a=[];for(const e of g||[])!e||e.specs?.length||typeof e.hint=="function"&&a.push(e.hint);for(const e of i){if(typeof e.hint=="function"&&a.push(e.hint),Array.isArray(e.hinters))for(const t of e.hinters)typeof t=="function"&&a.push(t);const s=e.remote===!0;if(e.traits instanceof Map)for(const[t,n]of e.traits)p.has(t)||p.set(t,n);const c=e.hiddenVia instanceof Map;if(c){const t=new Map((Array.isArray(e.reach)?e.reach:[]).filter(n=>n?.name).map(n=>[n.name,n]));for(const[n,T]of e.hiddenVia)o.has(n)||!e.specs.some(R=>R?.name===T)||(o.set(n,T),t.has(n)&&l.push(t.get(n)))}else if(Array.isArray(e.reach)&&e.specs.length===1)for(const t of e.reach)t?.name&&!o.has(t.name)&&(o.set(t.name,e.specs[0].name),l.push(t));const f=e.remoteTools instanceof Set?e.remoteTools:null,E=e.serialTools instanceof Set?e.serialTools:null;for(const t of e.specs){if(u.has(t.name))continue;r.push(t),u.set(t.name,e.execute);const n=c&&e.residents instanceof Map?e.residents.get(t.name):e.system;n&&S.set(t.name,String(n)),(s||f?.has(t.name)||A.test(String(t.name||"")))&&y.add(t.name),(e.serial===!0||E?.has(t.name))&&M.add(t.name),(e.quiet===!0||e.quietTools instanceof Set&&e.quietTools.has(t.name))&&w.add(t.name)}}if(!r.length)return;const m=r.some(e=>A.test(String(e?.name||"")))?String((typeof h=="function"?h():h)||""):"",q=[m,...i.filter(e=>e.quiet!==!0).map(e=>e.system)].map(e=>String(e||"").trim()).filter(Boolean).join(`
2
2
 
3
- `)||void 0,d={};p.trim()&&(d.mcp=Math.round(p.length/4));for(const e of a){const s=Math.round(String(e.system||"").trim().length/4);s&&(d[e.id||e.specs[0]?.name||"group"]=s)}return{specs:r,system:T,systemParts:d,remoteTools:u,traits:l,serialTools:g,reach:h,hiddenVia:o,residents:M,async execute(e,s,i={}){const c=m.get(e);return c?c(e,s,i):JSON.stringify({error:`Unknown tool: ${e}`})}}}export{x as buildToolset};
3
+ `)||void 0,d={};m.trim()&&(d.mcp=Math.round(m.length/4));for(const e of i){if(e.quiet===!0)continue;const s=Math.round(String(e.system||"").trim().length/4);s&&(d[e.id||e.specs[0]?.name||"group"]=s)}return{specs:r,system:q,systemParts:d,remoteTools:y,traits:p,serialTools:M,reach:l,hiddenVia:o,residents:S,quietTools:w,hinters:a,async execute(e,s,c={}){const f=u.get(e);return f?f(e,s,c):JSON.stringify({error:`Unknown tool: ${e}`})}}}export{V as buildToolset};
package/turn-loop.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import{runToolRound as pt}from"./tool-round.js";import{toolTraits as dt,effectiveToolName as W,parallelEligible as ft}from"./tool-traits.js";import{createToolLoopGuard as tt,roundSignature as mt,toolMadeProgress as ht,blockedToolResult as gt}from"./tool-loop-guard.js";import{createAdaptiveToolPolicy as et,adaptiveToolRetryHint as yt,resultText as P}from"./adaptive-tool-policy.js";import{toolStatus as kt}from"./tool-hints.js";import{isSmallWindow as Tt,SMALL_WINDOW_ROUNDS as nt}from"./context-window.js";import{createShimLog as ot}from"./shim.js";import{EXHAUSTED_NOTE as xt}from"./model-view.js";import{HUB_TOOL_NAME as _t}from"./tool-hub.js";const q=60,wt=6,X=4e3,Y=`
2
2
 
3
- `,z=Object.freeze(["The tool budget for this turn is spent. Do not call tools again; write your answer now with what you have, including your findings.","No more tool calls will be answered. Reply with your answer as plain text, now — a partial answer beats none.","FINAL: any further tool call ends this turn with no answer. Write what you have found, as text, in this message."]),St="You have repeated the same tool call several times. Do not call tools again; answer now with what you have.",rt=/\[External MCP[^\n]*\n|⟦\/?EXTERNAL_MCP_OUTPUT⟧/g,bt=t=>/^\s*(?:error\b|\{"error")|"error"\s*:/i.test(String(t||"").replace(rt,""));function qt(t=[],{finish:o="",window:e=0,thinking:n=!1}={}){if(/^(length|max_tokens|max_output_tokens)$/i.test(String(o||"")))return`⚠ The model ran out of room: its${Number(e)>0?` ${Math.round(Number(e)/1024)}k-token`:""} window filled ${n?"while it was still thinking":"before it wrote an answer"}. A longer context (Settings › Runtime › the engine's Profile), less thinking (its Thinking setting), or a new chat gives it room.`;const r=[...Array.isArray(t)?t:[]].reverse().find(x=>/^error/i.test(String(x?.status||""))||bt(x?.result));if(!r)return"⚠ The model ended this turn without an answer. Try again, or pick another model.";const a=r.input?.action||r.action||r.tool||r.name||"an action",c=(/^error/i.test(String(r.status||""))?String(r.status).replace(/^error:\s*/i,""):String(r.result||"")).replace(rt,"").replace(/\s+/g," ").trim().slice(0,200);return`⚠ No answer: the turn ended after \`${a}\` failed${c?` — ${c}`:""}. Try again, or ask without it.`}function Xt({tools:t,agent:o,settings:e,fallback:n=q}={}){if(!t)return 1;const a=[Math.max(1,Number(n)||q)],h=Number(o?.maxRequestsPerTurn)||0;h>0&&a.push(h);const c=Number(e?.ui?.maxToolRoundsPerTurn??e?.maxToolRoundsPerTurn)||0;return c>0&&a.push(c),Tt(o?.window||o?.contextLength||o?.contextWindow)&&a.push(nt),Math.max(1,Math.min(...a))}function B(t){if(!t)return{};if(typeof t=="object")return t;try{return JSON.parse(t)}catch{return{}}}const st=t=>typeof t.arguments=="string"?t.arguments:JSON.stringify(t.arguments??t.input??{});function Nt(t){const o=String(P(t)||"");return o.length>X?`${o.slice(0,X)}…`:o}function Rt(t){const o=String(P(t)||"").length;if(o<=X)return"";const e=n=>n.toLocaleString("en-US");return`Showing the first ${e(X)} of ${e(o)} characters — the model received all of them.`}function At(t,o){const e=W(t,o),n=o&&typeof o=="object"&&o.args&&typeof o.args=="object"?o.args:o||{},r=["query","id","tool","location","ref"].find(a=>typeof n[a]=="string"&&n[a]);return r?`${e} "${String(n[r]).slice(0,80)}"`:e}function zt(t,o){const e=Array.isArray(t)?[...t]:[],n=String(o||"").trim();if(!n)return e;const r=e.findIndex(a=>a?.role==="system"&&typeof a.content=="string");return r>=0?(e[r]={...e[r],content:`${e[r].content}
3
+ `,z=Object.freeze(["The tool budget for this turn is spent. Do not call tools again; write your answer now with what you have, including your findings.","No more tool calls will be answered. Reply with your answer as plain text, now — a partial answer beats none.","FINAL: any further tool call ends this turn with no answer. Write what you have found, as text, in this message."]),St="You have repeated the same tool call several times. Do not call tools again; answer now with what you have.",rt=/\[External MCP[^\n]*\n|⟦\/?EXTERNAL_MCP_OUTPUT⟧/g,bt=t=>/^\s*(?:error\b|\{"error")|"error"\s*:/i.test(String(t||"").replace(rt,""));function qt(t=[],{finish:o="",window:e=0,thinking:n=!1}={}){if(/^(length|max_tokens|max_output_tokens)$/i.test(String(o||"")))return`⚠ The model ran out of room: its${Number(e)>0?` ${Math.round(Number(e)/1024)}k-token`:""} window filled ${n?"while it was still thinking":"before it wrote an answer"}. A longer context (Settings › Runtime › the engine's Profile), less thinking (its Thinking setting), or a new chat gives it room.`;const r=[...Array.isArray(t)?t:[]].reverse().find(x=>/^error/i.test(String(x?.status||""))||bt(x?.result));if(!r)return"⚠ The model ended this turn without an answer. Try again, or pick another model.";const a=r.input?.action||r.action||r.tool||r.name||"an action",c=(/^error/i.test(String(r.status||""))?String(r.status).replace(/^error:\s*/i,""):String(r.result||"")).replace(rt,"").replace(/\s+/g," ").trim().slice(0,200);return`⚠ No answer: the turn ended after \`${a}\` failed${c?` — ${c}`:""}. Try again, or ask without it.`}function Xt({tools:t,agent:o,settings:e,fallback:n=q}={}){if(!t)return 1;const a=[Math.max(1,Number(n)||q)],h=Number(o?.maxRequestsPerTurn)||0;h>0&&a.push(h);const c=Number(e?.ui?.maxToolRoundsPerTurn??e?.maxToolRoundsPerTurn)||0;return c>0&&a.push(c),Tt(o?.window||o?.contextLength||o?.contextWindow)&&a.push(nt+(t?.handoff?1:0)),Math.max(1,Math.min(...a))}function B(t){if(!t)return{};if(typeof t=="object")return t;try{return JSON.parse(t)}catch{return{}}}const st=t=>typeof t.arguments=="string"?t.arguments:JSON.stringify(t.arguments??t.input??{});function Nt(t){const o=String(P(t)||"");return o.length>X?`${o.slice(0,X)}…`:o}function Rt(t){const o=String(P(t)||"").length;if(o<=X)return"";const e=n=>n.toLocaleString("en-US");return`Showing the first ${e(X)} of ${e(o)} characters — the model received all of them.`}function At(t,o){const e=W(t,o),n=o&&typeof o=="object"&&o.args&&typeof o.args=="object"?o.args:o||{},r=["query","id","tool","location","ref"].find(a=>typeof n[a]=="string"&&n[a]);return r?`${e} "${String(n[r]).slice(0,80)}"`:e}function zt(t,o){const e=Array.isArray(t)?[...t]:[],n=String(o||"").trim();if(!n)return e;const r=e.findIndex(a=>a?.role==="system"&&typeof a.content=="string");return r>=0?(e[r]={...e[r],content:`${e[r].content}
4
4
 
5
5
  ${n}`},e):[{role:"system",content:n},...e]}const N=t=>Number(t)||0;function it(t){if(!t||typeof t!="object")return null;const o=N(t.cacheReadTokens??t.cache_read_input_tokens??t.prompt_tokens_details?.cached_tokens),e=N(t.cacheWriteTokens??t.cache_creation_input_tokens),n=t.inputTokens??t.input_tokens,r=n!=null?N(n):Math.max(0,N(t.prompt_tokens)-o-e),a=N(t.outputTokens??t.output_tokens??t.completion_tokens),h=r+o+e,c={inputTokens:r,outputTokens:a,cacheReadTokens:o,cacheWriteTokens:e,prompt_tokens:h,completion_tokens:a,total_tokens:N(t.total_tokens)||h+a,calls:N(t.calls)||1,reported:t.reported!==!1&&(h>0||a>0)},x=N(t.usd??t.cost);return x&&(c.usd=x),c}function Ot(t,o){const e=it(t),n=it(o);if(!n)return e;if(!e)return n;const r={inputTokens:e.inputTokens+n.inputTokens,outputTokens:e.outputTokens+n.outputTokens,cacheReadTokens:e.cacheReadTokens+n.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens+n.cacheWriteTokens,calls:e.calls+n.calls,reported:e.reported||n.reported};r.prompt_tokens=r.inputTokens+r.cacheReadTokens+r.cacheWriteTokens,r.completion_tokens=r.outputTokens,r.total_tokens=e.total_tokens+n.total_tokens;const a=N(e.usd)+N(n.usd);return a&&(r.usd=a),r}function at(t){return Math.max(0,Math.round(String(t||"").length/4))}function Mt(t,o){const e=(t||[]).map(n=>typeof n?.content=="string"?n.content:JSON.stringify(n?.content||"")).join(`
6
6
  `);return{inputTokens:at(e),outputTokens:at(o),cacheReadTokens:0,cacheWriteTokens:0,estimated:!0}}const Et=Object.freeze({asked(t,o){return{role:"assistant",content:String(t?.text||"")||null,tool_calls:o.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:st(e)}}))}},answered(t,{noVision:o=!1}={}){const e=t.map(({call:n,result:r})=>({role:"tool",tool_call_id:n.id,content:P(r)}));for(const{call:n,result:r}of t){const a=r&&typeof r=="object"?r.image:null;a&&e.push(o?{role:"user",content:`(Screenshot from ${n.name} omitted — this model has no vision. Rely on read_canvas / inspect_page / tool results.)`}:{role:"user",content:[{type:"text",text:`(Screenshot from ${n.name})`},{type:"image_url",image_url:{url:a}}]})}return e},nudge(t,o){return[{role:"assistant",content:null,tool_calls:t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:st(e)}}))},...t.map(e=>({role:"tool",tool_call_id:e.id,content:o}))]},system:t=>({role:"system",content:t}),said:t=>({role:"assistant",content:t})}),Bt=Object.freeze({asked(t,o){return{role:"assistant",content:Array.isArray(t?.blocks)&&t.blocks.length?t.blocks.filter(n=>n&&(n.type==="tool_use"||n.type==="text"&&n.text)).map(n=>n.type==="tool_use"?{type:"tool_use",id:n.id,name:n.name,input:n.input??B(n.json)}:{type:"text",text:n.text}):[...t?.text?[{type:"text",text:String(t.text)}]:[],...o.map(n=>({type:"tool_use",id:n.id,name:n.name,input:n.input}))]}},answered(t){return[{role:"user",content:t.map(({call:o,result:e})=>{const n=P(e),r=e&&typeof e=="object"?e.image:null;if(!r)return{type:"tool_result",tool_use_id:o.id,content:n};const a=/^data:([^;]+);base64,(.+)$/s.exec(r),h=[];return a&&h.push({type:"image",source:{type:"base64",media_type:a[1],data:a[2]}}),h.push({type:"text",text:n}),{type:"tool_result",tool_use_id:o.id,content:h}})}]},nudge(t,o){return[{role:"assistant",content:t.map(e=>({type:"tool_use",id:e.id,name:e.name,input:e.input}))},{role:"user",content:t.map(e=>({type:"tool_result",tool_use_id:e.id,content:o}))}]},system:t=>({role:"user",content:t}),said:t=>({role:"assistant",content:t})});function vt({tools:t,guard:o=null,policy:e=null,modelLabel:n=()=>null,maxCalls:r=0,onStep:a=null,steps:h=[],now:c=Date.now,shims:x=ot()}={}){o=o||tt({shims:x}),e=e||et({shims:x});let R=0,w=0;const M=c(),_=new Map,j=s=>{const l=W(s.name,s.input);return t?.traits?.get(l)||t?.traits?.get(s.name)||dt({name:l})},E=(s,l,i,m)=>{const y={phase:l,callId:s.id,name:s.name,action:W(s.name,s.input),input:s.input,text:At(s.name,s.input),model:n(),...m};if(l==="start")_.set(s.id,y.at=Math.max(0,c()-M));else{const b=i&&typeof i=="object"?i.image:void 0,u=_.get(s.id)??Math.max(0,c()-M),f=Rt(i);Object.assign(y,{status:kt(i),result:Nt(i),...f?{resultNote:f}:{},at:u,ms:Math.max(0,c()-M-u),...b?{image:b}:{}})}return y},I=(s,l)=>{try{a?.(E(s,"start",void 0,l))}catch{}},A=(s,l,i)=>{const m=E(s,"done",l,i);h.push(m);try{a?.(m)}catch{}},C=(s,l,i)=>{e.recordResult(W(s.name,s.input),i),!l.blocked&&!l.replayed&&ht(s.name,i,s.input)&&o.reset(l.key),l.replayed||o.remember(l.key,s.name,s.input,i,{readOnly:!!j(s)?.readOnly})},V=s=>(x.fire("loop.budget-spent",{tool:W(s.name,s.input),calls:R,maxCalls:r}),gt(s.name,z[Math.min(Math.max(0,R-r-1),z.length-1)],{budget:"spent",calls:R,maxCalls:r})),J=async(s,l,i)=>{if(R+=1,r>0&&R>r)return V(s);if(l.blocked||l.replayed)return l.result;if(typeof t?.execute!="function")return JSON.stringify({error:"no tools armed"});const m=W(s.name,s.input);return m!==s.name&&e.isSuppressed(m)?JSON.stringify({error:`${m} rejected its parameters earlier in this turn and is off for the rest of it.`,retry_hint:yt(m)}):t.execute(s.name,s.input,{callId:s.id,shims:x,...i||{}})};return{guard:o,policy:e,steps:h,traitsOf:j,shims:x,get calls(){return R},get exhausted(){return r>0&&R>=r},async one(s,l=null){const i={id:s.id,name:s.name,input:s.input??B(s.arguments)};I(i);const m=o.check(i.name,i.input);let y;try{y=await J(i,m,l)}catch(b){y=JSON.stringify({error:String(b?.message||b)})}return C(i,m,y),A(i,y),y},async round(s){const l=s.map(u=>({id:u.id,name:u.name,input:u.input??B(u.arguments)})),i=l.map(u=>o.check(u.name,u.input)),m=w+=1,{results:y}=await pt(l,{execute:(u,f)=>J(u,i[f]),traitsOf:j,concurrent:(u,f)=>ft(t,u,f),onStart:(u,f,p)=>I(u,{round:m,batch:p}),onDone:(u,f,p,v)=>A(u,p,{round:m,batch:v})});y.forEach((u,f)=>C(l[f],i[f],u));const b=i.filter(u=>u.blocked).length;return o.noteRound(b,l.length,mt(l)),{calls:l,results:y,blocked:b}}}}function Dt(t){const o=String(t?.input?.action||"").toLowerCase();return t?.name===_t&&o==="find"||o==="describe"}const $t=2;function Ut(t){const o=String(t||"").trim();if(!o)return!1;const e=o.split(/(?<=[.!?…:])\s+|\n+/).map(n=>n.trim()).filter(Boolean).at(-1)||"";return e.length>200||/\?\s*$/.test(e)?!1:/^(?:(?:ok(?:ay)?|sure|alright|now|first|so)[,.!]?\s+)?(?:let me|let[’']s|i[’']?ll|i will|i[’']?m going to|i am going to|i[’']?m now going to|now i[’']?ll|one moment|give me a (?:moment|sec(?:ond)?))\b[^?]{0,160}\b(?:look|check|search|find|open|read|fetch|pull|browse|see|try|get|gather|query|dig|explore)\b/i.test(e)}const Wt="You said what you would do next, but called no tool. Do it now with a tool call, or, if no tool can do it, answer with what you have.";async function Vt({model:t,messages:o,tools:e,signal:n,redaction:r,run:a,stream:h,transcript:c=Et,maxRounds:x=q,maxFinishTries:R=wt,guard:w=null,policy:M=null,shims:_=null,modelLabel:j=()=>t||null,usageLabel:E=null,onDelta:I=null,onEvent:A=null,onStep:C=null,onMessage:V=null,onActivity:J=null}={}){if(typeof h!="function")throw new Error("runTurnLoop: stream required");_=_||ot({emit:A?(k,d)=>A({type:"shim",...d}):null,engine:E?.provider?{kind:"model",id:E.provider,model:E.model||t||void 0}:t?{kind:"model",id:t}:null}),w=w||tt({shims:_}),M=M||et({shims:_});const s=!!(e&&Array.isArray(e.specs)&&e.specs.length),l=s?e.specs:null;let i=s?Math.max(1,Number(x)||q):1,m=$t,y=!1;const b=[],u=vt({tools:e,guard:w,policy:M,modelLabel:j,steps:b,shims:_,onStep:k=>{try{C?.(k)}catch{}try{A?.({type:"tool",...k})}catch{}}});let f=[...o||[]],p="",v=null,S=0,K=!1,D=0,F=!1;const $=k=>{for(const d of k){f=[...f,d];try{V?.(d)}catch{}}},L=k=>{try{A?.({type:"finish",reason:k})}catch{}},Q=k=>{if(!A)return;const d=v&&v.reported?{...v,estimated:!1}:Mt(f,k);try{A({type:"usage",provider:E?.provider||"unknown",model:E?.model||t||null,inputTokens:d.inputTokens,outputTokens:d.outputTokens,cacheReadTokens:d.cacheReadTokens,cacheWriteTokens:d.cacheWriteTokens,estimated:!!d.estimated,requests:S})}catch{}},Z=k=>({ok:!0,text:p,usage:v,rounds:S,steps:b,transcript:f,exhausted:F,aborted:!1,shims:_.summary(),...k}),G=(k,d={})=>{const O=String(k||"");return O.trim()&&$([c.said(O)]),Z(d)};for(;;){S+=1;const k=!s||S>=i||w.stalled||w.looping||D>0;s&&S<i&&D===0&&(w.stalled||w.looping)&&_.fire("loop.closing-early",{round:S,cap:i,stalled:!!w.stalled,looping:!!w.looping});const d=k?null:l.filter(g=>!M.isSuppressed(g?.name));let O="";const T=await h({model:t,messages:f,tools:d&&d.length?d:null,signal:n,onActivity:J,...r!==void 0?{redaction:r}:{},...a?{run:a}:{},onDelta:g=>{if(g){if(!O&&p){p+=Y;try{I?.(Y,p)}catch{}}O+=g,p+=g;try{I?.(g,p)}catch{}}}});T?.usage&&(v=Ot(v,T.usage)),T?.noVision&&(K=!0);const H=String(T?.text||"");if(H&&!O&&(p&&(p+=Y),p+=H,O=H),!T?.ok)return L("error"),Z({ok:!1,error:T?.error||"the model did not answer",...T?.status?{status:T.status}:{},aborted:!!T?.aborted,transcript:H.trim()?[...f,c.said(p)]:f});if(T.aborted||n?.aborted)return L("aborted"),G(p,{aborted:!0});const U=(Array.isArray(T.toolCalls)?T.toolCalls:[]).filter(g=>g&&g.name).map(g=>({id:g.id,name:g.name,input:g.input??B(g.arguments),arguments:g.arguments}));if(!U.length){if(!y&&d&&d.length&&Ut(O)){y=!0,S+1>=i&&(i=S+2),_.fire("loop.announced-not-done",{round:S}),$([c.said(O),{role:"user",content:Wt}]);continue}return L(T.finish||"stop"),Q(p),G(p,{finish:T.finish||"stop"})}if(!d||!d.length){if(D+=1,D>R)return L("tool-step-limit"),Q(p),G(p,{exhausted:!0});F=F||S>=i,_.fire("loop.finish-nudge",{attempt:D,calls:U.length}),$(c.nudge(U,z[Math.min(D-1,z.length-1)]));continue}$([c.asked(T,U)]);const{calls:lt,results:ut}=await u.round(U);if($(c.answered(lt.map((g,ct)=>({call:g,result:ut[ct]})),{noVision:K})),n?.aborted)return L("aborted"),G(p,{aborted:!0});w.looping&&(_.fire("loop.looping-nudge",{repeats:w.repeats}),$([c.system(St)])),m>0&&U.every(Dt)&&(m-=1,i+=1,_.fire("loop.discovery-round",{round:S,cap:i})),S+1>=i&&(F=!0)}}export{Wt as ANNOUNCED_NUDGE,wt as DEFAULT_MAX_FINISH_TRIES,q as DEFAULT_MAX_ROUNDS,$t as DISCOVERY_GRACE,xt as EXHAUSTED_NOTE,z as FINISH_NUDGES,St as LOOPING_NUDGE,Y as ROUND_SEPARATOR,nt as SMALL_WINDOW_ROUNDS,X as STEP_RESULT_MAX_CHARS,Ot as addUsage,Ut as announcesAction,Bt as anthropicTranscript,vt as createCallRunner,At as describeCall,qt as emptyTurnNote,at as estimateTokens,Dt as isDiscoveryCall,it as normalizeUsage,Et as openAiTranscript,P as resultText,Xt as roundCap,Vt as runTurnLoop,Rt as stepResultNote,Nt as stepResultText,zt as withToolSystem};
package/web-research.js CHANGED
@@ -1,7 +1,7 @@
1
- import{fuseRRF as W,planQueries as re}from"./rrf.js";import{buildIndex as oe,bm25Search as ne}from"./text-index.js";import{offersIn as ae,rankOffers as ie,quoteFormIn as ce,formatValue as Z,basisLabel as M,hostOf as le}from"./offers.js";import{fenceUntrusted as ue}from"./page-guard.js";import{markdownUrl as U}from"./citations.js";const P=Object.freeze({queries:4,rounds:2,parallel:3,pages:10,perHost:2,read:6,passages:8,passageChars:700,offers:8,forms:5,ms:25e3,briefChars:9e3}),C="jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?",Y="monday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tue|wed|thu|fri|sat|sun",N=new RegExp(String.raw`\b(?:(?:${C})\.?\s+\d{1,2}(?:st|nd|rd|th)?(?:\s*(?:-|–|to|until)\s*(?:(?:${C})\.?\s+)?\d{1,2}(?:st|nd|rd|th)?)?(?:,?\s+\d{4})?|\d{1,2}(?:st|nd|rd|th)?\s+(?:${C})\b(?:\s+\d{4})?|(?:in|during|for|this|next|early|mid|late)\s+(?:${C})\b|\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}(?:\/\d{2,4})?|(?:this|next|coming)\s+(?:week(?:end)?|month|(?:${Y}))|tomorrow|tonight|today|(?:over|for)\s+(?:christmas|thanksgiving|new year'?s?|easter|spring break|the holidays)|in\s+\d+\s+(?:days?|weeks?|months?))\b`,"i"),he=new RegExp(`^(?:${C}|${Y}|today|tomorrow|tonight|next|this|the|a|an|my|our|me|us|\\d+)$`,"i"),de=/\s+(?:for|from|to|on|in|at|under|below|with|next|this|during|by|and|or|between|around|near|within|over|departing|leaving|returning|round|one|nonstop|direct|cheap|best|flights?|hotels?|deals?)\b.*$/i,pe=/\b(\d{5}(?:-\d{4})?|[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2})\b/,K=/\b([A-Z]{3})\s*(?:-|–|→|>|to)\s*([A-Z]{3})\b/;function z(e){const t=String(e||"").replace(de,"").replace(/[?!.,;:]+$/g,"").trim();return!t||t.split(/\s+/).length>4||he.test(t)||N.test(t)||!new RegExp("\\p{L}","u").test(t)||/^(?:me|here|there|home|you|it|them|us|the|a|my|our|cheap|best|flights?|hotels?)$/i.test(t)?"":t}const D={where:e=>{const t=pe.exec(e);if(t)return t[1];const r=/\b(?:in|near|around|at|for)\s+([\p{L}][\p{L}.'’ -]{1,40})/iu.exec(e.replace(N," "));return r?z(r[1]):""},from:e=>{const t=K.exec(e);if(t)return t[1];const r=/\bfrom\s+([\p{L}][\p{L}.'’ -]{1,40}?)(?=\s+(?:to|→|-)\s|\s*$|[?,])/iu.exec(e)||/\b([\p{L}][\p{L}.'’ -]{1,30}?)\s+to\s+[\p{L}][\p{L} .'-]{1,30}?\s+(?:flights?|fares?|airfare|tickets?)\b/iu.exec(e);return r?z(r[1].replace(/^(?:cheap(?:est)?|best|find|flights?|fly(?:ing)?|airfares?)\s+/i,"").replace(/^(?:flights?|fly(?:ing)?)\s+/i,"")):""},to:e=>{const t=K.exec(e);if(t)return t[2];const r=/\bto\s+([\p{L}][\p{L}.'’ -]{1,40})/iu.exec(e.replace(/\bhow much\b/i,""));return r?z(r[1]):""},when:e=>(N.exec(e)?.[0]||"").trim(),who:e=>/\b(\d+|one|two|three|four|five|six|seven|eight)\s+(?:adults?|people|persons|passengers|travell?ers|guests|of us)\b|\bfamily of (\d+)\b|\b(solo|couple)\b/i.exec(e)?.[0]||"",budget:e=>/\b(?:under|below|less than|max(?:imum)?|up to|within|no more than|<)\s*(?:[$€£]\s?)?\d[\d,.]*\s?(?:k|usd|eur|gbp|dollars|euros|pounds)?(?:\s*(?:\/|per|a)\s*(?:mo(?:nth)?|yr|year|night))?\b/i.exec(e)?.[0]||"",kind:e=>(/\b(auto|car|vehicle|motorcycle|homeowners?|home|house|renters?|condo|landlord|term life|whole life|life|health|medical|dental|vision|pet|dog|cat|travel|boat|umbrella|business)\b/i.exec(e)?.[1]||"").toLowerCase()},B=Object.freeze([{id:"insurance",label:"insurance",match:/\binsur(?:ance|er|ers)\b|\b(?:premiums?|coverage) (?:quotes?|rates?|prices?)\b/i,terms:["insurance","quote","rate","premium","coverage"],subject:"{kind?} insurance",queries:["{kind?} insurance quotes {where?}","cheapest {kind?} insurance {where?} {year}","{kind?} insurance rates compared {year}"],slots:[{id:"kind",label:"what to insure (car, home, renters, life, health, pet, travel…)",required:!0},{id:"where",label:"ZIP code / postcode or state",required:!0}],forms:!0},{id:"flight",label:"flights",match:/\b(?:flights?|airfares?|air ?fares?|plane tickets?|airline tickets?|fly(?:ing)? (?:to|from|out)|nonstop to)\b/i,terms:["flight","fare","airline","round","trip"],subject:"flights",queries:["cheap flights {from} to {to} {when?}","{from} to {to} flight deals","{from} {to} airfare {when?} {year}","cheap flight deals {year}","best time to book flights {year}"],slots:[{id:"from",label:"departure city or airport",required:!0},{id:"to",label:"destination",required:!0},{id:"when",label:"travel dates",required:!0},{id:"who",label:"number of travellers",required:!1}],forms:!0},{id:"hotel",label:"hotels",match:/\b(?:hotels?|motels?|resorts?|accommodation|lodging|places? to stay|vacation rentals?|airbnb|b&b)\b/i,terms:["hotel","night","room","stay"],subject:"hotels",queries:["best hotel deals {where} {when?}","cheap hotels {where} {when?}","{where} hotels price per night {year}","hotel deals {year}"],slots:[{id:"where",label:"city or area",required:!0},{id:"when",label:"dates",required:!0},{id:"who",label:"number of guests",required:!1}],forms:!0},{id:"car-rental",label:"car rental",match:/\b(?:car rentals?|rental cars?|rent a car|hire car|car hire)\b/i,terms:["rental","car","day"],subject:"car rental",queries:["cheap car rental {where} {when?}","car rental deals {where} {year}","car rental deals {year}"],slots:[{id:"where",label:"pick-up city or airport",required:!0},{id:"when",label:"dates",required:!0}],forms:!0},{id:"plan",label:"plans",match:/\b(?:internet|broadband|fib(?:er|re)|wi-?fi|mobile|cell(?:ular)?|phone|sim|electric(?:ity)?|energy|power|gas|streaming|vpn|cloud storage)\s+(?:plans?|providers?|deals?|services?|bills?|tariffs?|rates?|packages?)\b/i,terms:["plan","month","price"],queries:["best {subject} {where?} {year}","cheapest {subject} {where?}","{subject} prices compared {year}"],slots:[{id:"where",label:"ZIP code / city",required:!1},{id:"budget",label:"budget",required:!1}],forms:!1},{id:"product",label:"products",match:null,terms:["price","review"],queries:["best {subject} {budget?} {year}","{subject} price","{subject} deals {budget?}"],slots:[{id:"budget",label:"budget",required:!1}],forms:!1}]),I=e=>B.find(t=>t.id===e)||B[B.length-1],Q=/\b(?:cheapest|cheaper|lowest (?:price|fare|rate|cost)s?|affordable|deals?|discounts?|coupons?|promo codes?|on sale|bargains?|prices?|pricing|fares?|(?:get|want|need|free|instant) (?:a |an |my )?quotes?|quotes? (?:for|on)|how much (?:is|are|does|do|would|will|for|to)\b(?!\s+(?:time|longer|more|of my|of the (?:meeting|page|doc)))[^?]*\b(?:cost|costs|charge|pay|price)|how much (?:is|are) (?:a|an|the)? ?(?:flight|ticket|hotel|room|night)|cost of (?:a|an|the)?)\b/i,fe=/\b(?:best|top[- ]rated|compare|comparison|vs\.?|versus|recommend(?:ation)?s? for|worth buying|quotes?|where (?:can i|to|should i) (?:buy|get|find|book|rent)|save money on|rates?)\b/i,ge=/\b(?:buy|buying|purchase|shop(?:ping)?|order|book(?:ing)?|rent(?:al|ing)?|subscribe|subscription|plans?|insurance|flights?|hotels?|tickets?|deals?|prices?|costs?|rates?|fares?|movers?|moving company|contractors?|plumbers?|roofers?|repair (?:shop|service)s?|installation|providers?|under\s*[$€£]?\s?\d)\b|[$€£]\s?\d/i,me=/\bbest\s+(?!way|ways|practice|practices|time|approach|method|answer|thing|things|idea|ideas|advice|place to (?:learn|start)|book(?!ing))[\p{L}\d][\p{L}\d+-]*(?:\s+[\p{L}\d][\p{L}\d+-]*){0,3}\s+(?:for|under|below|to buy|in 20\d\d|of 20\d\d)\b/iu,be=/\b(?:stocks?|shares?|share price|ticker|market cap|dividend|crypto(?:currency)?|bitcoin|ethereum|exchange rate)\b|\b(?:my|our) (?:notes?|meetings?|chats?|calendar|emails?|inbox|files?|docs?|documents?|history|library)\b|\b(?:this|the) (?:page|tab|doc(?:ument)?|file|repo(?:sitory)?|code(?:base)?|pr|diff|function|spreadsheet)\b|\b(?:function|exception|stack ?trace|npm|pip|python|javascript|typescript|regex|sql|compile|git|docker|kubernetes|api key|endpoint)\b/i,G=/^\s*(?:(?:hey|hi|ok(?:ay)?|so|please|pls|can you|could you|would you|will you|help me|i need(?: to)?|i want(?: to)?|i'?m looking for|i am looking for|look(?:ing)? for|find(?: me)?|get(?: me)?|show(?: me)?|search(?: for)?|look up|tell me|give me|what(?:'s| is| are)|which(?: is| are)?|where(?:'s| is| are| can i (?:buy|get|find|book))?|who (?:has|offers)|how much (?:is|are|does|do|for)|how much)\s+)+/i,F=/\s+(?:for me|for us|near me|right now|now|today|online|please|pls|this year|in 20\d\d)\s*$|[?!.]+$/i,we=/\b(?:the|a|an|best|cheapest|cheaper|cheap|lowest|affordable|good|great|top[- ]rated|top|most|really|deals?|discounts?|coupons?|bargains?|quotes?|prices?|pricing|costs?|rates?|fares?|offers?|options?|compare|comparison|cost|to buy|on sale)\b/gi;function ye(e,t){let r=String(e||"").replace(G,"").replace(F,"").replace(F,"");return r=r.replace(N," ").replace(/\b(?:from|to|in|near|around|under|below|for|with|between)\s+.*$/i,o=>t.id==="product"||t.id==="plan"?o.replace(/\b(?:in|near|around|from|to)\s+.*$/i,""):""),r=r.replace(D.budget(r)||"\0"," ").replace(we," ").replace(/\b(?:does|do|is|are|a|an|it|cost|costs|20\d\d|i|can|buy|get|where)\b/gi," ").replace(/\s+/g," ").trim(),r.length>=2?r:t.label}function V(e,t){let r=!0;const o=e.replace(/\{(\w+)(\?)?\}/g,(l,i,s)=>(!t[i]&&!s&&(r=!1),t[i]||""));return r?o.replace(/\s+/g," ").trim():""}function Ie(e,{previous:t=null,now:r=Date.now()}={}){const o=String(e||"").trim();if(!o||o.length>400)return null;const l=o.split(/\s+/).length,i=t?.kind==="research"&&t.research?.domain?t.research:null;let s=B.find(u=>u.match&&u.match.test(o))||null;const d=s?s.slots.filter(u=>D[u.id]?.(o)).length:0,p=!be.test(o)&&l>=2&&(Q.test(o)||fe.test(o)&&(s||ge.test(o))||me.test(o)||s&&(/\b(?:find|search|look|book|get|need)\b/i.test(o)||d>=2));if(!p&&i&&l<=14&&(!s||s.id===i.domain)){const u=I(i.domain),b=Object.fromEntries(u.slots.map(c=>[c.id,D[c.id]?.(o)||""]).filter(([,c])=>c));return Object.keys(b).length?J(`${i.question} ${o}`,u,{...i.slots,...b},r,!0,u.subject?"":i.subject):null}if(!p)return null;s||=I("product");const h=Object.fromEntries(s.slots.map(u=>[u.id,D[u.id]?.(o)||""]).filter(([,u])=>u));return J(o,s,h,r,!1)}function J(e,t,r,o,l,i=""){const s=String(new Date(o).getFullYear()),d=i||(t.subject?V(t.subject,r):ye(e,t)),p={...r,subject:d,year:s},h=t.queries.map(c=>V(c,p)).filter(Boolean),u=l?"":e.replace(G,"").replace(F,"").replace(/^(?:a|an|the)\s+/i,"").trim(),b=(u?re(u,{extra:h,max:P.queries*2}):[...new Set(h)]).filter(c=>c.split(/\s+/).length>=2).slice(0,P.queries);return{question:e,domain:t.id,subject:d,slots:r,missing:t.slots.filter(c=>c.required&&!r[c.id]).map(c=>({id:c.id,label:c.label})),queries:b,forms:t.forms,followUp:l}}function $e(e,t=[],{now:r=Date.now()}={}){const o=String(new Date(r).getFullYear()),l=I(e.domain),i=l.slots.map(u=>e.slots?.[u.id]).filter(Boolean).join(" "),s=e.subject,d=[`${s} ${i} price ${o}`,l.forms?`${s} ${i} average cost`:`${s} ${i} cost`,`${s} ${i} comparison`,`${s} ${i}`],p=new Set(t.map(u=>u.toLowerCase().replace(/\s+/g," ").trim())),h=[];for(const u of d){const b=u.replace(/\s+/g," ").trim();b.split(/\s+/).length>=2&&!p.has(b.toLowerCase())&&!h.includes(b)&&h.push(b)}return h.slice(0,3)}function ke(e){if(e&&typeof e=="object"&&Array.isArray(e.results))return{query:e.query||"",engines:e.engines||[],results:e.results.filter(i=>i?.url)};const t=typeof e=="string"?e:typeof e?.text=="string"?e.text:"",r=/^Web search results for "([^"]*)" \(engines: ([^)]*)\)/m.exec(t),o=t.indexOf("Result details:");if(!r||o<0)return{query:r?.[1]||"",engines:[],results:[]};const l=[];for(const i of t.slice(o).split(/\n+---\n+(?=### \[\d+\])/)){const s=/### \[(\d+)\] ([^\n]*)\n<([^>\s]+)>\n\n?([\s\S]*)$/.exec(i);s&&l.push({rank:Number(s[1]),title:s[2].trim(),url:s[3],text:s[4].trim()})}return{query:r[1],engines:r[2].split(/,\s*/).filter(Boolean),results:l}}const X=/^(?:utm_\w+|gclid|fbclid|msclkid|mc_[a-z]+|ref|ref_src|source|campaign|affiliate|aff_id|clickid|irclickid|_ga)$/i;function xe(e){try{const t=new URL(e);for(const r of[...t.searchParams.keys()])X.test(r)&&t.searchParams.delete(r);return t.hash="",t.toString()}catch{return String(e||"")}}function qe(e){try{const t=new URL(e),o=[...t.searchParams.entries()].filter(([l])=>!X.test(l)).sort(([l],[i])=>l.localeCompare(i)).map(([l,i])=>`${l}=${i}`).join("&");return`${t.hostname.replace(/^www\./,"").toLowerCase()}${t.pathname.replace(/\/+$/,"")||"/"}${o?`?${o}`:""}`}catch{return String(e||"")}}function ve(e,t=P.passageChars){const r=[];let o="";const l=()=>{const i=o.trim();i.length>=40&&r.push(i),o=""};for(const i of String(e||"").split(/\n\s*\n/)){const s=i.replace(/[ \t]+/g," ").trim();if(s)if(s.length>t){l();let d="";for(const p of s.split(/(?<=[.!?])\s+/))d&&d.length+p.length+1>t&&(o=d,l(),d=""),d=d?`${d} ${p}`:p.slice(0,t);o=d,l()}else o.length+s.length+2>t?(l(),o=s):o=o?`${o}
2
- ${s}`:s}return l(),r}async function ee(e,t,r,o){const l=new Array(e.length);let i=0;const s=Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;i<e.length;){const d=i++;try{l[d]=await r(e[d],d)}catch{l[d]=null}}});return await(o?Promise.race([Promise.all(s),o]):Promise.all(s)),l}async function je({ask:e,search:t,read:r=null,rerank:o=null,now:l=()=>Date.now(),until:i=null,limits:s={},onProgress:d=()=>{}}={}){if(!e||typeof t!="function")throw new Error("webResearch: ask and search required");const p={...P,...s},h=l(),u=()=>l()-h>p.ms;let b=!1;const c=i?i.then(()=>{b=!0}):null,x=I(e.domain),q=[],A=[],k=new Map,O=new Set;let v=0,a=null;const f=(S,L)=>{try{d({phase:S,label:L,searches:q.length,pages:k.size,offers:a?.offerCount||0})}catch{}};let m=e.queries.slice(0,p.queries);for(let S=1;S<=p.rounds&&m.length;S++){f("search",`Searching: ${m.map($=>`“${$}”`).join(", ")}`);const L=await ee(m,p.parallel,async $=>ke(await t($)),c);if(m.forEach(($,n)=>{q.push($);const g=L[n];if(!g?.results?.length){v+=1;return}g.engines.forEach(y=>O.add(y));const w=[];g.results.forEach(y=>{const R=qe(y.url);w.push(R);const T=k.get(R),H=String(y.text||y.snippet||"");T?(T.foundBy.push($),H.length>T.text.length&&(T.text=H)):k.set(R,{key:R,url:xe(y.url),title:y.title||y.url,host:le(y.url),text:H,foundBy:[$]})}),A.push(w)}),r&&!b&&!u()){const $=te(A,k,p).filter(n=>n.text.length<400).slice(0,p.read);if($.length){f("read",`Reading ${$.length} page${$.length===1?"":"s"}`);const n=await ee($,p.parallel,g=>r(g.url),c);$.forEach((g,w)=>{const y=n[w],R=typeof y=="string"?y:y?.text;R&&R.length>g.text.length&&(g.text=String(R),y?.title&&(g.title=y.title))})}}if(a=await se({ask:e,d:x,lists:A,pages:k,L:p,rerank:o}),f("decide",Se(a)),a.enough||b||u()||S===p.rounds)break;m=$e(e,q,{now:h})}a||=await se({ask:e,d:x,lists:A,pages:k,L:p,rerank:null});const E={searches:q.length,failed:v,pages:k.size,sites:new Set([...k.values()].map(S=>S.host)).size,engines:[...O],ms:Math.max(0,l()-h)},j={ask:e,queries:q,...a,stats:E};return{...j,text:Ee(j,p)}}function te(e,t,r){const o=new Map,l=[];for(const{id:i}of W(e)){const s=t.get(i);if(!s?.host)continue;const d=o.get(s.host)||0;if(!(d>=r.perHost)&&(o.set(s.host,d+1),l.push(s),l.length>=r.pages))break}return l}async function se({ask:e,d:t,lists:r,pages:o,L:l,rerank:i}){const s=te(r,o,l),d=new Map(s.map((n,g)=>[n.key,g])),p=[e.subject,...Object.values(e.slots||{}),...t.terms],h=t.id!=="product"||Q.test(e.question)||!!e.slots?.budget||/\b(?:cheap|costs?|deals?|quotes?|rates?)\b|[$€£]/i.test(e.question),u=[];for(const n of s)ve(n.text,l.passageChars).forEach((g,w)=>u.push({id:`${n.key}#${w}`,key:n.key,url:n.url,host:n.host,title:n.title,text:g}));const b=`${p.join(" ")}${h?" price cost per month":""}`,c=u.length?ne(oe(u),b).map(n=>n.id):[],x=[...u].sort((n,g)=>d.get(n.key)-d.get(g.key)).map(n=>n.id),q=h?u.filter(n=>/[$€£]\s?\d|\d\s?(?:€|£|USD|EUR|GBP)\b/.test(n.text)).map(n=>n.id):[],A=[c,x,...q.length?[q]:[]];if(typeof i=="function"&&c.length){const n=c.slice(0,40).map(g=>u.find(w=>w.id===g));try{const g=await i(e.question,n.map(w=>w.text));Array.isArray(g)&&g.length===n.length&&A.push(n.map((w,y)=>({id:w.id,s:Number(g[y])||0})).sort((w,y)=>y.s-w.s).map(w=>w.id))}catch{}}const k=new Set(c),O=new Map(u.map(n=>[n.id,n])),v=new Map,a=[];for(const{id:n}of W(A)){if(!k.has(n))continue;const g=O.get(n),w=v.get(g.host)||0;if(!(w>=2)&&(v.set(g.host,w+1),a.push(g),a.length>=l.passages))break}const f=h?ie(s.flatMap(n=>ae(n.text,{url:n.url,title:n.title,terms:p,max:l.offers}))):{basis:"",currency:"",ranked:[],floors:[],other:[],averages:[]},m=[];for(const n of s){const g=t.forms||/\bquote\b/i.test(e.question)?ce(n.text):"";if(g&&!m.some(w=>w.host===n.host)&&m.push({url:n.url,title:n.title,host:n.host,cta:g}),m.length>=l.forms)break}const E=f.ranked.length+f.floors.length,j=new Set([...f.ranked,...f.floors].map(n=>n.host)).size,S=f.ranked.some(n=>n.seenOn>=2),L=new Set(a.map(n=>n.host)).size,$=h?E>=3&&j>=2||S&&f.ranked.length>=2:a.length>=4&&L>=3;return{pages:s,passages:a,offers:f,forms:m,enough:$,offerCount:E,wantPrices:h}}function Se(e){const t=[`${e.pages.length} page${e.pages.length===1?"":"s"}`];return e.wantPrices&&t.push(`${e.offerCount} price${e.offerCount===1?"":"s"}`),e.forms.length&&t.push(`${e.forms.length} quote form${e.forms.length===1?"":"s"}`),t.join(" · ")}const _=(e,t)=>{const r=String(e||"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}…`:r};function Ee(e,t={}){const r={...P,...t};if(!e?.pages?.length)return"";const o=new Map,l=a=>(o.has(a.url)||o.set(a.url,{n:o.size+1,title:a.title||a.host||a.url,url:a.url}),o.get(a.url).n),i=a=>`[${l(a)}](${U(a.url)})`,{offers:s,forms:d,passages:p,ask:h,stats:u}=e,b=I(h.domain),c=[],x=`${u.searches} search${u.searches===1?"":"es"}, ${u.pages} page${u.pages===1?"":"s"} from ${u.sites} site${u.sites===1?"":"s"}, ${(u.ms/1e3).toFixed(1)} s`;e.wantPrices&&h.browse?c.push(`(FIRST PASS from web search for the question below — ${x}. These are listing and article pages, not live quotes. A price answers the question only when its page says it is for THIS request (the route or item, and the dates asked); a 12-month low, an average or a deal advertised for other dates does not. When nothing below is that, get it live before answering: open the booking or comparison site in your own tab (page open_tab), enter the request, read the results, and compare at least two sites. Cite with the markdown links given and with the pages you open. Do not repeat these searches.)`):c.push(`(ALREADY RESEARCHED on the web for the question below — ${x}. Answer from this and cite with the markdown links given. `+(e.wantPrices?'State ONLY prices listed under "Prices found" — each was read on the linked page — and call a "from" price an advertised minimum, not a quote. ':"")+"Do not repeat these searches; search again only for something this does not cover.)"),c.push(""),c.push(`Question: ${_(h.question,200)}`);const q=b.slots.filter(a=>h.slots?.[a.id]).map(a=>`${a.id} = ${h.slots[a.id]}`);if(c.push(`Looking for: ${h.subject}${b.id!=="product"?` (${b.label})`:""}${q.length?` · known: ${q.join(" · ")}`:""}`),h.missing?.length&&h.browse?c.push(`Not given: ${h.missing.map(a=>a.label).join("; ")}. Use what the conversation, the user's memory or the pages below point to (a page searched from a city says where they are), say it is an assumption, and go on — ask only when nothing points anywhere. A vague time ("the holidays") is the usual span; say which dates you took.`):h.missing?.length&&c.push(`Missing for a personalised price: ${h.missing.map(a=>a.label).join("; ")}. Ask the user for these before filling any quote form — say what the prices below are based on meanwhile.`),e.wantPrices){c.push("");const a=s.basis==="month"?"per month":M(s.basis);if(s.ranked.length){c.push(`Prices found (cheapest first, ${a}${s.currency?`, ${s.currency}`:""}):`);const f=[];for(const m of s.ranked){const E=f.find(j=>j.o.currency===m.currency&&Math.round(j.o.value*100)===Math.round(m.value*100));E?E.also.some(j=>j.url===m.url)||E.also.push(m):f.push({o:m,also:[]})}f.slice(0,r.offers).forEach(({o:m,also:E},j)=>{const S=[m,...E].map(i).filter((L,$,n)=>n.indexOf(L)===$).join(" ");c.push(`${j+1}. ${Z(m.value,m.currency,s.basis)}${m.converted?` (${m.raw} ${M(m.basis)})`:""} — “${_(m.quote,160)}” ${S}${m.seenOn>1?` · stated by ${m.seenOn} sites`:""}`)})}else c.push(h.browse?"Prices found: none stated plainly on the pages read — do not invent one; get them live, as above.":"Prices found: none stated plainly on the pages read — do not invent one; say so and offer to get a quote.");s.floors.length&&c.push(`Advertised minimums ("from" — not a quote for this person): ${s.floors.slice(0,4).map(f=>`${Z(f.value,f.currency,s.basis)} ${i(f)}`).join(" · ")}`),s.other.length&&c.push(`On another basis or currency (not comparable with the list above): ${s.other.slice(0,4).map(f=>`${f.raw} ${M(f.basis)} ${i(f)}`).join(" · ")}`),s.averages.length&&c.push(`Averages (context, not offers): ${s.averages.slice(0,3).map(f=>`${f.raw} ${M(f.basis)} — “${_(f.quote,100)}” ${i(f)}`).join(" · ")}`)}if(d.length){c.push(""),c.push("Quote forms (an exact price needs the user's details — you can fill these in the user's browser with the page tools, asking them for anything missing; NEVER press a submit/continue/pay button without the user's OK):");for(const a of d)c.push(`- ${a.host}: “${a.cta}” ${i(a)}`)}const A=p.map(a=>`[${l(a)}] ${a.title?`${_(a.title,80)} — `:""}${a.text}`);c.push(""),c.push("Sources:");for(const a of o.values())c.push(`[${a.n}] [${_(a.title,90)}](${U(a.url)})`);let k=c.join(`
3
- `);const O=r.briefChars-k.length-200;let v="";for(const a of A){if(v.length+a.length+2>O)break;v+=`${v?`
1
+ import{fuseRRF as W,planQueries as re}from"./rrf.js";import{buildIndex as oe,bm25Search as ne}from"./text-index.js";import{offersIn as ae,rankOffers as ie,quoteFormIn as ce,formatValue as Z,basisLabel as M,hostOf as le}from"./offers.js";import{fenceUntrusted as ue}from"./page-guard.js";import{markdownUrl as U}from"./citations.js";const P=Object.freeze({queries:4,rounds:2,parallel:3,pages:10,perHost:2,read:6,passages:8,passageChars:700,offers:8,forms:5,ms:25e3,briefChars:9e3}),C="jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?",Y="monday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tue|wed|thu|fri|sat|sun",N=new RegExp(String.raw`\b(?:(?:${C})\.?\s+\d{1,2}(?:st|nd|rd|th)?(?:\s*(?:-|–|to|until)\s*(?:(?:${C})\.?\s+)?\d{1,2}(?:st|nd|rd|th)?)?(?:,?\s+\d{4})?|\d{1,2}(?:st|nd|rd|th)?\s+(?:${C})\b(?:\s+\d{4})?|(?:in|during|for|this|next|early|mid|late)\s+(?:${C})\b|\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}(?:\/\d{2,4})?|(?:this|next|coming)\s+(?:week(?:end)?|month|(?:${Y}))|tomorrow|tonight|today|(?:over|for)\s+(?:christmas|thanksgiving|new year'?s?|easter|spring break|the holidays)|in\s+\d+\s+(?:days?|weeks?|months?))\b`,"i"),he=new RegExp(`^(?:${C}|${Y}|today|tomorrow|tonight|next|this|the|a|an|my|our|me|us|\\d+)$`,"i"),de=/\s+(?:for|from|to|on|in|at|under|below|with|next|this|during|by|and|or|between|around|near|within|over|departing|leaving|returning|round|one|nonstop|direct|cheap|best|flights?|hotels?|deals?)\b.*$/i,pe=/\b(\d{5}(?:-\d{4})?|[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2})\b/,K=/\b([A-Z]{3})\s*(?:-|–|→|>|to)\s*([A-Z]{3})\b/;function z(e){const t=String(e||"").replace(de,"").replace(/[?!.,;:]+$/g,"").trim();return!t||t.split(/\s+/).length>4||he.test(t)||N.test(t)||!new RegExp("\\p{L}","u").test(t)||/^(?:me|here|there|home|you|it|them|us|the|a|my|our|cheap|best|flights?|hotels?)$/i.test(t)?"":t}const D={where:e=>{const t=pe.exec(e);if(t)return t[1];const r=/\b(?:in|near|around|at|for)\s+([\p{L}][\p{L}.'’ -]{1,40})/iu.exec(e.replace(N," "));return r?z(r[1]):""},from:e=>{const t=K.exec(e);if(t)return t[1];const r=/\bfrom\s+([\p{L}][\p{L}.'’ -]{1,40}?)(?=\s+(?:to|→|-)\s|\s*$|[?,])/iu.exec(e)||/\b([\p{L}][\p{L}.'’ -]{1,30}?)\s+to\s+[\p{L}][\p{L} .'-]{1,30}?\s+(?:flights?|fares?|airfare|tickets?)\b/iu.exec(e);return r?z(r[1].replace(/^(?:cheap(?:est)?|best|find|flights?|fly(?:ing)?|airfares?)\s+/i,"").replace(/^(?:flights?|fly(?:ing)?)\s+/i,"")):""},to:e=>{const t=K.exec(e);if(t)return t[2];const r=/\bto\s+([\p{L}][\p{L}.'’ -]{1,40})/iu.exec(e.replace(/\bhow much\b/i,""));return r?z(r[1]):""},when:e=>(N.exec(e)?.[0]||"").trim(),who:e=>/\b(\d+|one|two|three|four|five|six|seven|eight)\s+(?:adults?|people|persons|passengers|travell?ers|guests|of us)\b|\bfamily of (\d+)\b|\b(solo|couple)\b/i.exec(e)?.[0]||"",budget:e=>/\b(?:under|below|less than|max(?:imum)?|up to|within|no more than|<)\s*(?:[$€£]\s?)?\d[\d,.]*\s?(?:k|usd|eur|gbp|dollars|euros|pounds)?(?:\s*(?:\/|per|a)\s*(?:mo(?:nth)?|yr|year|night))?\b/i.exec(e)?.[0]||"",kind:e=>(/\b(auto|car|vehicle|motorcycle|homeowners?|home|house|renters?|condo|landlord|term life|whole life|life|health|medical|dental|vision|pet|dog|cat|travel|boat|umbrella|business)\b/i.exec(e)?.[1]||"").toLowerCase()},B=Object.freeze([{id:"insurance",label:"insurance",match:/\binsur(?:ance|er|ers)\b|\b(?:premiums?|coverage) (?:quotes?|rates?|prices?)\b/i,terms:["insurance","quote","rate","premium","coverage"],subject:"{kind?} insurance",queries:["{kind?} insurance quotes {where?}","cheapest {kind?} insurance {where?} {year}","{kind?} insurance rates compared {year}"],slots:[{id:"kind",label:"what to insure (car, home, renters, life, health, pet, travel…)",required:!0},{id:"where",label:"ZIP code / postcode or state",required:!0}],forms:!0},{id:"flight",label:"flights",match:/\b(?:flights?|airfares?|air ?fares?|plane tickets?|airline tickets?|fly(?:ing)? (?:to|from|out)|nonstop to)\b/i,terms:["flight","fare","airline","round","trip"],subject:"flights",queries:["cheap flights {from} to {to} {when?}","{from} to {to} flight deals","{from} {to} airfare {when?} {year}","cheap flight deals {year}","best time to book flights {year}"],slots:[{id:"from",label:"departure city or airport",required:!0},{id:"to",label:"destination",required:!0},{id:"when",label:"travel dates",required:!0},{id:"who",label:"number of travellers",required:!1}],forms:!0},{id:"hotel",label:"hotels",match:/\b(?:hotels?|motels?|resorts?|accommodation|lodging|places? to stay|vacation rentals?|airbnb|b&b)\b/i,terms:["hotel","night","room","stay"],subject:"hotels",queries:["best hotel deals {where} {when?}","cheap hotels {where} {when?}","{where} hotels price per night {year}","hotel deals {year}"],slots:[{id:"where",label:"city or area",required:!0},{id:"when",label:"dates",required:!0},{id:"who",label:"number of guests",required:!1}],forms:!0},{id:"car-rental",label:"car rental",match:/\b(?:car rentals?|rental cars?|rent a car|hire car|car hire)\b/i,terms:["rental","car","day"],subject:"car rental",queries:["cheap car rental {where} {when?}","car rental deals {where} {year}","car rental deals {year}"],slots:[{id:"where",label:"pick-up city or airport",required:!0},{id:"when",label:"dates",required:!0}],forms:!0},{id:"plan",label:"plans",match:/\b(?:internet|broadband|fib(?:er|re)|wi-?fi|mobile|cell(?:ular)?|phone|sim|electric(?:ity)?|energy|power|gas|streaming|vpn|cloud storage)\s+(?:plans?|providers?|deals?|services?|bills?|tariffs?|rates?|packages?)\b/i,terms:["plan","month","price"],queries:["best {subject} {where?} {year}","cheapest {subject} {where?}","{subject} prices compared {year}"],slots:[{id:"where",label:"ZIP code / city",required:!1},{id:"budget",label:"budget",required:!1}],forms:!1},{id:"product",label:"products",match:null,terms:["price","review"],queries:["best {subject} {budget?} {year}","{subject} price","{subject} deals {budget?}"],slots:[{id:"budget",label:"budget",required:!1}],forms:!1}]),I=e=>B.find(t=>t.id===e)||B[B.length-1],Q=/\b(?:cheapest|cheaper|lowest (?:price|fare|rate|cost)s?|affordable|deals?|discounts?|coupons?|promo codes?|on sale|bargains?|prices?|pricing|fares?|(?:get|want|need|free|instant) (?:a |an |my )?quotes?|quotes? (?:for|on)|how much (?:is|are|does|do|would|will|for|to)\b(?!\s+(?:time|longer|more|of my|of the (?:meeting|page|doc)))[^?]*\b(?:cost|costs|charge|pay|price)|how much (?:is|are) (?:a|an|the)? ?(?:flight|ticket|hotel|room|night)|cost of (?:a|an|the)?)\b/i,fe=/\b(?:best|top[- ]rated|compare|comparison|vs\.?|versus|recommend(?:ation)?s? for|worth buying|quotes?|where (?:can i|to|should i) (?:buy|get|find|book|rent)|save money on|rates?)\b/i,ge=/\b(?:buy|buying|purchase|shop(?:ping)?|order|book(?:ing)?|rent(?:al|ing)?|subscribe|subscription|plans?|insurance|flights?|hotels?|tickets?|deals?|prices?|costs?|rates?|fares?|movers?|moving company|contractors?|plumbers?|roofers?|repair (?:shop|service)s?|installation|providers?|under\s*[$€£]?\s?\d)\b|[$€£]\s?\d/i,me=/\bbest\s+(?!way|ways|practice|practices|time|approach|method|answer|thing|things|idea|ideas|advice|place to (?:learn|start)|book(?!ing))[\p{L}\d][\p{L}\d+-]*(?:\s+[\p{L}\d][\p{L}\d+-]*){0,3}\s+(?:for|under|below|to buy|in 20\d\d|of 20\d\d)\b/iu,be=/\b(?:stocks?|shares?|share price|ticker|market cap|dividend|crypto(?:currency)?|bitcoin|ethereum|exchange rate)\b|\b(?:my|our) (?:notes?|meetings?|chats?|calendar|emails?|inbox|files?|docs?|documents?|history|library)\b|\b(?:this|the) (?:page|tab|doc(?:ument)?|file|repo(?:sitory)?|code(?:base)?|pr|diff|function|spreadsheet)\b|\b(?:function|exception|stack ?trace|npm|pip|python|javascript|typescript|regex|sql|compile|git|docker|kubernetes|api key|endpoint)\b/i,G=/^\s*(?:(?:hey|hi|ok(?:ay)?|so|please|pls|can you|could you|would you|will you|help me|i need(?: to)?|i want(?: to)?|i'?m looking for|i am looking for|look(?:ing)? for|find(?: me)?|get(?: me)?|show(?: me)?|search(?: for)?|look up|tell me|give me|what(?:'s| is| are)|which(?: is| are)?|where(?:'s| is| are| can i (?:buy|get|find|book))?|who (?:has|offers)|how much (?:is|are|does|do|for)|how much)\s+)+/i,F=/\s+(?:for me|for us|near me|right now|now|today|online|please|pls|this year|in 20\d\d)\s*$|[?!.]+$/i,we=/\b(?:the|a|an|best|cheapest|cheaper|cheap|lowest|affordable|good|great|top[- ]rated|top|most|really|deals?|discounts?|coupons?|bargains?|quotes?|prices?|pricing|costs?|rates?|fares?|offers?|options?|compare|comparison|cost|to buy|on sale)\b/gi;function ye(e,t){let r=String(e||"").replace(G,"").replace(F,"").replace(F,"");return r=r.replace(N," ").replace(/\b(?:from|to|in|near|around|under|below|for|with|between)\s+.*$/i,o=>t.id==="product"||t.id==="plan"?o.replace(/\b(?:in|near|around|from|to)\s+.*$/i,""):""),r=r.replace(D.budget(r)||"\0"," ").replace(we," ").replace(/\b(?:does|do|is|are|a|an|it|cost|costs|20\d\d|i|can|buy|get|where)\b/gi," ").replace(/\s+/g," ").trim(),r.length>=2?r:t.label}function V(e,t){let r=!0;const o=e.replace(/\{(\w+)(\?)?\}/g,(a,c,s)=>(!t[c]&&!s&&(r=!1),t[c]||""));return r?o.replace(/\s+/g," ").trim():""}function $e(e){const t=String(e||"").trim(),r=t.split(/(?<=[.!?])\s+(?=\S)/).map(a=>a.trim()).filter(Boolean),o=r.filter(a=>/\?$/.test(a));return r.length>1&&o.length&&o.length<r.length?o.join(" "):t}function _e(e,{previous:t=null,now:r=Date.now()}={}){const o=String(e||"").trim();if(!o||o.length>400)return null;const a=o.split(/\s+/).length,c=t?.kind==="research"&&t.research?.domain?t.research:null;let s=B.find(p=>p.match&&p.match.test(o))||null;const h=s?s.slots.filter(p=>D[p.id]?.(o)).length:0,d=$e(o),u=!be.test(o)&&a>=2&&(Q.test(d)||fe.test(d)&&(s||ge.test(d))||me.test(d)||s&&(/\b(?:find|search|look|book|get|need)\b/i.test(d)||d===o&&h>=2));if(!u&&c&&a<=14&&(!s||s.id===c.domain)){const p=I(c.domain),l=Object.fromEntries(p.slots.map(k=>[k.id,D[k.id]?.(o)||""]).filter(([,k])=>k));return Object.keys(l).length?J(`${c.question} ${o}`,p,{...c.slots,...l},r,!0,p.subject?"":c.subject):null}if(!u)return null;s||=I("product");const f=Object.fromEntries(s.slots.map(p=>[p.id,D[p.id]?.(o)||""]).filter(([,p])=>p));return J(o,s,f,r,!1)}function J(e,t,r,o,a,c=""){const s=String(new Date(o).getFullYear()),h=c||(t.subject?V(t.subject,r):ye(e,t)),d={...r,subject:h,year:s},u=t.queries.map(l=>V(l,d)).filter(Boolean),f=a?"":e.replace(G,"").replace(F,"").replace(/^(?:a|an|the)\s+/i,"").trim(),p=(f?re(f,{extra:u,max:P.queries*2}):[...new Set(u)]).filter(l=>l.split(/\s+/).length>=2).slice(0,P.queries);return{question:e,domain:t.id,subject:h,slots:r,missing:t.slots.filter(l=>l.required&&!r[l.id]).map(l=>({id:l.id,label:l.label})),queries:p,forms:t.forms,followUp:a}}function ke(e,t=[],{now:r=Date.now()}={}){const o=String(new Date(r).getFullYear()),a=I(e.domain),c=a.slots.map(f=>e.slots?.[f.id]).filter(Boolean).join(" "),s=e.subject,h=[`${s} ${c} price ${o}`,a.forms?`${s} ${c} average cost`:`${s} ${c} cost`,`${s} ${c} comparison`,`${s} ${c}`],d=new Set(t.map(f=>f.toLowerCase().replace(/\s+/g," ").trim())),u=[];for(const f of h){const p=f.replace(/\s+/g," ").trim();p.split(/\s+/).length>=2&&!d.has(p.toLowerCase())&&!u.includes(p)&&u.push(p)}return u.slice(0,3)}function xe(e){if(e&&typeof e=="object"&&Array.isArray(e.results))return{query:e.query||"",engines:e.engines||[],results:e.results.filter(c=>c?.url)};const t=typeof e=="string"?e:typeof e?.text=="string"?e.text:"",r=/^Web search results for "([^"]*)" \(engines: ([^)]*)\)/m.exec(t),o=t.indexOf("Result details:");if(!r||o<0)return{query:r?.[1]||"",engines:[],results:[]};const a=[];for(const c of t.slice(o).split(/\n+---\n+(?=### \[\d+\])/)){const s=/### \[(\d+)\] ([^\n]*)\n<([^>\s]+)>\n\n?([\s\S]*)$/.exec(c);s&&a.push({rank:Number(s[1]),title:s[2].trim(),url:s[3],text:s[4].trim()})}return{query:r[1],engines:r[2].split(/,\s*/).filter(Boolean),results:a}}const X=/^(?:utm_\w+|gclid|fbclid|msclkid|mc_[a-z]+|ref|ref_src|source|campaign|affiliate|aff_id|clickid|irclickid|_ga)$/i;function qe(e){try{const t=new URL(e);for(const r of[...t.searchParams.keys()])X.test(r)&&t.searchParams.delete(r);return t.hash="",t.toString()}catch{return String(e||"")}}function ve(e){try{const t=new URL(e),o=[...t.searchParams.entries()].filter(([a])=>!X.test(a)).sort(([a],[c])=>a.localeCompare(c)).map(([a,c])=>`${a}=${c}`).join("&");return`${t.hostname.replace(/^www\./,"").toLowerCase()}${t.pathname.replace(/\/+$/,"")||"/"}${o?`?${o}`:""}`}catch{return String(e||"")}}function je(e,t=P.passageChars){const r=[];let o="";const a=()=>{const c=o.trim();c.length>=40&&r.push(c),o=""};for(const c of String(e||"").split(/\n\s*\n/)){const s=c.replace(/[ \t]+/g," ").trim();if(s)if(s.length>t){a();let h="";for(const d of s.split(/(?<=[.!?])\s+/))h&&h.length+d.length+1>t&&(o=h,a(),h=""),h=h?`${h} ${d}`:d.slice(0,t);o=h,a()}else o.length+s.length+2>t?(a(),o=s):o=o?`${o}
2
+ ${s}`:s}return a(),r}async function ee(e,t,r,o){const a=new Array(e.length);let c=0;const s=Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;c<e.length;){const h=c++;try{a[h]=await r(e[h],h)}catch{a[h]=null}}});return await(o?Promise.race([Promise.all(s),o]):Promise.all(s)),a}async function Se({ask:e,search:t,read:r=null,rerank:o=null,now:a=()=>Date.now(),until:c=null,limits:s={},onProgress:h=()=>{}}={}){if(!e||typeof t!="function")throw new Error("webResearch: ask and search required");const d={...P,...s},u=a(),f=()=>a()-u>d.ms;let p=!1;const l=c?c.then(()=>{p=!0}):null,k=I(e.domain),q=[],A=[],x=new Map,O=new Set;let v=0,i=null;const g=(S,L)=>{try{h({phase:S,label:L,searches:q.length,pages:x.size,offers:i?.offerCount||0})}catch{}};let b=e.queries.slice(0,d.queries);for(let S=1;S<=d.rounds&&b.length;S++){g("search",`Searching: ${b.map($=>`“${$}”`).join(", ")}`);const L=await ee(b,d.parallel,async $=>xe(await t($)),l);if(b.forEach(($,n)=>{q.push($);const m=L[n];if(!m?.results?.length){v+=1;return}m.engines.forEach(y=>O.add(y));const w=[];m.results.forEach(y=>{const R=ve(y.url);w.push(R);const T=x.get(R),H=String(y.text||y.snippet||"");T?(T.foundBy.push($),H.length>T.text.length&&(T.text=H)):x.set(R,{key:R,url:qe(y.url),title:y.title||y.url,host:le(y.url),text:H,foundBy:[$]})}),A.push(w)}),r&&!p&&!f()){const $=te(A,x,d).filter(n=>n.text.length<400).slice(0,d.read);if($.length){g("read",`Reading ${$.length} page${$.length===1?"":"s"}`);const n=await ee($,d.parallel,m=>r(m.url),l);$.forEach((m,w)=>{const y=n[w],R=typeof y=="string"?y:y?.text;R&&R.length>m.text.length&&(m.text=String(R),y?.title&&(m.title=y.title))})}}if(i=await se({ask:e,d:k,lists:A,pages:x,L:d,rerank:o}),g("decide",Ee(i)),i.enough||p||f()||S===d.rounds)break;b=ke(e,q,{now:u})}i||=await se({ask:e,d:k,lists:A,pages:x,L:d,rerank:null});const E={searches:q.length,failed:v,pages:x.size,sites:new Set([...x.values()].map(S=>S.host)).size,engines:[...O],ms:Math.max(0,a()-u)},j={ask:e,queries:q,...i,stats:E};return{...j,text:Ae(j,d)}}function te(e,t,r){const o=new Map,a=[];for(const{id:c}of W(e)){const s=t.get(c);if(!s?.host)continue;const h=o.get(s.host)||0;if(!(h>=r.perHost)&&(o.set(s.host,h+1),a.push(s),a.length>=r.pages))break}return a}async function se({ask:e,d:t,lists:r,pages:o,L:a,rerank:c}){const s=te(r,o,a),h=new Map(s.map((n,m)=>[n.key,m])),d=[e.subject,...Object.values(e.slots||{}),...t.terms],u=t.id!=="product"||Q.test(e.question)||!!e.slots?.budget||/\b(?:cheap|costs?|deals?|quotes?|rates?)\b|[$€£]/i.test(e.question),f=[];for(const n of s)je(n.text,a.passageChars).forEach((m,w)=>f.push({id:`${n.key}#${w}`,key:n.key,url:n.url,host:n.host,title:n.title,text:m}));const p=`${d.join(" ")}${u?" price cost per month":""}`,l=f.length?ne(oe(f),p).map(n=>n.id):[],k=[...f].sort((n,m)=>h.get(n.key)-h.get(m.key)).map(n=>n.id),q=u?f.filter(n=>/[$€£]\s?\d|\d\s?(?:€|£|USD|EUR|GBP)\b/.test(n.text)).map(n=>n.id):[],A=[l,k,...q.length?[q]:[]];if(typeof c=="function"&&l.length){const n=l.slice(0,40).map(m=>f.find(w=>w.id===m));try{const m=await c(e.question,n.map(w=>w.text));Array.isArray(m)&&m.length===n.length&&A.push(n.map((w,y)=>({id:w.id,s:Number(m[y])||0})).sort((w,y)=>y.s-w.s).map(w=>w.id))}catch{}}const x=new Set(l),O=new Map(f.map(n=>[n.id,n])),v=new Map,i=[];for(const{id:n}of W(A)){if(!x.has(n))continue;const m=O.get(n),w=v.get(m.host)||0;if(!(w>=2)&&(v.set(m.host,w+1),i.push(m),i.length>=a.passages))break}const g=u?ie(s.flatMap(n=>ae(n.text,{url:n.url,title:n.title,terms:d,max:a.offers}))):{basis:"",currency:"",ranked:[],floors:[],other:[],averages:[]},b=[];for(const n of s){const m=t.forms||/\bquote\b/i.test(e.question)?ce(n.text):"";if(m&&!b.some(w=>w.host===n.host)&&b.push({url:n.url,title:n.title,host:n.host,cta:m}),b.length>=a.forms)break}const E=g.ranked.length+g.floors.length,j=new Set([...g.ranked,...g.floors].map(n=>n.host)).size,S=g.ranked.some(n=>n.seenOn>=2),L=new Set(i.map(n=>n.host)).size,$=u?E>=3&&j>=2||S&&g.ranked.length>=2:i.length>=4&&L>=3;return{pages:s,passages:i,offers:g,forms:b,enough:$,offerCount:E,wantPrices:u}}function Ee(e){const t=[`${e.pages.length} page${e.pages.length===1?"":"s"}`];return e.wantPrices&&t.push(`${e.offerCount} price${e.offerCount===1?"":"s"}`),e.forms.length&&t.push(`${e.forms.length} quote form${e.forms.length===1?"":"s"}`),t.join(" · ")}const _=(e,t)=>{const r=String(e||"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}…`:r};function Ae(e,t={}){const r={...P,...t};if(!e?.pages?.length)return"";const o=new Map,a=i=>(o.has(i.url)||o.set(i.url,{n:o.size+1,title:i.title||i.host||i.url,url:i.url}),o.get(i.url).n),c=i=>`[${a(i)}](${U(i.url)})`,{offers:s,forms:h,passages:d,ask:u,stats:f}=e,p=I(u.domain),l=[],k=`${f.searches} search${f.searches===1?"":"es"}, ${f.pages} page${f.pages===1?"":"s"} from ${f.sites} site${f.sites===1?"":"s"}, ${(f.ms/1e3).toFixed(1)} s`;e.wantPrices&&u.browse?l.push(`(FIRST PASS from web search for the question below — ${k}. These are listing and article pages, not live quotes. A price answers the question only when its page says it is for THIS request (the route or item, and the dates asked); a 12-month low, an average or a deal advertised for other dates does not. When nothing below is that, get it live before answering: open the booking or comparison site in your own tab (page open_tab), enter the request, read the results, and compare at least two sites. Cite with the markdown links given and with the pages you open. Do not repeat these searches.)`):l.push(`(ALREADY RESEARCHED on the web for the question below — ${k}. Answer from this and cite with the markdown links given. `+(e.wantPrices?'State ONLY prices listed under "Prices found" — each was read on the linked page — and call a "from" price an advertised minimum, not a quote. ':"")+"Do not repeat these searches; search again only for something this does not cover.)"),l.push(""),l.push(`Question: ${_(u.question,200)}`);const q=p.slots.filter(i=>u.slots?.[i.id]).map(i=>`${i.id} = ${u.slots[i.id]}`);if(l.push(`Looking for: ${u.subject}${p.id!=="product"?` (${p.label})`:""}${q.length?` · known: ${q.join(" · ")}`:""}`),u.missing?.length&&u.browse?l.push(`Not given: ${u.missing.map(i=>i.label).join("; ")}. Use what the conversation, the user's memory or the pages below point to (a page searched from a city says where they are), say it is an assumption, and go on — ask only when nothing points anywhere. A vague time ("the holidays") is the usual span; say which dates you took.`):u.missing?.length&&l.push(`Missing for a personalised price: ${u.missing.map(i=>i.label).join("; ")}. Ask the user for these before filling any quote form — say what the prices below are based on meanwhile.`),e.wantPrices){l.push("");const i=s.basis==="month"?"per month":M(s.basis);if(s.ranked.length){l.push(`Prices found (cheapest first, ${i}${s.currency?`, ${s.currency}`:""}):`);const g=[];for(const b of s.ranked){const E=g.find(j=>j.o.currency===b.currency&&Math.round(j.o.value*100)===Math.round(b.value*100));E?E.also.some(j=>j.url===b.url)||E.also.push(b):g.push({o:b,also:[]})}g.slice(0,r.offers).forEach(({o:b,also:E},j)=>{const S=[b,...E].map(c).filter((L,$,n)=>n.indexOf(L)===$).join(" ");l.push(`${j+1}. ${Z(b.value,b.currency,s.basis)}${b.converted?` (${b.raw} ${M(b.basis)})`:""} — “${_(b.quote,160)}” ${S}${b.seenOn>1?` · stated by ${b.seenOn} sites`:""}`)})}else l.push(u.browse?"Prices found: none stated plainly on the pages read — do not invent one; get them live, as above.":"Prices found: none stated plainly on the pages read — do not invent one; say so and offer to get a quote.");s.floors.length&&l.push(`Advertised minimums ("from" — not a quote for this person): ${s.floors.slice(0,4).map(g=>`${Z(g.value,g.currency,s.basis)} ${c(g)}`).join(" · ")}`),s.other.length&&l.push(`On another basis or currency (not comparable with the list above): ${s.other.slice(0,4).map(g=>`${g.raw} ${M(g.basis)} ${c(g)}`).join(" · ")}`),s.averages.length&&l.push(`Averages (context, not offers): ${s.averages.slice(0,3).map(g=>`${g.raw} ${M(g.basis)} — “${_(g.quote,100)}” ${c(g)}`).join(" · ")}`)}if(h.length){l.push(""),l.push("Quote forms (an exact price needs the user's details — you can fill these in the user's browser with the page tools, asking them for anything missing; NEVER press a submit/continue/pay button without the user's OK):");for(const i of h)l.push(`- ${i.host}: “${i.cta}” ${c(i)}`)}const A=d.map(i=>`[${a(i)}] ${i.title?`${_(i.title,80)} — `:""}${i.text}`);l.push(""),l.push("Sources:");for(const i of o.values())l.push(`[${i.n}] [${_(i.title,90)}](${U(i.url)})`);let x=l.join(`
3
+ `);const O=r.briefChars-x.length-200;let v="";for(const i of A){if(v.length+i.length+2>O)break;v+=`${v?`
4
4
 
5
- `:""}${a}`}return v&&(k+=`
5
+ `:""}${i}`}return v&&(x+=`
6
6
 
7
- ${ue(v,{source:"web search results"})}`),k}function Ae(e,t){return e?.tool==="find"?{tool:"find",input:{action:"web_search",args:{query:t}}}:{tool:e?.tool||"web_search",input:{query:t}}}async function _e(e,{execute:t,read:r=null,rerank:o=null,now:l=()=>Date.now(),until:i=null,onProgress:s=()=>{},limits:d={}}={}){const p=async u=>{const b=Ae(e,u),c=await t(b.tool,b.input,{prefetched:!0,research:!0}),x=typeof c=="string"?c:c?.text;if(!x||/^(?:error\b|\w+ failed\b|\{"error")/i.test(x))throw new Error("search failed");return x},h=await je({ask:e.research,search:p,read:r,rerank:o,now:l,until:i,limits:d,onProgress:s});return{text:h.text,result:h}}export{P as WEB_RESEARCH_LIMITS,B as WEB_TASK_DOMAINS,xe as cleanUrl,qe as pageKey,ke as parseSearchText,ve as passagesOf,$e as refineQueries,Ie as researchAsk,Ee as researchBrief,Ae as researchCall,_e as runResearch,je as webResearch};
7
+ ${ue(v,{source:"web search results"})}`),x}function Re(e,t){return e?.tool==="find"?{tool:"find",input:{action:"web_search",args:{query:t}}}:{tool:e?.tool||"web_search",input:{query:t}}}async function Te(e,{execute:t,read:r=null,rerank:o=null,now:a=()=>Date.now(),until:c=null,onProgress:s=()=>{},limits:h={}}={}){const d=async f=>{const p=Re(e,f),l=await t(p.tool,p.input,{prefetched:!0,research:!0}),k=typeof l=="string"?l:l?.text;if(!k||/^(?:error\b|\w+ failed\b|\{"error")/i.test(k))throw new Error("search failed");return k},u=await Se({ask:e.research,search:d,read:r,rerank:o,now:a,until:c,limits:h,onProgress:s});return{text:u.text,result:u}}export{P as WEB_RESEARCH_LIMITS,B as WEB_TASK_DOMAINS,$e as askingPart,qe as cleanUrl,ve as pageKey,xe as parseSearchText,je as passagesOf,ke as refineQueries,_e as researchAsk,Ae as researchBrief,Re as researchCall,Te as runResearch,Se as webResearch};