@chatpanel/events 0.400.0 → 0.425.2

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.
@@ -0,0 +1 @@
1
+ const r="RESEARCH OR MULTI-STEP WORK: keep a task list, work through every item, check more than one source, then say what is still open.",a=new Set(["bridge"]);function s(e){return a.has(String(e?.kind||""))}function h(e){const t=String(e?.kind||"");return!(t==="webllm"||t==="bridge"&&(e?.bridgeAgent||"claude")==="antigravity")}function l(e,t=[]){if(!s(e))return"";const o=[...new Set((t||[]).filter(n=>typeof n=="string"&&n.trim()))].slice(0,24);return["YOUR OWN TOOLS STILL APPLY. The Chap tools above are authoritative for what only","Chap can reach — this browser tab, the user's Chap notes/chats/meetings, and the","MCP servers they connected THERE. They are not a restriction on the rest of your toolset.",`For anything else — ${o.length?`your own MCP connectors — you have ${o.join(", ")} configured — plus your filesystem and your shell`:"your own MCP connectors (Slack, Jira, GitHub, Confluence, calendar, email), your filesystem, your shell"} — use them normally.`,"FINISH THE JOB RATHER THAN HANDING IT BACK. If the answer points somewhere you can reach —","a thread, a ticket, a repo, a document — go and read it, then answer. Telling the user to","go and look something up themselves is a last resort, for when you genuinely have no tool","that reaches it; say which tool you lack when that happens, rather than declining vaguely.",r].join(" ")}export{r as RESEARCH_RULE,h as agentTakesTools,s as isRelayedAgent,l as ownToolsSystem};
package/agent-thread.js CHANGED
@@ -1,5 +1,5 @@
1
- import{EventError as p}from"./event.js";const y=(t,r)=>{if(!t)throw new p("SHAPE",r)},m=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function I(t){if(!t||typeof t!="object")return null;const r=String(t.id??"").trim().replace(/^chat:/,"");if(!m.test(r))return null;const n=String(t.title??"").replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim().slice(0,120);return{id:r,...n?{title:n}:{}}}function E(t){return t?[`chat:${t}`]:[]}function x(t=[]){const n=(Array.isArray(t)?t:[]).slice(0,-1);return{users:n.filter(e=>e?.role==="user").map(e=>l(e.content).trim()),answers:n.filter(e=>e?.role==="assistant").length}}function A(t=[],{answered:r=!0}={}){const n=Array.isArray(t)?t:[];return{users:n.filter(e=>e?.role==="user").map(e=>l(e.content).trim()),answers:n.filter(e=>e?.role==="assistant").length+(r?1:0)}}const g=8;function h(t,r=g){const n=String(t??"").trim(),e=[n];let s=n;for(let i=0;i<r;i++){const o=s.lastIndexOf(`
1
+ import{EventError as g}from"./event.js";const A=(t,n)=>{if(!t)throw new g("SHAPE",n)},h=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function b(t){if(!t||typeof t!="object")return null;const n=String(t.id??"").trim().replace(/^chat:/,"");if(!h.test(n))return null;const e=String(t.title??"").replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim().slice(0,120),r=Array.isArray(t.ids)&&t.ids.length<=m&&t.ids.every(i=>typeof i=="string"&&h.test(i))?t.ids.slice():null,s=typeof t.answerId=="string"&&h.test(t.answerId)?t.answerId:"";return{id:n,...e?{title:e}:{},...r?.length?{ids:r}:{},...s?{answerId:s}:{}}}const m=1e3;function p(t,n){const e=n?.ids;if(!Array.isArray(e)||!e.length)return null;const r=(Array.isArray(t)?t:[]).filter(s=>s?.role==="user"||s?.role==="assistant");return r.length===e.length?{turns:r,ids:e}:null}function D(t=[],n=null,{answered:e=!0,mark:r=s=>s}={}){const s=p(t,n);if(!s)return null;let i=s.turns.length-1;for(;i>=0&&s.turns[i].role!=="user";)i--;return i<0?null:{user:r(s.ids[i]),answer:e&&n.answerId?r(n.answerId):"",answered:!!e}}function P(t=[],n=null,e=null,{mark:r=s=>s}={}){const s=p(t,n);if(!s||!e?.user)return null;const i=a=>{for(let f=s.ids.length-1;f>=0;f--)if(r(s.ids[f])===a)return f;return-1};let l=-1,o=!1;const u=e.answer?i(e.answer):-1;if(u>=0&&s.turns[u].role==="assistant")l=u+1,o=!0;else{const a=i(e.user);if(a<0||s.turns[a].role!=="user")return null;l=a+1,e.answered&&!e.answer&&s.turns[l]?.role==="assistant"&&(l++,o=!0)}const d=s.turns.slice(l);return!d.length||d.at(-1).role!=="user"?null:{tail:d,answered:o}}function T(t){return t?[`chat:${t}`]:[]}function x(t=[]){const e=(Array.isArray(t)?t:[]).slice(0,-1);return{users:e.filter(r=>r?.role==="user").map(r=>c(r.content).trim()),answers:e.filter(r=>r?.role==="assistant").length}}function w(t=[],{answered:n=!0}={}){const e=Array.isArray(t)?t:[];return{users:e.filter(r=>r?.role==="user").map(r=>c(r.content).trim()),answers:e.filter(r=>r?.role==="assistant").length+(n?1:0)}}const I=8;function y(t,n=I){const e=String(t??"").trim(),r=[e];let s=e;for(let i=0;i<n;i++){const l=s.lastIndexOf(`
2
2
 
3
- `);if(o<0)break;s=s.slice(0,o).trim(),s&&e.push(s)}return[...new Set(e)]}function w(t,r){const n=String(r??"").trim();return h(t).includes(n)}function b(t=[],{answered:r=!0}={}){const n=A(t,{answered:r});return{users:n.users.slice(0,-1),answers:n.answers,last:h(n.users.at(-1)??"")}}function P(t=[]){const r=x(t);return{users:r.users.slice(0,-1),answers:r.answers,last:r.users.at(-1)??null}}function T(t=[],{n:r,answers:n}={}){const e=Array.isArray(t)?t:[];if(!Number.isInteger(r)||r<0||!Number.isInteger(n)||n<0)return null;const s=[];let i=0,o=-1;for(let f=0;f<e.length;f++){const c=e[f];if(c?.role==="user"){if(s.length===r){o=f;break}s.push(l(c.content).trim())}else c?.role==="assistant"&&i++}if(o<0)return null;const u=n-i;if(u!==0&&u!==1)return null;let a=o+1;if(u===1){for(;a<e.length&&e[a]?.role!=="assistant";){if(e[a]?.role==="user")return null;a++}if(a>=e.length)return null;a++}const d=e.slice(a);return d.at(-1)?.role!=="user"?null:{prefix:{users:s,answers:n},last:l(e[o].content).trim(),tail:d,answered:u===1}}function D(t=[],r=()=>!1,{answered:n=!0}={}){const e=Array.isArray(t)?t:[];for(let s=e.length-1;s>=0;s--){if(e[s]?.role!=="user"||!r(l(e[s].content).trim()))continue;let i=s+1;n&&e[i]?.role==="assistant"&&i++;const o=e.slice(i).filter(u=>u?.role==="user"||u?.role==="assistant");return o.at(-1)?.role==="user"&&o.pop(),o}return[]}function _(t=[],r=[]){let n=Array.isArray(t)?t:[];for(const e of Array.isArray(r)?r:[]){if(e?.role!=="user")continue;const s=n.findIndex(i=>i?.role==="user"&&w(l(i.content),l(e.content)));s>=0&&(n=[...n.slice(0,s),...n.slice(s+1)])}return n}function z(t=[]){const r=Array.isArray(t)?t:[],n=r.filter(e=>e?.role==="user").map(e=>l(e.content).trim());return{users:n.slice(0,-1),answers:r.filter(e=>e?.role==="assistant").length,last:h(n.at(-1)??"")}}function l(t){return typeof t=="string"?t:Array.isArray(t)?t.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
3
+ `);if(l<0)break;s=s.slice(0,l).trim(),s&&r.push(s)}return[...new Set(r)]}function S(t,n){const e=String(n??"").trim();return y(t).includes(e)}function _(t=[],{answered:n=!0}={}){const e=w(t,{answered:n});return{users:e.users.slice(0,-1),answers:e.answers,last:y(e.users.at(-1)??"")}}function v(t=[]){const n=x(t);return{users:n.users.slice(0,-1),answers:n.answers,last:n.users.at(-1)??null}}function z(t=[],{n,answers:e}={}){const r=Array.isArray(t)?t:[];if(!Number.isInteger(n)||n<0||!Number.isInteger(e)||e<0)return null;const s=[];let i=0,l=-1;for(let a=0;a<r.length;a++){const f=r[a];if(f?.role==="user"){if(s.length===n){l=a;break}s.push(c(f.content).trim())}else f?.role==="assistant"&&i++}if(l<0)return null;const o=e-i;if(o!==0&&o!==1)return null;let u=l+1;if(o===1){for(;u<r.length&&r[u]?.role!=="assistant";){if(r[u]?.role==="user")return null;u++}if(u>=r.length)return null;u++}const d=r.slice(u);return d.at(-1)?.role!=="user"?null:{prefix:{users:s,answers:e},last:c(r[l].content).trim(),tail:d,answered:o===1}}function N(t=[],n=()=>!1,{answered:e=!0}={}){const r=Array.isArray(t)?t:[];for(let s=r.length-1;s>=0;s--){if(r[s]?.role!=="user"||!n(c(r[s].content).trim()))continue;let i=s+1;e&&r[i]?.role==="assistant"&&i++;const l=r.slice(i).filter(o=>o?.role==="user"||o?.role==="assistant");return l.at(-1)?.role==="user"&&l.pop(),l}return[]}function O(t=[],n=[]){let e=Array.isArray(t)?t:[];for(const r of Array.isArray(n)?n:[]){if(r?.role!=="user")continue;const s=e.findIndex(i=>i?.role==="user"&&S(c(i.content),c(r.content)));s>=0&&(e=[...e.slice(0,s),...e.slice(s+1)])}return e}function j(t=[]){const n=Array.isArray(t)?t:[],e=n.filter(r=>r?.role==="user").map(r=>c(r.content).trim());return{users:e.slice(0,-1),answers:n.filter(r=>r?.role==="assistant").length,last:y(e.at(-1)??"")}}function c(t){return typeof t=="string"?t:Array.isArray(t)?t.map(n=>typeof n=="string"?n:n?.text||"").filter(Boolean).join(`
4
4
 
5
- `):String(t??"")}function N({link:t=null,digest:r="",cwd:n="",hasHistory:e=!1}={}){return y(typeof r=="string","threadPlan: digest must be a string"),!t||!t.sessionId?{mode:"start",sessionId:null,seed:!!e,why:"no session holds this thread yet"}:String(t.cwd||"")!==String(n||"")?{mode:"start",sessionId:null,seed:!!e,why:"the thread moved to another folder"}:!r||t.digest!==r?{mode:"start",sessionId:null,seed:!!e,why:"the history differs from what the session saw (edited or regenerated)"}:{mode:"resume",sessionId:String(t.sessionId),seed:!1,why:"the session has seen exactly this history"}}export{T as historyExtension,x as historyShape,P as historySplit,E as legacyThreadIds,A as nextShape,I as normalizeThread,_ as outsideBeyond,D as outsideTurns,z as seenOf,h as sentVariants,N as threadPlan,b as turnSeen,w as userTextMatches};
5
+ `):String(t??"")}function B({link:t=null,digest:n="",cwd:e="",hasHistory:r=!1}={}){return A(typeof n=="string","threadPlan: digest must be a string"),!t||!t.sessionId?{mode:"start",sessionId:null,seed:!!r,why:"no session holds this thread yet"}:String(t.cwd||"")!==String(e||"")?{mode:"start",sessionId:null,seed:!!r,why:"the thread moved to another folder"}:!n||t.digest!==n?{mode:"start",sessionId:null,seed:!!r,why:"the history differs from what the session saw (edited or regenerated)"}:{mode:"resume",sessionId:String(t.sessionId),seed:!1,why:"the session has seen exactly this history"}}export{z as historyExtension,x as historyShape,v as historySplit,P as idsExtension,D as idsSeen,T as legacyThreadIds,w as nextShape,b as normalizeThread,O as outsideBeyond,N as outsideTurns,j as seenOf,y as sentVariants,B as threadPlan,_ as turnSeen,S as userTextMatches};
@@ -1 +1 @@
1
- import{EventError as b}from"./event.js";const d=e=>!!e&&typeof e=="object"&&!Array.isArray(e),l=e=>typeof e=="number"&&Number.isFinite(e),a=e=>{throw new b("SHAPE",e)},y=e=>Math.min(1,Math.max(0,e));function x(e){const t={};for(const[o,n]of Object.entries(e.questions)){const r={type:n.type,instructions:n.instructions};n.type==="choice"?r.criteria=Object.fromEntries(n.options.map(s=>[s.value,s.describe||s.value])):n.type==="score"&&(r.criteria=n.options.map(s=>s.describe?`${s.value}: ${s.describe}`:s.value)),t[o]=r}return{state:e.state,...e.model?{model:e.model}:{},questions:t}}function k(e,t){d(e)&&d(e.answers)||a("systemone: answers {} missing");const o={};for(const[n,r]of Object.entries(t.questions)){const s=e.answers[n];d(s)||a(`systemone: no answer for ${n}`);const p=d(s.probabilities)?s.probabilities:{},f=l(s.confidence)?y(s.confidence):void 0;if(r.type==="choice"){const i=typeof s.choice=="string"?s.choice:a(`systemone: ${n}.choice missing`),m=r.options.map(c=>({value:c.value,p:y(l(p[c.value])?p[c.value]:0)}));o[n]={value:i,p:m.find(c=>c.value===i)?.p??0,options:m,...f!=null?{confidence:f}:{}}}else if(r.type==="score"){l(s.score)||a(`systemone: ${n}.score missing`);const i=r.options.map((c,u)=>({value:c.value,p:y(l(p[String(u)])?p[String(u)]:0)})),m=i.reduce((c,u)=>u.p>c.p?u:c,i[0]);o[n]={value:s.score,p:m.p,options:i,...f!=null?{confidence:f}:{}}}else{l(s.noul)||a(`systemone: ${n}.noul missing`);const i=y(s.noul);o[n]={value:i>=.5,p:i>=.5?i:1-i,options:[{value:!0,p:i},{value:!1,p:1-i}]}}}return{answers:o,...typeof e.model=="string"&&e.model?{model:e.model}:{}}}function O(e){return{query:e.query,texts:e.documents,raw_scores:!1,return_text:!1}}function _(e,t){Array.isArray(e)||a("tei: an array of { index, score } expected");const o=e.map(n=>d(n)&&Number.isInteger(n.index)&&l(n.score)?{index:n.index,relevance_score:n.score}:a("tei: a result needs index and score")).sort((n,r)=>r.relevance_score-n.relevance_score);return{results:t.top_n!=null?o.slice(0,t.top_n):o}}function j(e,t){d(e)&&Array.isArray(e.results)||a("rerank: results[] missing");const o=e.results.map(n=>d(n)&&Number.isInteger(n.index)&&l(n.relevance_score)?{index:n.index,relevance_score:n.relevance_score}:a("rerank: a result needs index and relevance_score")).sort((n,r)=>r.relevance_score-n.relevance_score);return{results:t.top_n!=null?o.slice(0,t.top_n):o,...typeof e.model=="string"&&e.model?{model:e.model}:{}}}function S(e){return d(e)&&d(e.answers)||a("decide: answers {} missing"),{answers:e.answers,...typeof e.model=="string"&&e.model?{model:e.model}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{}}}const v=Object.freeze({systemone:Object.freeze({id:"systemone",capability:"decide",route:"/v1/systemone",label:"TypeSafe System One (Jev · OpenDecision · Laya)",request:x,response:k}),tei:Object.freeze({id:"tei",capability:"rerank",route:"/rerank",label:"Text Embeddings Inference",request:O,response:_}),"rerank-standard":Object.freeze({id:"rerank-standard",capability:"rerank",route:"/v1/rerank",label:"Cohere / Jina rerank",request:e=>({...e,budgetMs:void 0}),response:j}),"decide-standard":Object.freeze({id:"decide-standard",capability:"decide",route:"/v1/decide",label:"ChatPanel decide",request:e=>({...e,budgetMs:void 0}),response:S})});function g(e){const t=v[e];if(!t)throw new b("SHAPE",`capability adapter ${JSON.stringify(e)} unknown (${Object.keys(v).join(", ")})`);return t}function A(e,t){const o=g(e),n=o.request(t);for(const r of Object.keys(n))n[r]===void 0&&delete n[r];return{route:o.route,body:n}}function $(e,t,o){return g(e).response(t,o)}export{v as ADAPTERS,A as adaptRequest,$ as adaptResponse,g as adapterFor};
1
+ import{EventError as b}from"./event.js";const d=e=>!!e&&typeof e=="object"&&!Array.isArray(e),l=e=>typeof e=="number"&&Number.isFinite(e),a=e=>{throw new b("SHAPE",e)},y=e=>Math.min(1,Math.max(0,e));function k(e){const t={};for(const[o,n]of Object.entries(e.questions)){const r={type:n.type,instructions:n.instructions};n.type==="choice"?r.criteria=Object.fromEntries(n.options.map(s=>[s.value,s.describe||s.value])):n.type==="score"&&(r.criteria=n.options.map(s=>s.describe?`${s.value}: ${s.describe}`:s.value)),t[o]=r}return{state:e.state,...e.model?{model:e.model}:{},questions:t}}function x(e,t){d(e)&&d(e.answers)||a("systemone: answers {} missing");const o={};for(const[n,r]of Object.entries(t.questions)){const s=e.answers[n];d(s)||a(`systemone: no answer for ${n}`);const p=d(s.probabilities)?s.probabilities:{},f=l(s.confidence)?y(s.confidence):void 0;if(r.type==="choice"){const i=typeof s.choice=="string"?s.choice:a(`systemone: ${n}.choice missing`),m=r.options.map(c=>({value:c.value,p:y(l(p[c.value])?p[c.value]:0)}));o[n]={value:i,p:m.find(c=>c.value===i)?.p??0,options:m,...f!=null?{confidence:f}:{}}}else if(r.type==="score"){l(s.score)||a(`systemone: ${n}.score missing`);const i=r.options.map((c,u)=>({value:c.value,p:y(l(p[String(u)])?p[String(u)]:0)})),m=i.reduce((c,u)=>u.p>c.p?u:c,i[0]);o[n]={value:s.score,p:m.p,options:i,...f!=null?{confidence:f}:{}}}else{l(s.noul)||a(`systemone: ${n}.noul missing`);const i=y(s.noul);o[n]={value:i>=.5,p:i>=.5?i:1-i,options:[{value:!0,p:i},{value:!1,p:1-i}]}}}return{answers:o,...typeof e.model=="string"&&e.model?{model:e.model}:{}}}function O(e){return{query:e.query,texts:e.documents,raw_scores:!1,return_text:!1}}function _(e,t){Array.isArray(e)||a("tei: an array of { index, score } expected");const o=e.map(n=>d(n)&&Number.isInteger(n.index)&&l(n.score)?{index:n.index,relevance_score:n.score}:a("tei: a result needs index and score")).sort((n,r)=>r.relevance_score-n.relevance_score);return{results:t.top_n!=null?o.slice(0,t.top_n):o}}function j(e,t){d(e)&&Array.isArray(e.results)||a("rerank: results[] missing");const o=e.results.map(n=>d(n)&&Number.isInteger(n.index)&&l(n.relevance_score)?{index:n.index,relevance_score:n.relevance_score}:a("rerank: a result needs index and relevance_score")).sort((n,r)=>r.relevance_score-n.relevance_score);return{results:t.top_n!=null?o.slice(0,t.top_n):o,...typeof e.model=="string"&&e.model?{model:e.model}:{}}}function S(e){return d(e)&&d(e.answers)||a("decide: answers {} missing"),{answers:e.answers,...typeof e.model=="string"&&e.model?{model:e.model}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{}}}const v=Object.freeze({systemone:Object.freeze({id:"systemone",capability:"decide",route:"/v1/systemone",label:"TypeSafe System One (Jev · OpenDecision · Laya)",request:k,response:x}),tei:Object.freeze({id:"tei",capability:"rerank",route:"/rerank",label:"Text Embeddings Inference",request:O,response:_}),"rerank-standard":Object.freeze({id:"rerank-standard",capability:"rerank",route:"/v1/rerank",label:"Cohere / Jina rerank",request:e=>({...e,budgetMs:void 0,wake:void 0}),response:j}),"decide-standard":Object.freeze({id:"decide-standard",capability:"decide",route:"/v1/decide",label:"ChatPanel decide",request:e=>({...e,budgetMs:void 0,wake:void 0}),response:S})});function g(e){const t=v[e];if(!t)throw new b("SHAPE",`capability adapter ${JSON.stringify(e)} unknown (${Object.keys(v).join(", ")})`);return t}function A(e,t){const o=g(e),n=o.request(t);for(const r of Object.keys(n))n[r]===void 0&&delete n[r];return{route:o.route,body:n}}function $(e,t,o){return g(e).response(t,o)}export{v as ADAPTERS,A as adaptRequest,$ as adaptResponse,g as adapterFor};
@@ -0,0 +1 @@
1
+ const u=Object.freeze({chat:Object.freeze(["first","route","merge"]),embed:Object.freeze(["first","route"]),rerank:Object.freeze(["first","route","merge"]),decide:Object.freeze(["first","route","merge"]),stt:Object.freeze(["first","route"]),tts:Object.freeze(["first","route"]),detect:Object.freeze(["merge","first"]),search:Object.freeze(["first","route","merge"]),read:Object.freeze(["first"]),extract:Object.freeze(["first"]),s2s:Object.freeze(["first"])}),a=Object.freeze(["first","route","merge"]),v=16,d=e=>!!e&&typeof e=="object"&&!Array.isArray(e),p=e=>(u[e]||a)[0],m=e=>d(e)&&Array.isArray(e.providers);function n(e,r){return d(e)?m(e)?{mode:(u[r]||a).includes(e.mode)?e.mode:p(r),providers:e.providers.filter(d)}:{mode:p(r),providers:[e]}:{mode:p(r),providers:[]}}function x(e,r){return n(e,r).providers[0]||null}function c(e,r){const t=(e?.providers||[]).filter(d);if(!t.length)return null;const s=(u[r]||a).includes(e.mode)?e.mode:p(r);return t.length===1&&s===p(r)?t[0]:{mode:s,providers:t}}function O(e,r,t,{match:s=null,at:i="start"}={}){const o=n(e,r),f=s?o.providers.findIndex(s):-1,l=o.providers.slice();return f>=0?l[f]=t:i==="end"?l.push(t):l.unshift(t),c({mode:o.mode,providers:l},r)}function $(e,r,t){const s=n(e,r);return c({mode:s.mode,providers:s.providers.filter(i=>!t(i))},r)}function j(e,r){if(!m(r))return[];const t=[],s=u[e]||a;r.mode!=null&&!s.includes(r.mode)&&t.push(`capabilities.${e}.mode must be one of ${s.join(", ")}`),r.providers.length>v&&t.push(`capabilities.${e} holds at most ${v} providers`),r.providers.some(o=>!d(o))&&t.push(`capabilities.${e}.providers: each is an object`);const i=r.providers.filter(d).map(o=>o.id).filter(o=>o!=null);return i.some(o=>typeof o!="string"||!/^[A-Za-z0-9_.:-]{1,64}$/.test(o))&&t.push(`capabilities.${e}.providers[].id is a short name (letters, digits, _ . : -)`),new Set(i).size!==i.length&&t.push(`capabilities.${e}.providers: two providers share an id`),t}const h=1,g=e=>!!e&&typeof e=="object"&&e.provider!=="embedded"&&e.provider!=="none"&&!e.service&&(e.provider==="remote"||e.kind==="remote"||typeof e.url=="string"&&!!e.url);function b(e,r){return n(e,r).providers.filter(g).length}function w(e,r,t,{pro:s=!1}={}){if(s)return"";const i=b(r,e),o=b(t,e);return o>h&&o>i?`More than ${h} provider of your own for ${e} needs Pro — Free uses the built-in ones and one of your own per job.`:""}function z(e,r,t,s){const i=n(e,r),o=i.providers.slice();if(t<0||t>=o.length)return c(i,r);const[f]=o.splice(t,1);return o.splice(Math.max(0,Math.min(o.length,s)),0,f),c({mode:i.mode,providers:o},r)}function P(e,r,t){const s=n(e,r);return c({mode:s.mode,providers:s.providers.filter((i,o)=>o!==t)},r)}function y(e,r,t){const s=new Set(n(e,r).providers.map(o=>o.id).filter(Boolean)),i=String(t||"provider").toLowerCase().replace(/[^a-z0-9_.:-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"provider";if(!s.has(i))return i;for(let o=2;;o++)if(!s.has(`${i}-${o}`))return`${i}-${o}`}function _(e,r){const t=n(e,r);return{mode:t.mode,providers:t.providers}}function E(e){let r;try{r=new URL(e)}catch{return"server"}const t=r.hostname.replace(/^\[|\]$/g,"");if(/^(localhost|127\.\d+\.\d+\.\d+|::1|\d+\.\d+\.\d+\.\d+)$/.test(t)||t.includes(":"))return`local${r.port?`-${r.port}`:""}`;const s=t.split(".").filter(i=>!["api","www"].includes(i));return s.length>1?s[s.length-2]:s[0]||"server"}export{h as FREE_OWN_PROVIDERS,u as JOB_MODES,v as MAX_PROVIDERS,a as PROVIDER_MODES,n as capabilityList,p as defaultMode,w as freeLimitProblem,g as isOwnProvider,m as isProviderList,_ as listPatch,j as listProblems,z as moveProvider,y as nextProviderId,b as ownProviderCount,x as primaryProvider,E as providerIdBase,P as removeProviderAt,c as storedShape,O as withProvider,$ as withoutProvider};
@@ -1 +1 @@
1
- import{EventError as A}from"./event.js";const k=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract","chat","s2s"]),p=Object.freeze(["embedded","container","remote","harness","router","none"]),f=Object.freeze(["none","loopback","lan","internet","configurable"]),g=Object.freeze({detect:"/v1/detect",decide:"/v1/decide",rerank:"/v1/rerank",embed:"/v1/embeddings",stt:"/v1/audio/transcriptions",tts:"/v1/audio/speech",search:"/v1/search",read:"/v1/read",extract:"/v1/extract",chat:"/v1/chat/completions",s2s:"/v1/audio/conversations"}),b=Object.freeze(new Set(["search","read","extract"])),v=Object.freeze(["day","week","month","year"]),h=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),m=Object.freeze(["markdown","text"]),_="/v1/capabilities",S="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),i=e=>typeof e=="string"&&e.length>0,o=e=>typeof e=="number"&&Number.isFinite(e),t=(e,s)=>{if(!e)throw new A("SHAPE",s)};function M(e,s){if(!a(e)||!(e.calls>0))return null;const r=o(e.p50Ms)?e.p50Ms:0,n=o(e.charsPerSec)&&e.charsPerSec>0&&o(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(r,n))}function w(e,s,r){if(!o(r)||r<=0)return null;const n=M(e,s);return n===null||n<=r?null:{error:{type:S,message:`predicted ${n} ms is over the ${r} ms budget`,predictedMs:n,budgetMs:r}}}function O(e){t(a(e),"detect: body must be an object"),t(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(t(i(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(t(Array.isArray(e.labels)&&e.labels.every(i),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),e.strict!=null&&(t(typeof e.strict=="boolean","detect: strict must be a boolean"),e.strict&&(s.strict=!0)),s}function N(e,s=null){t(a(e),"detect: response must be an object"),t(Array.isArray(e.entities),"detect: entities[] required"),t(i(e.model),"detect: model required"),t(o(e.ms)&&e.ms>=0,"detect: ms required");for(const r of e.entities)t(a(r)&&i(r.value)&&i(r.type),"detect: entity needs value and type"),t(Number.isInteger(r.start)&&Number.isInteger(r.end)&&r.start>=0&&r.end>r.start,`detect: entity ${JSON.stringify(r.value)} needs start < end`),t(o(r.score)&&r.score>=0&&r.score<=1,`detect: entity ${JSON.stringify(r.value)} needs a score in [0,1]`),typeof s=="string"&&t(s.slice(r.start,r.end)===r.value,`detect: entity ${JSON.stringify(r.value)} is not at ${r.start}–${r.end} of the text`);return e}const c=e=>{if(!i(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function y(e){t(a(e),"search: body must be an object"),t(i(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(t(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=50,"search: limit must be an integer 1–50"),s.limit=e.limit),e.lang!=null&&(t(i(e.lang)&&/^[a-z]{2}(-[A-Za-z]{2})?$/.test(e.lang),"search: lang must be a BCP-47 tag like en or en-US"),s.lang=e.lang),e.site!=null&&(t(i(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(t(v.includes(e.freshness),`search: freshness must be one of ${v.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(t(Number.isInteger(e.read)&&e.read>=0&&e.read<=10,"search: read must be an integer 0–10"),s.read=e.read),e.provider!=null&&(t(i(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function C(e){return t(a(e),"search: response must be an object"),t(Array.isArray(e.results),"search: results[] required"),t(i(e.provider),"search: provider required"),t(o(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,r)=>{t(a(s)&&s.rank===r+1,`search: result ${r} must carry rank ${r+1}`),t(c(s.url),`search: result ${r+1} needs an absolute http(s) url`),t(i(s.title),`search: result ${r+1} needs a title`),t(typeof s.snippet=="string",`search: result ${r+1} needs a snippet (may be empty)`),s.read!=null&&j(s.read),s.engine!=null&&t(typeof s.engine=="string",`search: result ${r+1} engine must be a string`),s.via!=null&&t($.includes(s.via),`search: result ${r+1} via must be one of ${$.join(", ")}`)}),e.trail!=null&&(t(a(e.trail)&&x.includes(e.trail.status),`search: trail.status must be one of ${x.join(", ")}`),t(Array.isArray(e.trail.asked)&&e.trail.asked.every(s=>a(s)&&i(s.id)&&["answered","empty","refused"].includes(s.outcome)),"search: trail.asked[] needs { id, outcome }"),t(Array.isArray(e.trail.resting)&&e.trail.resting.every(s=>a(s)&&i(s.id)&&o(s.until)),"search: trail.resting[] needs { id, until }")),e}const $=Object.freeze(["gateway","searxng","api","page","browser"]),x=Object.freeze(["answered","nothing","blocked","resting","offline","no-engines"]);function z(e){t(a(e),"read: body must be an object"),t(c(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(t(m.includes(e.format),`read: format must be one of ${m.join(", ")}`),s.format=e.format),e.maxChars!=null&&(t(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(t(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(t(i(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function j(e){t(a(e),"read: response must be an object"),t(c(e.url),"read: url (absolute, where the page landed) required"),t(typeof e.title=="string","read: title (string, may be empty) required"),t(m.includes(e.format),"read: format required");const s=e[e.format];t(typeof s=="string",`read: ${e.format} (string) required`),t(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),t(typeof e.truncated=="boolean","read: truncated (boolean) required"),t(i(e.provider),"read: provider required"),t(o(e.ms)&&e.ms>=0,"read: ms required"),t(Array.isArray(e.sections),"read: sections[] required");for(const r of e.sections)t(a(r)&&i(r.id)&&i(r.heading),"read: section needs id and heading"),t(Number.isInteger(r.level)&&r.level>=1&&r.level<=6,`read: section ${r.id} needs level 1–6`),t(Number.isInteger(r.offset)&&r.offset>=0&&r.offset<=s.length,`read: section ${r.id} offset must index the content`);return e.restricted!=null&&t(a(e.restricted)&&h.includes(e.restricted.reason),`read: restricted.reason must be one of ${h.join(", ")}`),e}const q=Object.freeze(["choice","score","noul"]),R=/^[A-Za-z_][A-Za-z0-9_]*$/;function D(e){t(a(e),"decide: body must be an object"),t(i(e.state),"decide: state (non-empty string) required"),t(a(e.questions)&&Object.keys(e.questions).length>0,"decide: questions {} required");const s={};for(const[n,u]of Object.entries(e.questions)){t(R.test(n),`decide: question key ${JSON.stringify(n)} must be an identifier`),t(a(u)&&q.includes(u.type),`decide: question ${n}.type must be one of ${q.join(", ")}`),t(i(u.instructions),`decide: question ${n} needs instructions`);const l={type:u.type,instructions:u.instructions};u.type==="noul"?t(u.options==null,`decide: question ${n}: a noul has no options`):(t(Array.isArray(u.options)&&u.options.length>=2&&u.options.length<=255,`decide: question ${n}.options needs 2–255 entries`),l.options=u.options.map(d=>i(d)?{value:d}:(t(a(d)&&i(d.value),`decide: question ${n}: an option is a string or { value, describe? }`),d.describe!=null?{value:d.value,describe:String(d.describe)}:{value:d.value})),t(new Set(l.options.map(d=>d.value)).size===l.options.length,`decide: question ${n}.options must be distinct`)),s[n]=l}const r={state:e.state,questions:s};return e.model!=null&&(t(i(e.model),"decide: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"decide: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),r}function T(e,s=null){t(a(e),"decide: response must be an object"),t(a(e.answers),"decide: answers {} required"),t(i(e.model),"decide: model required"),t(o(e.ms)&&e.ms>=0,"decide: ms required"),e.calibrated!=null&&t(typeof e.calibrated=="boolean","decide: calibrated must be a boolean");const r=n=>o(n)&&n>=0&&n<=1;for(const n of Object.keys(s?s.questions:e.answers)){const u=e.answers[n];t(a(u),`decide: answer ${n} missing`),t(r(u.p),`decide: answer ${n}.p must be in [0,1]`),t(Array.isArray(u.options)&&u.options.every(d=>a(d)&&d.value!==void 0&&r(d.p)),`decide: answer ${n}.options must be [{ value, p }]`),u.confidence!=null&&t(r(u.confidence),`decide: answer ${n}.confidence must be in [0,1]`);const l=s?.questions?.[n];l?.type==="choice"&&t(l.options.some(d=>d.value===u.value),`decide: answer ${n}.value must be one of the options`),l?.type==="noul"&&t(typeof u.value=="boolean",`decide: answer ${n}.value must be a boolean`),l?.type==="score"&&t(o(u.value),`decide: answer ${n}.value must be a number`)}return e}function P(e){t(a(e),"rerank: body must be an object"),t(i(e.query),"rerank: query (non-empty string) required"),t(Array.isArray(e.documents)&&e.documents.length>=1&&e.documents.length<=1e3&&e.documents.every(r=>typeof r=="string"),"rerank: documents must be 1–1000 strings");const s={query:e.query,documents:e.documents.slice()};return e.top_n!=null&&(t(Number.isInteger(e.top_n)&&e.top_n>=1,"rerank: top_n must be an integer ≥ 1"),s.top_n=e.top_n),e.model!=null&&(t(i(e.model),"rerank: model must be a non-empty string"),s.model=e.model),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"rerank: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function B(e,s=null){t(a(e),"rerank: response must be an object"),t(Array.isArray(e.results),"rerank: results[] required"),t(i(e.model),"rerank: model required"),t(o(e.ms)&&e.ms>=0,"rerank: ms required");const r=s?s.documents.length:1/0,n=new Set;let u=1/0;return e.results.forEach((l,d)=>{t(a(l)&&Number.isInteger(l.index)&&l.index>=0&&l.index<r,`rerank: result ${d} needs an index into the documents`),t(!n.has(l.index),`rerank: index ${l.index} listed twice`),n.add(l.index),t(o(l.relevance_score),`rerank: result ${d} needs relevance_score`),t(l.relevance_score<=u,"rerank: results must be ordered best first"),u=l.relevance_score}),s?.top_n!=null&&t(e.results.length<=s.top_n,`rerank: more than top_n (${s.top_n}) results`),e}function U(e){t(a(e),"embed: body must be an object");const s=typeof e.input=="string"?[e.input]:e.input;t(Array.isArray(s)&&s.length>=1&&s.length<=256&&s.every(n=>typeof n=="string"),"embed: input must be a string or 1–256 strings");const r={input:s.slice()};return e.model!=null&&(t(i(e.model),"embed: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"embed: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),e.kind!=null&&(t(e.kind==="query"||e.kind==="passage",'embed: kind must be "query" or "passage"'),r.kind=e.kind),r}function H(e,s=null){t(a(e),"embed: response must be an object"),t(Array.isArray(e.data)&&e.data.length>=1,"embed: data (non-empty array) required"),t(i(e.model),"embed: model required"),t(o(e.ms)&&e.ms>=0,"embed: ms required");let r=0;return e.data.forEach((n,u)=>{t(a(n)&&n.index===u,`embed: data[${u}].index must be ${u}`);const l=n.embedding;t((Array.isArray(l)||ArrayBuffer.isView(l))&&l.length>0,`embed: data[${u}].embedding must be a non-empty vector`),r||(r=l.length),t(l.length===r,"embed: every vector must have the same dimension")}),s&&t(e.data.length===s.input.length,`embed: ${s.input.length} inputs, ${e.data.length} vectors`),e}function L(e){t(a(e),"capabilities: response must be an object"),t(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),t(a(e.server)&&i(e.server.name)&&i(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const r of e.capabilities)t(a(r)&&k.includes(r.id),`capabilities: unknown capability id ${JSON.stringify(r?.id)}`),t(!s.has(r.id),`capabilities: ${r.id} listed twice`),s.add(r.id),t(r.route===g[r.id],`capabilities: ${r.id} must be served at ${g[r.id]}`),b.has(r.id)?(t(Array.isArray(r.providers)&&r.providers.length>0&&r.providers.every(i),`capabilities: ${r.id}.providers must be a non-empty string[]`),r.default!=null&&t(r.providers.includes(r.default),`capabilities: ${r.id}.default must be one of its providers`)):(t(Array.isArray(r.models)&&r.models.every(i),`capabilities: ${r.id}.models must be string[]`),r.default!=null&&t(r.models.includes(r.default),`capabilities: ${r.id}.default must be one of its models`)),r.labels!=null&&t(Array.isArray(r.labels)&&r.labels.every(i),`capabilities: ${r.id}.labels must be string[]`),r.stats!=null&&t(a(r.stats)&&(b.has(r.id)||o(r.stats.calls)),`capabilities: ${r.id}.stats needs calls`),r.runtime!=null&&t(a(r.runtime)&&i(r.runtime.state),`capabilities: ${r.id}.runtime needs state`),r.provider!=null&&E(r.provider,r.id);return e}function E(e,s="capability"){return t(a(e)&&p.includes(e.kind),`capabilities: ${s}.provider.kind must be one of ${p.join(", ")}`),e.egress!=null&&t(f.includes(e.egress),`capabilities: ${s}.provider.egress must be one of ${f.join(", ")}`),e.url!=null&&t(i(e.url)&&/^https?:\/\//.test(e.url),`capabilities: ${s}.provider.url must be http(s)`),e.adapter!=null&&t(i(e.adapter),`capabilities: ${s}.provider.adapter must be a string`),e.model!=null&&t(i(e.model),`capabilities: ${s}.provider.model must be a string`),e.label!=null&&t(i(e.label),`capabilities: ${s}.provider.label must be a string`),e}function V(e){return(e?.capabilities||[]).map(s=>({id:s.id,route:s.route,models:s.models||[],providers:s.providers||[],ready:!s.runtime||["ready","external","idle"].includes(s.runtime.state),stats:s.stats||null,labels:s.labels||null}))}export{k as CAPABILITIES,g as CAPABILITY_ROUTES,q as DECIDE_QUESTION_TYPES,_ as DISCOVERY_ROUTE,f as EGRESS_KINDS,S as OVER_BUDGET,b as PROVIDER_CAPABILITIES,p as PROVIDER_KINDS,m as READ_FORMATS,h as READ_RESTRICTIONS,v as SEARCH_FRESHNESS,x as SEARCH_TRAIL_STATUSES,$ as SEARCH_VIAS,V as offeredCapabilities,w as overBudget,M as predictMs,L as validateCapabilitiesResponse,D as validateDecideRequest,T as validateDecideResponse,O as validateDetectRequest,N as validateDetectResponse,U as validateEmbedRequest,H as validateEmbedResponse,E as validateProvider,z as validateReadRequest,j as validateReadResponse,P as validateRerankRequest,B as validateRerankResponse,y as validateSearchRequest,C as validateSearchResponse};
1
+ import{EventError as q}from"./event.js";const A=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract","chat","s2s"]),p=Object.freeze(["embedded","container","remote","harness","router","none"]),f=Object.freeze(["none","loopback","lan","internet","configurable"]),g=Object.freeze({detect:"/v1/detect",decide:"/v1/decide",rerank:"/v1/rerank",embed:"/v1/embeddings",stt:"/v1/audio/transcriptions",tts:"/v1/audio/speech",search:"/v1/search",read:"/v1/read",extract:"/v1/extract",chat:"/v1/chat/completions",s2s:"/v1/audio/conversations"}),b=Object.freeze(new Set(["search","read","extract"])),v=Object.freeze(["day","week","month","year"]),h=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),m=Object.freeze(["markdown","text"]),I="/v1/capabilities",w="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),i=e=>typeof e=="string"&&e.length>0,o=e=>typeof e=="number"&&Number.isFinite(e),t=(e,s)=>{if(!e)throw new q("SHAPE",s)};function S(e,s){if(!a(e)||!(e.calls>0))return null;const r=o(e.p50Ms)?e.p50Ms:0,n=o(e.charsPerSec)&&e.charsPerSec>0&&o(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(r,n))}function _(e,s,r){if(!o(r)||r<=0)return null;const n=S(e,s);return n===null||n<=r?null:{error:{type:w,message:`predicted ${n} ms is over the ${r} ms budget`,predictedMs:n,budgetMs:r}}}function O(e){t(a(e),"detect: body must be an object"),t(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(t(i(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(t(Array.isArray(e.labels)&&e.labels.every(i),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),e.strict!=null&&(t(typeof e.strict=="boolean","detect: strict must be a boolean"),e.strict&&(s.strict=!0)),s}function N(e,s=null){t(a(e),"detect: response must be an object"),t(Array.isArray(e.entities),"detect: entities[] required"),t(i(e.model),"detect: model required"),t(o(e.ms)&&e.ms>=0,"detect: ms required");for(const r of e.entities)t(a(r)&&i(r.value)&&i(r.type),"detect: entity needs value and type"),t(Number.isInteger(r.start)&&Number.isInteger(r.end)&&r.start>=0&&r.end>r.start,`detect: entity ${JSON.stringify(r.value)} needs start < end`),t(o(r.score)&&r.score>=0&&r.score<=1,`detect: entity ${JSON.stringify(r.value)} needs a score in [0,1]`),typeof s=="string"&&t(s.slice(r.start,r.end)===r.value,`detect: entity ${JSON.stringify(r.value)} is not at ${r.start}–${r.end} of the text`);return e}const c=e=>{if(!i(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function C(e){t(a(e),"search: body must be an object"),t(i(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(t(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=50,"search: limit must be an integer 1–50"),s.limit=e.limit),e.lang!=null&&(t(i(e.lang)&&/^[a-z]{2}(-[A-Za-z]{2})?$/.test(e.lang),"search: lang must be a BCP-47 tag like en or en-US"),s.lang=e.lang),e.site!=null&&(t(i(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(t(v.includes(e.freshness),`search: freshness must be one of ${v.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(t(Number.isInteger(e.read)&&e.read>=0&&e.read<=10,"search: read must be an integer 0–10"),s.read=e.read),e.provider!=null&&(t(i(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function y(e){return t(a(e),"search: response must be an object"),t(Array.isArray(e.results),"search: results[] required"),t(i(e.provider),"search: provider required"),t(o(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,r)=>{t(a(s)&&s.rank===r+1,`search: result ${r} must carry rank ${r+1}`),t(c(s.url),`search: result ${r+1} needs an absolute http(s) url`),t(i(s.title),`search: result ${r+1} needs a title`),t(typeof s.snippet=="string",`search: result ${r+1} needs a snippet (may be empty)`),s.read!=null&&M(s.read),s.engine!=null&&t(typeof s.engine=="string",`search: result ${r+1} engine must be a string`),s.via!=null&&t($.includes(s.via),`search: result ${r+1} via must be one of ${$.join(", ")}`)}),e.trail!=null&&(t(a(e.trail)&&x.includes(e.trail.status),`search: trail.status must be one of ${x.join(", ")}`),t(Array.isArray(e.trail.asked)&&e.trail.asked.every(s=>a(s)&&i(s.id)&&["answered","empty","refused"].includes(s.outcome)),"search: trail.asked[] needs { id, outcome }"),t(Array.isArray(e.trail.resting)&&e.trail.resting.every(s=>a(s)&&i(s.id)&&o(s.until)),"search: trail.resting[] needs { id, until }")),e}const $=Object.freeze(["gateway","searxng","api","page","browser"]),x=Object.freeze(["answered","nothing","blocked","resting","offline","no-engines"]);function z(e){t(a(e),"read: body must be an object"),t(c(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(t(m.includes(e.format),`read: format must be one of ${m.join(", ")}`),s.format=e.format),e.maxChars!=null&&(t(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(t(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(t(i(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function M(e){t(a(e),"read: response must be an object"),t(c(e.url),"read: url (absolute, where the page landed) required"),t(typeof e.title=="string","read: title (string, may be empty) required"),t(m.includes(e.format),"read: format required");const s=e[e.format];t(typeof s=="string",`read: ${e.format} (string) required`),t(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),t(typeof e.truncated=="boolean","read: truncated (boolean) required"),t(i(e.provider),"read: provider required"),t(o(e.ms)&&e.ms>=0,"read: ms required"),t(Array.isArray(e.sections),"read: sections[] required");for(const r of e.sections)t(a(r)&&i(r.id)&&i(r.heading),"read: section needs id and heading"),t(Number.isInteger(r.level)&&r.level>=1&&r.level<=6,`read: section ${r.id} needs level 1–6`),t(Number.isInteger(r.offset)&&r.offset>=0&&r.offset<=s.length,`read: section ${r.id} offset must index the content`);return e.restricted!=null&&t(a(e.restricted)&&h.includes(e.restricted.reason),`read: restricted.reason must be one of ${h.join(", ")}`),e}const k=Object.freeze(["choice","score","noul"]),j=/^[A-Za-z_][A-Za-z0-9_]*$/;function D(e){t(a(e),"decide: body must be an object"),t(i(e.state),"decide: state (non-empty string) required"),t(a(e.questions)&&Object.keys(e.questions).length>0,"decide: questions {} required");const s={};for(const[n,u]of Object.entries(e.questions)){t(j.test(n),`decide: question key ${JSON.stringify(n)} must be an identifier`),t(a(u)&&k.includes(u.type),`decide: question ${n}.type must be one of ${k.join(", ")}`),t(i(u.instructions),`decide: question ${n} needs instructions`);const l={type:u.type,instructions:u.instructions};u.type==="noul"?t(u.options==null,`decide: question ${n}: a noul has no options`):(t(Array.isArray(u.options)&&u.options.length>=2&&u.options.length<=255,`decide: question ${n}.options needs 2–255 entries`),l.options=u.options.map(d=>i(d)?{value:d}:(t(a(d)&&i(d.value),`decide: question ${n}: an option is a string or { value, describe? }`),d.describe!=null?{value:d.value,describe:String(d.describe)}:{value:d.value})),t(new Set(l.options.map(d=>d.value)).size===l.options.length,`decide: question ${n}.options must be distinct`)),s[n]=l}const r={state:e.state,questions:s};return e.model!=null&&(t(i(e.model),"decide: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"decide: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),e.wake!=null&&(t(typeof e.wake=="boolean","decide: wake must be true or false"),r.wake=e.wake),r}function T(e,s=null){t(a(e),"decide: response must be an object"),t(a(e.answers),"decide: answers {} required"),t(i(e.model),"decide: model required"),t(o(e.ms)&&e.ms>=0,"decide: ms required"),e.calibrated!=null&&t(typeof e.calibrated=="boolean","decide: calibrated must be a boolean");const r=n=>o(n)&&n>=0&&n<=1;for(const n of Object.keys(s?s.questions:e.answers)){const u=e.answers[n];t(a(u),`decide: answer ${n} missing`),t(r(u.p),`decide: answer ${n}.p must be in [0,1]`),t(Array.isArray(u.options)&&u.options.every(d=>a(d)&&d.value!==void 0&&r(d.p)),`decide: answer ${n}.options must be [{ value, p }]`),u.confidence!=null&&t(r(u.confidence),`decide: answer ${n}.confidence must be in [0,1]`);const l=s?.questions?.[n];l?.type==="choice"&&t(l.options.some(d=>d.value===u.value),`decide: answer ${n}.value must be one of the options`),l?.type==="noul"&&t(typeof u.value=="boolean",`decide: answer ${n}.value must be a boolean`),l?.type==="score"&&t(o(u.value),`decide: answer ${n}.value must be a number`)}return e}function P(e){t(a(e),"rerank: body must be an object"),t(i(e.query),"rerank: query (non-empty string) required"),t(Array.isArray(e.documents)&&e.documents.length>=1&&e.documents.length<=1e3&&e.documents.every(r=>typeof r=="string"),"rerank: documents must be 1–1000 strings");const s={query:e.query,documents:e.documents.slice()};return e.top_n!=null&&(t(Number.isInteger(e.top_n)&&e.top_n>=1,"rerank: top_n must be an integer ≥ 1"),s.top_n=e.top_n),e.model!=null&&(t(i(e.model),"rerank: model must be a non-empty string"),s.model=e.model),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"rerank: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),e.wake!=null&&(t(typeof e.wake=="boolean","rerank: wake must be true or false"),s.wake=e.wake),s}function B(e,s=null){t(a(e),"rerank: response must be an object"),t(Array.isArray(e.results),"rerank: results[] required"),t(i(e.model),"rerank: model required"),t(o(e.ms)&&e.ms>=0,"rerank: ms required");const r=s?s.documents.length:1/0,n=new Set;let u=1/0;return e.results.forEach((l,d)=>{t(a(l)&&Number.isInteger(l.index)&&l.index>=0&&l.index<r,`rerank: result ${d} needs an index into the documents`),t(!n.has(l.index),`rerank: index ${l.index} listed twice`),n.add(l.index),t(o(l.relevance_score),`rerank: result ${d} needs relevance_score`),t(l.relevance_score<=u,"rerank: results must be ordered best first"),u=l.relevance_score}),s?.top_n!=null&&t(e.results.length<=s.top_n,`rerank: more than top_n (${s.top_n}) results`),e}function U(e){t(a(e),"embed: body must be an object");const s=typeof e.input=="string"?[e.input]:e.input;t(Array.isArray(s)&&s.length>=1&&s.length<=256&&s.every(n=>typeof n=="string"),"embed: input must be a string or 1–256 strings");const r={input:s.slice()};return e.model!=null&&(t(i(e.model),"embed: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"embed: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),e.kind!=null&&(t(e.kind==="query"||e.kind==="passage",'embed: kind must be "query" or "passage"'),r.kind=e.kind),r}function H(e,s=null){t(a(e),"embed: response must be an object"),t(Array.isArray(e.data)&&e.data.length>=1,"embed: data (non-empty array) required"),t(i(e.model),"embed: model required"),t(o(e.ms)&&e.ms>=0,"embed: ms required");let r=0;return e.data.forEach((n,u)=>{t(a(n)&&n.index===u,`embed: data[${u}].index must be ${u}`);const l=n.embedding;t((Array.isArray(l)||ArrayBuffer.isView(l))&&l.length>0,`embed: data[${u}].embedding must be a non-empty vector`),r||(r=l.length),t(l.length===r,"embed: every vector must have the same dimension")}),s&&t(e.data.length===s.input.length,`embed: ${s.input.length} inputs, ${e.data.length} vectors`),e}function L(e){t(a(e),"capabilities: response must be an object"),t(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),t(a(e.server)&&i(e.server.name)&&i(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const r of e.capabilities)t(a(r)&&A.includes(r.id),`capabilities: unknown capability id ${JSON.stringify(r?.id)}`),t(!s.has(r.id),`capabilities: ${r.id} listed twice`),s.add(r.id),t(r.route===g[r.id],`capabilities: ${r.id} must be served at ${g[r.id]}`),b.has(r.id)?(t(Array.isArray(r.providers)&&r.providers.length>0&&r.providers.every(i),`capabilities: ${r.id}.providers must be a non-empty string[]`),r.default!=null&&t(r.providers.includes(r.default),`capabilities: ${r.id}.default must be one of its providers`)):(t(Array.isArray(r.models)&&r.models.every(i),`capabilities: ${r.id}.models must be string[]`),r.default!=null&&t(r.models.includes(r.default),`capabilities: ${r.id}.default must be one of its models`)),r.labels!=null&&t(Array.isArray(r.labels)&&r.labels.every(i),`capabilities: ${r.id}.labels must be string[]`),r.stats!=null&&t(a(r.stats)&&(b.has(r.id)||o(r.stats.calls)),`capabilities: ${r.id}.stats needs calls`),r.runtime!=null&&t(a(r.runtime)&&i(r.runtime.state),`capabilities: ${r.id}.runtime needs state`),r.provider!=null&&R(r.provider,r.id);return e}function R(e,s="capability"){return t(a(e)&&p.includes(e.kind),`capabilities: ${s}.provider.kind must be one of ${p.join(", ")}`),e.egress!=null&&t(f.includes(e.egress),`capabilities: ${s}.provider.egress must be one of ${f.join(", ")}`),e.url!=null&&t(i(e.url)&&/^https?:\/\//.test(e.url),`capabilities: ${s}.provider.url must be http(s)`),e.adapter!=null&&t(i(e.adapter),`capabilities: ${s}.provider.adapter must be a string`),e.model!=null&&t(i(e.model),`capabilities: ${s}.provider.model must be a string`),e.label!=null&&t(i(e.label),`capabilities: ${s}.provider.label must be a string`),e}function V(e){return(e?.capabilities||[]).map(s=>({id:s.id,route:s.route,models:s.models||[],providers:s.providers||[],ready:!s.runtime||["ready","external","idle"].includes(s.runtime.state),stats:s.stats||null,labels:s.labels||null}))}export{A as CAPABILITIES,g as CAPABILITY_ROUTES,k as DECIDE_QUESTION_TYPES,I as DISCOVERY_ROUTE,f as EGRESS_KINDS,w as OVER_BUDGET,b as PROVIDER_CAPABILITIES,p as PROVIDER_KINDS,m as READ_FORMATS,h as READ_RESTRICTIONS,v as SEARCH_FRESHNESS,x as SEARCH_TRAIL_STATUSES,$ as SEARCH_VIAS,V as offeredCapabilities,_ as overBudget,S as predictMs,L as validateCapabilitiesResponse,D as validateDecideRequest,T as validateDecideResponse,O as validateDetectRequest,N as validateDetectResponse,U as validateEmbedRequest,H as validateEmbedResponse,R as validateProvider,z as validateReadRequest,M as validateReadResponse,P as validateRerankRequest,B as validateRerankResponse,C as validateSearchRequest,y as validateSearchResponse};
@@ -1,3 +1,4 @@
1
- import{callFirstProvider as m}from"./capability-providers.js";import{DECIDE_QUESTION_TYPES as A,validateDecideRequest as E,validateRerankRequest as x}from"./capability-endpoints.js";const g="decide",f="rerank",O=6e4,v=200,q=2e3,b=160,_="A small DECISION MODEL and/or a RERANKER run on this device. For a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over text you already hold, call `decide` instead of judging it yourself — it answers in milliseconds with a probability per option. To order many candidates (search hits, comments, sections, options) by relevance to a question, call `rerank` instead of reading them all. Report its answer as the model's, with the probability, and say when it is marked uncalibrated.",N="No decision model is running on this device. Judge the text yourself now and say the answer is your own reading, not a model's probability.",R="No reranker is running on this device. Order the candidates yourself by reading them, and say the ordering is your own.",S=Object.freeze({name:g,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Ask a small local decision model one or more typed questions about a text: a choice among options (sentiment, category, urgency), a score on an ordered rubric, or a yes/no. Returns the answer per question with its probability and the runner-up. Use it for any classification of text you already have — the whole thread, a comment, an email — rather than judging it yourself. Not a language model: it cannot explain, only decide.",parameters:{type:"object",properties:{text:{type:"string",description:"The text to judge, as-is. Up to ~60k characters."},questions:{type:"array",minItems:1,description:"One or more questions, each answered independently over the same text.",items:{type:"object",properties:{key:{type:"string",description:'A short identifier for the answer (e.g. "sentiment"). Optional.'},type:{type:"string",enum:[...A],description:'"choice" picks one option; "score" places the text on options read as an ordered rubric (worst first); "noul" is yes/no and takes no options.'},instructions:{type:"string",description:'What to decide, in one sentence — e.g. "The overall sentiment of the comments toward the company."'},options:{type:"array",items:{type:"string"},description:"For choice and score: 2–255 distinct options. Omit for noul."}},required:["type","instructions"],additionalProperties:!1}}},required:["text","questions"],additionalProperties:!1}}),T=Object.freeze({name:f,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Order candidate texts by relevance to a query with a local reranker (a cross-encoder). Give it the query and the candidates — search results, comments, paragraphs, options — and it returns them best first with a relevance score each. Use it to pick what to read or cite from many candidates instead of reading them all.",parameters:{type:"object",properties:{query:{type:"string",description:"What relevance is measured against — the question or the need."},documents:{type:"array",items:{type:"string"},minItems:2,description:"The candidates, 2–200 strings. Each is read up to ~2000 characters."},top_n:{type:"integer",minimum:1,description:"Return only the best N. Default: all, ordered."}},required:["query","documents"],additionalProperties:!1}}),D=/^[A-Za-z_][A-Za-z0-9_]*$/;function j(e){const i={};return(Array.isArray(e)?e:[]).forEach((t,s)=>{if(!t||typeof t!="object")return;let n=String(t.key||"").trim();(!D.test(n)||i[n])&&(n=`q${s+1}`);const r={type:String(t.type||""),instructions:String(t.instructions||"")};r.type!=="noul"&&Array.isArray(t.options)&&(r.options=t.options.map(p=>String(p))),i[n]=r}),i}const w=e=>`${Math.round(Number(e)*100)}%`,h=e=>String(e).replace(/\s+/g," ").trim();function $(e,i,t){const s=i.where?` on ${i.where}`:"",n=Number.isFinite(e.ms)?` in ${Math.round(e.ms)} ms`:"";return`Answered by ${e.model||i.id}${s}${n} — ${t}, not a language model.`}function C(e,i,t){const s=[];for(const[n,r]of Object.entries(e.answers||{})){const p=t[n],d=typeof r.value=="boolean"?r.value?"yes":"no":String(r.value),o=(r.options||[]).filter(c=>c.value!==r.value).sort((c,l)=>l.p-c.p),y=o.length?`; then ${typeof o[0].value=="boolean"?o[0].value?"yes":"no":o[0].value} ${w(o[0].p)}`:"";s.push(`${n}${p?.instructions?` (${h(p.instructions)})`:""}: ${d} — ${w(r.p)}${y}`)}return s.push("",$(e,i,"a decision model")),e.calibrated===!1&&s.push("Uncalibrated: the probabilities rank the options but are not confidence — say so if you quote them."),s.join(`
2
- `)}function I(e,i,t,{query:s="",topN:n=null}={}){const r=e.results.map((d,o)=>`${o+1}. [doc ${d.index+1}] score ${Number(d.relevance_score).toFixed(3)} — ${h(t[d.index]).slice(0,b)}${t[d.index].length>b?"…":""}`);return[`${e.results.length} of ${t.length} candidate(s) for "${h(s).slice(0,120)}", best first${n?` (top ${n})`:""}. [doc N] is the 1-based position in the list you sent.`,...r,"",$(e,i,"a reranker")].join(`
3
- `)}function H({providers:e={},fetch:i,budgetMs:t=8e3,always:s=!1}={}){if(typeof i!="function")throw new Error("capabilityToolsProvider: fetch required");const n=Array.isArray(e.decide)?e.decide:[],r=Array.isArray(e.rerank)?e.rerank:[];if(!s&&!n.length&&!r.length)return null;const p=[];return(s||n.length)&&p.push(S),(s||r.length)&&p.push(T),{specs:p,system:_,async execute(d,o){if(d===g){if(!n.length)return N;const y=String(o?.text||"").trim().slice(0,O),c=j(o?.questions);if(!y)return"decide needs `text` — the passage to judge.";if(!Object.keys(c).length)return"decide needs at least one question: { type, instructions, options? }.";let l;try{l=E({state:y,questions:c,budgetMs:t})}catch(u){return`decide could not take the questions (${u.message}). Fix them and call again: a choice or score needs 2–255 distinct options, a noul none.`}try{const{doc:u,provider:a}=await m(n,"decide",l,{fetch:i,timeoutMs:2e4,validateAgainst:l});return C(u,a,l.questions)}catch(u){return`No decision model answered (${u?.message||u}). Judge the text yourself now and say the answer is your own reading, not a model's probability.`}}if(d===f){if(!r.length)return R;const y=String(o?.query||"").trim(),c=(Array.isArray(o?.documents)?o.documents:[]).map(a=>String(a??"")).filter(a=>a.trim()).slice(0,v);if(!y)return"rerank needs `query` — what relevance is measured against.";if(c.length<2)return c.length===1?"One candidate needs no ordering — it is the answer.":"rerank needs `documents` — two or more candidates.";const l=Number.isInteger(o?.top_n)&&o.top_n>=1?Math.min(o.top_n,c.length):null;let u;try{u=x({query:y,documents:c.map(a=>h(a).slice(0,q)),budgetMs:t,...l?{top_n:l}:{}})}catch(a){return`rerank could not take the candidates (${a.message}).`}try{const{doc:a,provider:k}=await m(r,"rerank",u,{fetch:i,validateAgainst:u});return I(a,k,c,{query:y,topN:l})}catch(a){return`No reranker answered (${a?.message||a}). Order the candidates yourself by reading them, and say the ordering is your own.`}}return JSON.stringify({error:`Unknown tool: ${d}`})}}}export{_ as CAPABILITY_TOOLS_SYSTEM,g as DECIDE_TOOL_NAME,f as RERANK_TOOL_NAME,H as capabilityToolsProvider,j as questionsToWire,C as renderDecideResult,I as renderRerankResult};
1
+ import{callFirstProvider as q}from"./capability-providers.js";import{DECIDE_QUESTION_TYPES as A,validateDecideRequest as v,validateRerankRequest as R}from"./capability-endpoints.js";import{questionsToWire as $,QUESTION_WORDS as _}from"./decide-ask.js";const f="decide",x="rerank",N=6e4,S=200,T=2e3,E=160,D="A small DECISION MODEL and/or a RERANKER run on this device. For a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over text you already hold, call `decide` instead of judging it yourself — it answers in milliseconds with a probability per option. To order many candidates (search hits, comments, sections, options) by relevance to a question, call `rerank` instead of reading them all. Report its answer as the model's, with the probability, and say when it is marked uncalibrated.",C="No decision model is running on this device. Judge the text yourself now and say the answer is your own reading, not a model's probability.",j="No reranker is running on this device. Order the candidates yourself by reading them, and say the ordering is your own.",I=Object.freeze({name:f,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Ask a small local decision model one or more typed questions about a text: a choice among options (sentiment, category, urgency), a score on an ordered rubric, or a yes/no. Returns the answer per question with its probability and the runner-up. Use it for any classification of text you already have — the whole thread, a comment, an email — rather than judging it yourself. Not a language model: it cannot explain, only decide.",parameters:{type:"object",properties:{text:{type:"string",description:"The text to judge, as-is. Up to ~60k characters."},questions:{type:"array",minItems:1,description:"One or more questions, each answered independently over the same text.",items:{type:"object",properties:{key:{type:"string",description:'A short identifier for the answer (e.g. "sentiment"). Optional.'},type:{type:"string",enum:[...A],description:'"choice" picks one option; "score" places the text on options read as an ordered rubric (worst first); "noul" is yes/no and takes no options.'},instructions:{type:"string",description:'What to decide, in one sentence — e.g. "The overall sentiment of the comments toward the company."'},options:{type:"array",items:{type:"string"},description:"For choice and score: 2–255 distinct options. Omit for noul."}},required:["type","instructions"],additionalProperties:!1}}},required:["text","questions"],additionalProperties:!1}}),M=Object.freeze({name:x,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Order candidate texts by relevance to a query with a local reranker (a cross-encoder). Give it the query and the candidates — search results, comments, paragraphs, options — and it returns them best first with a relevance score each. Use it to pick what to read or cite from many candidates instead of reading them all.",parameters:{type:"object",properties:{query:{type:"string",description:"What relevance is measured against — the question or the need."},documents:{type:"array",items:{type:"string"},minItems:2,description:"The candidates, 2–200 strings. Each is read up to ~2000 characters."},top_n:{type:"integer",minimum:1,description:"Return only the best N. Default: all, ordered."}},required:["query","documents"],additionalProperties:!1}}),b='{ "text": "…", "questions": [{ "type": "choice", "instructions": "Which team should handle this?", "options": ["billing", "support"] }] }',k=t=>`${Math.round(Number(t)*100)}%`,g=t=>String(t).replace(/\s+/g," ").trim();function O(t,a,d){const s=a.where?` on ${a.where}`:"",r=Number.isFinite(t.ms)?` in ${Math.round(t.ms)} ms`:"";return`Answered by ${t.model||a.id}${s}${r} — ${d}, not a language model.`}function P(t,a,d){const s=[];for(const[r,o]of Object.entries(t.answers||{})){const m=d[r],u=typeof o.value=="boolean"?o.value?"yes":"no":String(o.value),c=(o.options||[]).filter(h=>h.value!==o.value).sort((h,y)=>y.p-h.p),e=c.length?`; then ${typeof c[0].value=="boolean"?c[0].value?"yes":"no":c[0].value} ${k(c[0].p)}`:"";s.push(`${r}${m?.instructions?` (${g(m.instructions)})`:""}: ${u} — ${k(o.p)}${e}`)}return s.push("",O(t,a,"a decision model")),t.calibrated===!1&&s.push("Uncalibrated: the probabilities rank the options but are not confidence — say so if you quote them."),s.join(`
2
+ `)}function U(t,a,d,{query:s="",topN:r=null}={}){const o=t.results.map((u,c)=>`${c+1}. [doc ${u.index+1}] score ${Number(u.relevance_score).toFixed(3)} — ${g(d[u.index]).slice(0,E)}${d[u.index].length>E?"…":""}`);return[`${t.results.length} of ${d.length} candidate(s) for "${g(s).slice(0,120)}", best first${r?` (top ${r})`:""}. [doc N] is the 1-based position in the list you sent.`,...o,"",O(t,a,"a reranker")].join(`
3
+ `)}function W({providers:t={},fetch:a,budgetMs:d=8e3,always:s=!1}={}){if(typeof a!="function")throw new Error("capabilityToolsProvider: fetch required");const r=Array.isArray(t.decide)?t.decide:[],o=Array.isArray(t.rerank)?t.rerank:[];if(!s&&!r.length&&!o.length)return null;const m=[];(s||r.length)&&m.push(I),(s||o.length)&&m.push(M);const u={specs:m,system:D,async execute(c,e){if(c===f){if(!r.length)return C;const h=String(e?.text??e?.input??"").trim().slice(0,N),y=$(e?.questions??(_.some(i=>e?.[i])?e:null));if(!h)return"decide needs `text` — the passage to judge.";if(!Object.keys(y).length)return`decide needs at least one question. Call it like this: ${b}`;let l;try{l=v({state:h,questions:y,budgetMs:d})}catch(i){return`decide could not take the questions (${i.message}). A choice or score needs 2–255 distinct options, a noul (yes/no) none. Call it like this: ${b}`}try{const{doc:i,provider:p}=await q(r,"decide",l,{fetch:a,timeoutMs:2e4,validateAgainst:l});return P(i,p,l.questions)}catch(i){return`No decision model answered (${i?.message||i}). Judge the text yourself now and say the answer is your own reading, not a model's probability.`}}if(c===x){const h=["options","labels","choices"].map(n=>e?.[n]).find(Array.isArray);if(h&&r.length){const n=typeof e?.documents=="string"?e.documents:Array.isArray(e?.documents)&&e.documents.length===1?String(e.documents[0]):String(e?.text??e?.input??"");return`That is a classification, so the decision model answered it (decide, not rerank):
4
+ ${await u.execute(f,{text:n,questions:[{question:String(e?.query||e?.question||""),options:h}]})}`}if(!o.length)return j;const y=String(e?.query||"").trim(),l=(Array.isArray(e?.documents)?e.documents:[]).map(n=>String(n??"")).filter(n=>n.trim()).slice(0,S);if(!y)return"rerank needs `query` — what relevance is measured against.";if(l.length<2)return`rerank orders TWO OR MORE candidate texts by how well each answers \`query\`${typeof e?.documents=="string"||l.length===1?" — it was given one text":""}. For one text and a question about it (which team, which label, yes or no), call decide instead: ${b}`;const i=Number.isInteger(e?.top_n)&&e.top_n>=1?Math.min(e.top_n,l.length):null;let p;try{p=R({query:y,documents:l.map(n=>g(n).slice(0,T)),budgetMs:d,...i?{top_n:i}:{}})}catch(n){return`rerank could not take the candidates (${n.message}).`}try{const{doc:n,provider:w}=await q(o,"rerank",p,{fetch:a,validateAgainst:p});return U(n,w,l,{query:y,topN:i})}catch(n){return`No reranker answered (${n?.message||n}). Order the candidates yourself by reading them, and say the ordering is your own.`}}return JSON.stringify({error:`Unknown tool: ${c}`})}};return u}export{D as CAPABILITY_TOOLS_SYSTEM,f as DECIDE_TOOL_NAME,x as RERANK_TOOL_NAME,W as capabilityToolsProvider,$ as questionsToWire,P as renderDecideResult,U as renderRerankResult};
package/client-prefs.js CHANGED
@@ -1 +1 @@
1
- const c=Object.freeze([{id:"mcpServers",label:"MCP tool servers",path:["mcpServers"],kind:"array"},{id:"mcpAuth",label:"MCP sign-ins",path:["mcpAuth"],kind:"object"},{id:"skills",label:"Skills",path:["skills"],kind:"array"},{id:"skillDirs",label:"Skill folders",path:["ui","skillDirs"],kind:"array"},{id:"recipes",label:"Recipes",path:["recipes"],kind:"array"},{id:"teams",label:"Teams",path:["teams"],kind:"array"},{id:"agents",label:"Agents",path:["agentPool"],kind:"array"},{id:"connections",label:"Connections",path:["connections"],kind:"array"},{id:"projects",label:"Projects",path:["projects"],kind:"array"},{id:"webSearch",label:"Web search",path:["ui","webSearch"],kind:"object"},{id:"tools",label:"Tools",path:null,kind:"object",keys:["mcpToolsMode","maxToolsPerTurn","maxToolRoundsPerTurn","historyTools","historyContextMode","dataDispatch","toolResultMaxChars","turn"]},{id:"endpoints",label:"Models",path:["endpoints"],kind:"array"},{id:"agentTools",label:"Coding Agents",path:null,kind:"object",rootKeys:["agents","removedBuiltinAgents"]},{id:"freeSlots",label:"Free plan picks",path:null,kind:"object",rootKeys:["freeEndpointId","freeAgentId"]},{id:"routing",label:"Model routing",path:["ui","routing"],kind:"object"},{id:"capabilityUses",label:"Where models may be used",path:["ui","capabilityUses"],kind:"object"},{id:"general",label:"General",path:null,kind:"object",keys:["theme","language","sendOnEnter","streamResponses","autoAttachActiveTab","autocomplete","settingsOpen"]},{id:"identity",label:"Identity",path:null,kind:"object",rootKeys:["selfName"]},{id:"suggestions",label:"Smart suggestions",path:["ui","suggestions"],kind:"object"},{id:"topics",label:"Topic extraction",path:["ui","topicExtraction"],kind:"object"},{id:"memory",label:"Memory",path:["ui","memory"],kind:"object"},{id:"notes",label:"Notes",path:["ui","notes"],kind:"object"},{id:"speech",label:"Speech",path:null,kind:"object",keys:["dictation","capture","scribeLive"]},{id:"warmSearch",label:"Gateway search index",path:["ui","warmSearch"],kind:"object"},{id:"recall",label:"Search & indexing",path:["ui","recall"],kind:"object"},{id:"voice",label:"Voice",path:["ui","voice"],kind:"object"},{id:"watch",label:"Watch",path:["ui","watch"],kind:"object"},{id:"meetings",label:"Meetings",path:null,kind:"object",keys:["meetingWindowMin","liveNotesIntervalMin","alertSound","meetingSummaryStyle","meetingAutoOpen"]},{id:"monitors",label:"Live monitors",path:["ui","monitors"],kind:"object"},{id:"redaction",label:"Redaction (client-side)",path:["ui","piiRedaction"],kind:"object"},{id:"internalSites",label:"Internal sites",path:["privacy"],kind:"object"},{id:"pageActions",label:"Act on page",path:null,kind:"object",browserOnly:!0,keys:["pageActions","pageActionsCdp","pageActionsDevJs","pageActionConfirm","pageSites"]},{id:"webllm",label:"In-browser model",path:null,kind:"object",browserOnly:!0,keys:["webllmBackground"],rootKeys:["webllmCustomModels"]}]),f=Object.freeze(c.map(t=>t.id)),m=Object.freeze(c.filter(t=>!t.browserOnly).map(t=>t.id));function g(t){return c.find(o=>o.id===t)}const s=t=>t===void 0?void 0:JSON.parse(JSON.stringify(t));function h(t,o){let e=t;for(const i of o){if(!e||typeof e!="object")return;e=e[i]}return e}function k(t,o,e){let i=t;for(let a=0;a<o.length-1;a+=1){const r=o[a];(!i[r]||typeof i[r]!="object")&&(i[r]={}),i=i[r]}i[o[o.length-1]]=e}function y(t,o){const e=c.find(n=>n.id===o);if(!e||!t)return;if(e.path)return s(h(t,e.path));const i=t.ui||{},a={};let r=!1;for(const n of e.keys||[])i[n]!==void 0&&(a[n]=s(i[n]),r=!0);for(const n of e.rootKeys||[])t[n]!==void 0&&(a[n]=s(t[n]),r=!0);return r?a:void 0}function j(t){const o={};for(const e of c){const i=y(t,e.id);i!==void 0&&(o[e.id]=i)}return o}function S(t,o){const e=s(t||{})||{};for(const[i,a]of Object.entries(o||{})){const r=c.find(n=>n.id===i);if(!(!r||a===void 0)){if(r.path){k(e,r.path,s(a));continue}(!e.ui||typeof e.ui!="object")&&(e.ui={});for(const n of r.keys||[])a&&a[n]!==void 0&&(e.ui[n]=s(a[n]));for(const n of r.rootKeys||[])a&&a[n]!==void 0&&(e[n]=s(a[n]))}}return e}function b(t){const o=e=>Array.isArray(e)?e.map(o):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(i=>[i,o(e[i])])):e;try{return JSON.stringify(o(t))}catch{return String(t)}}function A(t={},o={}){const e={},i=[],a=[],r=new Set([...Object.keys(t||{}),...Object.keys(o||{})]);for(const n of r){const l=t?.[n],d=o?.[n],u=Number(l?.updatedAt)||0,p=Number(d?.updatedAt)||0;if(d&&(!l||p>u)){e[n]={value:s(d.value),updatedAt:p},(!l||b(l.value)!==b(d.value))&&i.push(n);continue}l&&(e[n]={value:s(l.value),updatedAt:u},(!d||u>p)&&a.push(n))}return{merged:e,fromRemote:i,fromLocal:a}}function O(t,o={},{now:e=Date.now()}={}){const i={};for(const[a,r]of Object.entries(t||{})){if(!f.includes(a))continue;const n=o?.[a];n&&n.hash===b(r)||(i[a]={value:s(r),updatedAt:e})}return i}export{m as DESKTOP_SECTION_IDS,c as PREF_SECTIONS,f as PREF_SECTION_IDS,S as applySections,O as changedSections,A as mergeStamped,j as pickSections,b as sectionHash,g as sectionSpec,y as sectionValue};
1
+ const c=Object.freeze([{id:"mcpServers",label:"MCP tool servers",path:["mcpServers"],kind:"array"},{id:"mcpAuth",label:"MCP sign-ins",path:["mcpAuth"],kind:"object"},{id:"skills",label:"Skills",path:["skills"],kind:"array"},{id:"skillDirs",label:"Skill folders",path:["ui","skillDirs"],kind:"array"},{id:"recipes",label:"Recipes",path:["recipes"],kind:"array"},{id:"teams",label:"Teams",path:["teams"],kind:"array"},{id:"agents",label:"Agents",path:["agentPool"],kind:"array"},{id:"connections",label:"Connections",path:["connections"],kind:"array"},{id:"projects",label:"Projects",path:["projects"],kind:"array"},{id:"webSearch",label:"Web search",path:["ui","webSearch"],kind:"object"},{id:"tools",label:"Tools",path:null,kind:"object",keys:["mcpToolsMode","maxToolsPerTurn","maxToolRoundsPerTurn","historyTools","historyContextMode","dataDispatch","toolResultMaxChars","turn"]},{id:"endpoints",label:"Models",path:["endpoints"],kind:"array"},{id:"agentTools",label:"Coding Agents",path:null,kind:"object",rootKeys:["agents","removedBuiltinAgents"]},{id:"freeSlots",label:"Free plan picks",path:null,kind:"object",rootKeys:["freeEndpointId","freeAgentId"]},{id:"routing",label:"Model routing",path:["ui","routing"],kind:"object"},{id:"capabilityUses",label:"Where models may be used",path:["ui","capabilityUses"],kind:"object"},{id:"general",label:"General",path:null,kind:"object",keys:["theme","language","sendOnEnter","streamResponses","autoAttachActiveTab","autocomplete","settingsView"]},{id:"identity",label:"Identity",path:null,kind:"object",rootKeys:["selfName"]},{id:"suggestions",label:"Smart suggestions",path:["ui","suggestions"],kind:"object"},{id:"topics",label:"Topic extraction",path:["ui","topicExtraction"],kind:"object"},{id:"memory",label:"Memory",path:["ui","memory"],kind:"object"},{id:"notes",label:"Notes",path:["ui","notes"],kind:"object"},{id:"speech",label:"Speech",path:null,kind:"object",keys:["dictation","capture","scribeLive"]},{id:"warmSearch",label:"Gateway search index",path:["ui","warmSearch"],kind:"object"},{id:"recall",label:"Search & indexing",path:["ui","recall"],kind:"object"},{id:"voice",label:"Voice",path:["ui","voice"],kind:"object"},{id:"watch",label:"Watch",path:["ui","watch"],kind:"object"},{id:"meetings",label:"Meetings",path:null,kind:"object",keys:["meetingWindowMin","liveNotesIntervalMin","alertSound","meetingSummaryStyle","meetingAutoOpen"]},{id:"monitors",label:"Live monitors",path:["ui","monitors"],kind:"object"},{id:"redaction",label:"Redaction (client-side)",path:["ui","piiRedaction"],kind:"object"},{id:"internalSites",label:"Internal sites",path:["privacy"],kind:"object"},{id:"pageActions",label:"Act on page",path:null,kind:"object",browserOnly:!0,keys:["pageActions","pageActionsCdp","pageActionsDevJs","pageActionConfirm","pageSites"]},{id:"webllm",label:"In-browser model",path:null,kind:"object",browserOnly:!0,keys:["webllmBackground"],rootKeys:["webllmCustomModels"]}]),f=Object.freeze(c.map(t=>t.id)),m=Object.freeze(c.filter(t=>!t.browserOnly).map(t=>t.id));function g(t){return c.find(o=>o.id===t)}const s=t=>t===void 0?void 0:JSON.parse(JSON.stringify(t));function h(t,o){let e=t;for(const i of o){if(!e||typeof e!="object")return;e=e[i]}return e}function k(t,o,e){let i=t;for(let a=0;a<o.length-1;a+=1){const r=o[a];(!i[r]||typeof i[r]!="object")&&(i[r]={}),i=i[r]}i[o[o.length-1]]=e}function y(t,o){const e=c.find(n=>n.id===o);if(!e||!t)return;if(e.path)return s(h(t,e.path));const i=t.ui||{},a={};let r=!1;for(const n of e.keys||[])i[n]!==void 0&&(a[n]=s(i[n]),r=!0);for(const n of e.rootKeys||[])t[n]!==void 0&&(a[n]=s(t[n]),r=!0);return r?a:void 0}function j(t){const o={};for(const e of c){const i=y(t,e.id);i!==void 0&&(o[e.id]=i)}return o}function S(t,o){const e=s(t||{})||{};for(const[i,a]of Object.entries(o||{})){const r=c.find(n=>n.id===i);if(!(!r||a===void 0)){if(r.path){k(e,r.path,s(a));continue}(!e.ui||typeof e.ui!="object")&&(e.ui={});for(const n of r.keys||[])a&&a[n]!==void 0&&(e.ui[n]=s(a[n]));for(const n of r.rootKeys||[])a&&a[n]!==void 0&&(e[n]=s(a[n]))}}return e}function b(t){const o=e=>Array.isArray(e)?e.map(o):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(i=>[i,o(e[i])])):e;try{return JSON.stringify(o(t))}catch{return String(t)}}function A(t={},o={}){const e={},i=[],a=[],r=new Set([...Object.keys(t||{}),...Object.keys(o||{})]);for(const n of r){const l=t?.[n],d=o?.[n],u=Number(l?.updatedAt)||0,p=Number(d?.updatedAt)||0;if(d&&(!l||p>u)){e[n]={value:s(d.value),updatedAt:p},(!l||b(l.value)!==b(d.value))&&i.push(n);continue}l&&(e[n]={value:s(l.value),updatedAt:u},(!d||u>p)&&a.push(n))}return{merged:e,fromRemote:i,fromLocal:a}}function O(t,o={},{now:e=Date.now()}={}){const i={};for(const[a,r]of Object.entries(t||{})){if(!f.includes(a))continue;const n=o?.[a];n&&n.hash===b(r)||(i[a]={value:s(r),updatedAt:e})}return i}export{m as DESKTOP_SECTION_IDS,c as PREF_SECTIONS,f as PREF_SECTION_IDS,S as applySections,O as changedSections,A as mergeStamped,j as pickSections,b as sectionHash,g as sectionSpec,y as sectionValue};
package/compaction.js CHANGED
@@ -1,11 +1,13 @@
1
- import{keepRecentFor as m}from"./context-window.js";const g="You compress a conversation into a compact but COMPLETE summary for continuation. Preserve: the user’s goals, key facts, decisions made, current task/automation state, open questions, and specifics needed to keep going. Terse bullet points. No preamble.",f=4e3;function a(e=[]){return(Array.isArray(e)?e:[]).filter(t=>t&&!t.pending&&(t.role==="user"||t.role==="assistant")&&(t.content||t.attachments?.length))}function y({messages:e=[],keepRecent:t=4,budget:n=0,tokensOf:o=null}={}){const r=a(e);let i=Math.max(1,Math.floor(Number(t)||4));if(n>0&&typeof o=="function")for(;i>1&&r.slice(r.length-i).reduce((c,p)=>c+(o(p)||0),0)>n;)i-=1;if(r.length<=i+1)return null;const s=r.slice(0,r.length-i),l=r.slice(r.length-i),u=s.map(c=>`${c.role==="user"?"User":"Assistant"}: ${String(c.content||"").slice(0,f)}`).join(`
1
+ import{keepRecentFor as p}from"./context-window.js";const g="You compress a conversation into a compact but COMPLETE summary for continuation. Preserve: the user’s goals, key facts, decisions made, current task/automation state, open questions, and specifics needed to keep going. Terse bullet points. No preamble.",h=4e3;function c(e=[]){return(Array.isArray(e)?e:[]).filter(n=>n&&!n.pending&&(n.role==="user"||n.role==="assistant")&&(n.content||n.attachments?.length))}function x({messages:e=[],keepRecent:n=4,budget:t=0,tokensOf:o=null}={}){const r=c(e);let i=Math.max(1,Math.floor(Number(n)||4));if(t>0&&typeof o=="function")for(;i>1&&r.slice(r.length-i).reduce((a,m)=>a+(o(m)||0),0)>t;)i-=1;if(r.length<=i+1)return null;const s=r.slice(0,r.length-i),l=r.slice(r.length-i),u=s.map(a=>`${a.role==="user"?"User":"Assistant"}: ${String(a.content||"").slice(0,h)}`).join(`
2
2
 
3
- `);return{fold:s,keep:l,uptoId:s[s.length-1].id,transcript:u}}function x({transcript:e="",previousSummary:t=""}={}){return`${t?`Earlier summary to fold in:
4
- ${t}
3
+ `);return{fold:s,keep:l,uptoId:s[s.length-1].id,transcript:u}}function y({window:e=0,reasoning:n=!1}={}){const t=Number(e)||0,o=t?Math.min(1200,Math.max(256,Math.round(t/10))):1200,r=n?t?Math.min(4096,Math.max(1024,Math.round(t*.25))):2048:0,i=o+r,s=t?Math.max(512,Math.floor(t*.9)-i-300):0;return{summaryTokens:o,maxTokens:i,transcriptTokens:s}}function M(e="",n=0){const t=String(e||""),o=Math.max(0,Number(n)||0)*4;return!o||t.length<=o?t:`(earlier messages are in the earlier summary)
4
+
5
+ ${t.slice(t.length-o).replace(/^[^\n]*\n/,"")}`}function S({transcript:e="",previousSummary:n=""}={}){return`${n?`Earlier summary to fold in:
6
+ ${n}
5
7
 
6
8
  `:""}Summarize the conversation so far:
7
9
 
8
- ${e}`}function S({summary:e,uptoId:t,now:n=Date.now()}={}){return{summary:String(e||"").trim(),uptoId:t,ts:n}}function A(e=[],t=null){const n=a(e);if(!t?.uptoId)return n;const o=n.findIndex(r=>r.id===t.uptoId);return o>=0?n.slice(o+1):n}function E(e="",t=null){const n=String(t?.summary||"").trim();return n?`${e?`${e}
10
+ ${e}`}function k({summary:e,uptoId:n,now:t=Date.now()}={}){return{summary:String(e||"").trim(),uptoId:n,ts:t}}function A(e=[],n=null){const t=c(e);if(!n?.uptoId)return t;const o=t.findIndex(r=>r.id===n.uptoId);return o>=0?t.slice(o+1):t}function E(e="",n=null){const t=String(n?.summary||"").trim();return t?`${e?`${e}
9
11
 
10
12
  `:""}[Summary of the earlier part of this conversation — continue seamlessly; do not mention this summary]
11
- ${n}`:e||""}const d=36e4;function k(e=[],{maxChars:t=d}={}){const n=Array.isArray(e)?e:[];let o=0,r=n.length;for(;r>0;){const i=String(n[r-1]?.content??"").length+16;if(o+i>t&&r<n.length)break;o+=i,r-=1}return{kept:n.slice(r),elided:r}}export{g as COMPACTION_SYSTEM,d as SEED_MAX_CHARS,a as compactable,x as compactionPrompt,S as compactionRecord,m as keepRecentFor,A as messagesAfter,y as planCompaction,k as seedWithin,E as systemWithSummary};
13
+ ${t}`:e||""}const f=36e4;function $(e=[],{maxChars:n=f}={}){const t=Array.isArray(e)?e:[];let o=0,r=t.length;for(;r>0;){const i=String(t[r-1]?.content??"").length+16;if(o+i>n&&r<t.length)break;o+=i,r-=1}return{kept:t.slice(r),elided:r}}export{g as COMPACTION_SYSTEM,f as SEED_MAX_CHARS,M as boundTranscript,c as compactable,y as compactionBudget,S as compactionPrompt,k as compactionRecord,p as keepRecentFor,A as messagesAfter,x as planCompaction,$ as seedWithin,E as systemWithSummary};
package/context-window.js CHANGED
@@ -1 +1 @@
1
- const d=[[/^apple-on-device$|apple[-_ ]?foundation/,4096],[/gemini-?nano/,4096]],l=[[/gpt-4\.1/,1e6],[/gpt-5|o3|o4|o1/,2e5],[/gpt-4o|gpt-4-turbo/,128e3],[/claude-(3|4|5|opus|sonnet|haiku|fable)/,2e5],[/gemini-(1\.5|2|2\.5|3)/,1e6],[/gemini/,1e6],[/deepseek/,128e3],[/mistral-large|mixtral|codestral/,128e3],[/grok/,128e3],[/llama-3\.[1-3]|llama-4/,128e3]];function x(n={},t=null){const e=String(n.id||""),r=String(n.model||n.id||"").toLowerCase(),c=t&&(t[a(n)]||t[r]||t[String(n.model||"")]||(n.gateway?0:t[e]));if(Number(c)>0)return Number(c);const i=Number(n.window||n.contextLength||n.contextWindow||0);if(i>0)return i;for(const[o,u]of d)if(o.test(r))return u;if(n.reach==="device"||n.kind==="webllm")return 0;for(const[o,u]of l)if(o.test(r))return u;return 0}function a(n={}){const t=String(n.id||""),e=String(n.model||"");return e?`${t}:${e}`:t}const s=.85,f=8192,p=n=>Number(n)>0&&Number(n)<=f,w=2;function _({promptTokens:n=0,floorTokens:t=0,window:e=0,reserve:r=1024,headroom:c=s}={}){const i=Number(e)||0;if(!i)return{status:"unknown",budget:0,over:0,window:0};const o=Math.max(0,Math.floor(i*c)-Math.max(0,Number(r)||0)),u=Math.max(0,Number(n)||0),m=Math.max(0,Number(t)||0);return u<=o?{status:"ok",budget:o,over:0,window:i}:m<=o?{status:"compact",budget:o,over:u-o,window:i}:{status:"too-big",budget:o,over:m-o,window:i}}function b(n=0){const t=Number(n)||0;return t?t<=8e3?2:t<=32768?4:t<=128e3?8:12:4}function h({floorTokens:n=0,reserve:t=1024,headroom:e=s}={}){const r=Math.max(0,Number(n)||0);return r?Math.ceil((r+Math.max(0,Number(t)||0))/e):0}function N(n){return/context.{0,8}(length|window|size)|context_length_exceeded|prompt is too long|too many tokens|maximum context|exceed.{0,20}context|reduce the (length|number|size)|input is too long|token limit|n_ctx|kv cache|longer than .{0,80}\bwindow\b|exceed.{0,30}\bwindow\b/i.test(String(n?.message||n||""))}export{s as FIT_HEADROOM,f as SMALL_WINDOW,w as SMALL_WINDOW_ROUNDS,_ as fitFor,N as isContextLimitError,p as isSmallWindow,b as keepRecentFor,h as minWindowFor,a as observedKey,x as windowOf};
1
+ const a=[[/^apple-on-device$|apple[-_ ]?foundation/,4096],[/gemini-?nano/,4096]],d=[[/gpt-4\.1/,1e6],[/gpt-5|o3|o4|o1/,2e5],[/gpt-4o|gpt-4-turbo/,128e3],[/claude-(3|4|5|opus|sonnet|haiku|fable)/,2e5],[/gemini-(1\.5|2|2\.5|3)/,1e6],[/gemini/,1e6],[/deepseek/,128e3],[/mistral-large|mixtral|codestral/,128e3],[/grok/,128e3],[/llama-3\.[1-3]|llama-4/,128e3]];function x(t={},n=null){const r=String(t.id||""),e=String(t.model||t.id||"").toLowerCase(),u=n&&(n[l(t)]||n[e]||n[String(t.model||"")]||(t.gateway?0:n[r]));if(Number(u)>0)return Number(u);const i=Number(t.window||t.contextLength||t.contextWindow||0);if(i>0)return i;for(const[o,c]of a)if(o.test(e))return c;if(t.reach==="device"||t.kind==="webllm")return 0;for(const[o,c]of d)if(o.test(e))return c;return 0}function l(t={}){const n=String(t.id||""),r=String(t.model||"");return r?`${n}:${r}`:n}const m=.85,f=8192,p=t=>Number(t)>0&&Number(t)<=f,w=2;function _({promptTokens:t=0,floorTokens:n=0,window:r=0,reserve:e=1024,headroom:u=m}={}){const i=Number(r)||0;if(!i)return{status:"unknown",budget:0,over:0,window:0};const o=Math.max(0,Math.floor(i*u)-Math.max(0,Number(e)||0)),c=Math.max(0,Number(t)||0),s=Math.max(0,Number(n)||0);return c<=o?{status:"ok",budget:o,over:0,window:i}:s<=o?{status:"compact",budget:o,over:c-o,window:i}:{status:"too-big",budget:o,over:s-o,window:i}}function h({maxTokens:t=0,window:n=0,reasoning:r=!1}={}){const e=Math.max(0,Number(t)||0);if(!r)return e||1024;const u=Number(n)||0,i=u?Math.min(8192,Math.max(2048,Math.round(u*.3))):4096;return Math.max(e,i)}function b(t=0){const n=Number(t)||0;return n?n<=8e3?2:n<=32768?4:n<=128e3?8:12:4}function N({floorTokens:t=0,reserve:n=1024,headroom:r=m}={}){const e=Math.max(0,Number(t)||0);return e?Math.ceil((e+Math.max(0,Number(n)||0))/r):0}function g(t){return/context.{0,8}(length|window|size)|context_length_exceeded|prompt is too long|too many tokens|maximum context|exceed.{0,20}context|reduce the (length|number|size)|input is too long|token limit|n_ctx|kv cache|longer than .{0,80}\bwindow\b|exceed.{0,30}\bwindow\b/i.test(String(t?.message||t||""))}export{m as FIT_HEADROOM,f as SMALL_WINDOW,w as SMALL_WINDOW_ROUNDS,h as answerReserve,_ as fitFor,g as isContextLimitError,p as isSmallWindow,b as keepRecentFor,N as minWindowFor,l as observedKey,x as windowOf};
package/decide-ask.js ADDED
@@ -0,0 +1 @@
1
+ import{DECIDE_QUESTION_TYPES as y}from"./capability-endpoints.js";const m=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,p=Object.freeze(["instructions","question","ask","prompt"]),g=["options","choices","labels"],b=new Set(["noul","yesno","yes/no","yes_no","boolean","bool","binary"]),S=["input","text","state","passage","content","message"];function h(n){const i={};return(Array.isArray(n)?n:n&&typeof n=="object"&&!p.some(t=>typeof n[t]=="string")&&Object.values(n).every(t=>t&&typeof t=="object")?Object.entries(n).map(([t,u])=>({key:t,...u})):n&&typeof n=="object"?[n]:[]).forEach((t,u)=>{if(!t||typeof t!="object")return;let c=String(t.key||"").trim();(!m.test(c)||i[c])&&(c=`q${u+1}`);const o=String(p.map(e=>t[e]).find(e=>typeof e=="string"&&e.trim())||"").trim(),s=(g.map(e=>t[e]).find(Array.isArray)||[]).map(e=>e&&typeof e=="object"?e.value??e.label??"":e).map(e=>String(e)),a=String(t.type||"").trim().toLowerCase(),l=y.includes(a)?a:b.has(a)?"noul":s.length?"choice":"noul",f={type:l,instructions:o};l!=="noul"&&s.length&&(f.options=s),i[c]=f}),i}function j(n){const i=String(n??"").trim();if(!i.startsWith("{")||!i.endsWith("}")||i.length>7e4)return null;let r;try{r=JSON.parse(i)}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;const t=S.map(o=>r[o]).find(o=>typeof o=="string"&&o.trim());if(!t)return null;const u=h(r.questions??(p.some(o=>typeof r[o]=="string")?r:null)),c=Object.values(u);if(!c.length)return null;for(const o of c){if(!o.instructions)return null;if(o.type==="noul")continue;const s=o.options||[];if(s.length<2||s.length>255||new Set(s).size!==s.length||s.some(a=>!a.trim()))return null}return{text:t.trim(),questions:u}}export{p as QUESTION_WORDS,h as questionsToWire,j as structuredAskOf};
package/fast-path.js CHANGED
@@ -1,8 +1,8 @@
1
- const _=/\b(extract|list|find|pull( out)?|identify|get|show( me)?|give me|what are|who are|which)\b/i,T=/\b(names?|people|persons?|person names?|places?|locations?|cities|countries|emails?|e-mails?|email addresses|phone numbers?|phones?|addresses|organi[sz]ations?|companies|company names|entities|named entities|pii|personal (data|information|info)|account numbers?|credit cards?|secrets?|passwords?)\b/i,P=/\b(in|from|of)\s+(this|that|these|the|the following|below|above|here|it)\b|:\s*$|\n/i,j=/\b(explain|why|how|summari[sz]e|summary|rewrite|translate|describe|analy[sz]e|compare|tell me about|what does|what do|opinion|think)\b/i,k=[["PERSON",/\b(names?|people|persons?)\b/i],["LOCATION",/\b(places?|locations?|cities|countries)\b/i],["ADDRESS",/\baddresses\b/i],["EMAIL",/\be-?mails?\b|email addresses/i],["PHONE",/\bphones?\b|phone numbers?/i],["ORG",/\borgani[sz]ations?|compan(y|ies)\b/i],["ID",/\baccount numbers?\b/i],["CREDITCARD",/\bcredit cards?\b/i],["SECRET",/\bsecrets?|passwords?\b/i]],v=k.map(([i])=>i),M=/\b(sentiment|tone)\b|\b(is|was) (this|that|it|the)( (review|message|email|comment|feedback|text|ticket|post|reply))?\s+(positive|negative|happy|angry|a complaint|spam|urgent|toxic|offensive|abusive)\b/i,q=[[/\bspam\b/i,{spam:{type:"noul",instructions:"Is this message spam or unsolicited promotion?"}}],[/\burgent\b/i,{urgent:{type:"noul",instructions:"Does this convey urgency — something that needs attention now?"}}],[/\ba complaint\b/i,{complaint:{type:"noul",instructions:"Is the writer complaining about a product, a service or an experience?"}}],[/\b(toxic|offensive|abusive)\b/i,{toxic:{type:"noul",instructions:"Is this text toxic, offensive or abusive?"}}]];function F(i){for(const[r,t]of q)if(r.test(i))return t;return{sentiment:{type:"choice",instructions:"The overall sentiment of the text.",options:["positive","negative","neutral","mixed"]}}}const z=/^(?:please\s+)?(?:classify|categori[sz]e|label|tag|bucket|triage|sort|file)\b.*?\b(?:as|into|under|between|among|(?:to\s+)?one of)\s+(.+)$/i,B=/^(?:which|what)\s+(category|label|type|kind|class|bucket|topic|department|team|priority|intent|language|genre)\b(?:\s+(?:is|does|fits|best fits|describes)\s+(?:this|it|that)(?:\s+\w+)?)?\s*[,:—–-]?\s*(.+)$/i,H=/(?:this|it|that|the)(?:\s+(?:review|message|email|e-mail|comment|feedback|text|ticket|post|reply|request|issue|document|page|article|note|transcript|one))?/.source,U=new RegExp(`^(?:is|was)\\s+${H}\\s+(?:about\\s+|a\\s+|an\\s+)?(.+?\\bor\\b.+)$`,"i"),G=20;function Q(i){const t=String(i||"").replace(/^(?:one of)?\s*:?\s*/i,"").replace(/[?.!]+\s*$/,"").split(/\s*(?:,|\/|\||\bor\b)\s*/i).map(o=>o.trim().replace(/^["'“‘]|["'”’]$/g,"").replace(/^(?:a|an|the)\s+/i,"").trim()).filter(Boolean),s=new Set,e=[];for(const o of t){const l=o.toLowerCase();if(!s.has(l)){if(o.length>40||o.split(/\s+/).length>5)return null;s.add(l),e.push(o)}}return e.length>=2&&e.length<=G?e:null}function X(i){const r=String(i||"").trim();let t="label",s=null,e=z.exec(r);if(e?s=e[1]:(e=B.exec(r))&&/\bor\b|,|\//.test(e[2])?(t=e[1].toLowerCase(),s=e[2].replace(/^(?:is|does|fits|best fits|describes)\s+(?:this|it|that)(?:\s+\w+)?\s*[,:—–-]?\s*/i,"")):(e=U.exec(r))&&(s=e[1]),!s)return null;const o=Q(s);return o?{[t]:{type:"choice",instructions:`Which of these ${t==="label"?"labels":`${t} values`} best describes the text?`,options:o}}:null}function J(i){const r=String(i||""),t=/^(.*?)\n\s*\n([\s\S]{20,})$/s.exec(r);if(t&&!/\n\s*\n/.test(t[1]))return{instruction:t[1].trim(),inline:t[2].trim()};const s=/^(.*?)(?::\s*|\n\s*\n)([\s\S]{20,})$/s.exec(r);if(s)return{instruction:s[1].trim(),inline:s[2].trim()};const e=/^(.*?)["“]([\s\S]{20,})["”]\s*$/s.exec(r);return e?{instruction:e[1].trim(),inline:e[2].trim()}:{instruction:r.trim(),inline:""}}function K(i,{material:r="",providers:t={}}={}){const{instruction:s,inline:e}=J(i),o=e||String(r||"");if(!o||o.trim().length<20||j.test(s)||s.length>240)return null;if(t.detect&&_.test(s)&&T.test(s)&&(e||P.test(i)||r)){const c=k.filter(([,p])=>p.test(s)).map(([p])=>p),a=!c.length||/\b(entities|named entities|pii|personal (data|information|info))\b/i.test(s);return{capability:"detect",families:a?v:c,text:o,reason:`an extraction of ${a?"entities":c.join(", ").toLowerCase()} over ${e?"the pasted text":"the material"}`}}const l=t.decide?X(s):null;if(l){const c=Object.keys(l)[0];return{capability:"decide",question:l,text:o,reason:`a choice of ${c} among ${l[c].options.length} labels over the material`}}if(t.decide&&M.test(s)){const c=F(s),a=Object.keys(c)[0];return{capability:"decide",question:c,text:o,reason:`a ${a==="sentiment"?"sentiment":a} judgement over the material`}}return null}const A={PERSON:"People",LOCATION:"Places",ADDRESS:"Addresses",EMAIL:"Emails",PHONE:"Phone numbers",ORG:"Organisations",ID:"Identifiers",CREDITCARD:"Card numbers",SECRET:"Secrets",SSN:"National IDs",IBAN:"IBANs"};function V(i,r,t={}){const s=new Set(i.families),e=new Map;for(const n of r||[]){if(!n?.value||!s.has(n.type))continue;e.has(n.type)||e.set(n.type,[]);const u=e.get(n.type);u.some(g=>g.toLowerCase()===n.value.toLowerCase())||u.push(n.value)}const o=[];for(const n of i.families){const u=e.get(n);u?.length&&o.push(`**${A[n]||n}** (${u.length}): ${u.join(", ")}`)}const l=i.families.length===v.length?"entities":i.families.map(n=>(A[n]||n).toLowerCase()).join(", "),c=o.length?o.join(`
2
- `):`No ${l} found in the text (${i.text.length} characters checked).`,a=t.models?.length?t.models.join(" + "):"the local detector",p=t.where||"this device",m=typeof t.ms=="number"?` in ${t.ms} ms`:"";return`${c}
1
+ import{structuredAskOf as P}from"./decide-ask.js";const q=/\b(extract|list|find|pull( out)?|identify|get|show( me)?|give me|what are|who are|which)\b/i,j=/\b(names?|people|persons?|person names?|places?|locations?|cities|countries|emails?|e-mails?|email addresses|phone numbers?|phones?|addresses|organi[sz]ations?|companies|company names|entities|named entities|pii|personal (data|information|info)|account numbers?|credit cards?|secrets?|passwords?)\b/i,M=/\b(in|from|of)\s+(this|that|these|the|the following|below|above|here|it)\b|:\s*$|\n/i,F=/\b(explain|why|how|summari[sz]e|summary|rewrite|translate|describe|analy[sz]e|compare|tell me about|what does|what do|opinion|think)\b/i,I=[["PERSON",/\b(names?|people|persons?)\b/i],["LOCATION",/\b(places?|locations?|cities|countries)\b/i],["ADDRESS",/\baddresses\b/i],["EMAIL",/\be-?mails?\b|email addresses/i],["PHONE",/\bphones?\b|phone numbers?/i],["ORG",/\borgani[sz]ations?|compan(y|ies)\b/i],["ID",/\baccount numbers?\b/i],["CREDITCARD",/\bcredit cards?\b/i],["SECRET",/\bsecrets?|passwords?\b/i]],O=I.map(([o])=>o),A=/\b(sentiment|tone)\b|\b(is|was) (this|that|it|the)( (review|message|email|comment|feedback|text|ticket|post|reply))?\s+(positive|negative|happy|angry|a complaint|spam|urgent|toxic|offensive|abusive)\b/i,z=[[/\bspam\b/i,{spam:{type:"noul",instructions:"Is this message spam or unsolicited promotion?"}}],[/\burgent\b/i,{urgent:{type:"noul",instructions:"Does this convey urgency — something that needs attention now?"}}],[/\ba complaint\b/i,{complaint:{type:"noul",instructions:"Is the writer complaining about a product, a service or an experience?"}}],[/\b(toxic|offensive|abusive)\b/i,{toxic:{type:"noul",instructions:"Is this text toxic, offensive or abusive?"}}]];function B(o){for(const[r,t]of z)if(r.test(o))return t;return{sentiment:{type:"choice",instructions:"The overall sentiment of the text.",options:["positive","negative","neutral","mixed"]}}}const H=/^(?:please\s+)?(?:classify|categori[sz]e|label|tag|bucket|triage|sort|file)\b.*?\b(?:as|into|under|between|among|(?:to\s+)?one of)\s+(.+)$/i,U=/^(?:which|what)\s+(category|label|type|kind|class|bucket|topic|department|team|priority|intent|language|genre)\b(?:\s+(?:is|does|fits|best fits|describes)\s+(?:this|it|that)(?:\s+\w+)?)?\s*[,:—–-]?\s*(.+)$/i,G=/(?:this|it|that|the)(?:\s+(?:review|message|email|e-mail|comment|feedback|text|ticket|post|reply|request|issue|document|page|article|note|transcript|one))?/.source,Q=new RegExp(`^(?:is|was)\\s+${G}\\s+(?:about\\s+|a\\s+|an\\s+)?(.+?\\bor\\b.+)$`,"i"),X=20;function v(o){const t=String(o||"").replace(/^(?:one of)?\s*:?\s*/i,"").replace(/[?.!]+\s*$/,"").split(/\s*(?:,|\/|\||\bor\b)\s*/i).map(i=>i.trim().replace(/^["'“‘]|["'”’]$/g,"").replace(/^(?:a|an|the)\s+/i,"").trim()).filter(Boolean),s=new Set,e=[];for(const i of t){const u=i.toLowerCase();if(!s.has(u)){if(i.length>40||i.split(/\s+/).length>5)return null;s.add(u),e.push(i)}}return e.length>=2&&e.length<=X?e:null}const W=/(?:^|[\s.;!?])(?:options|choices|labels|categories|pick one of|choose from|one of)\s*[:=]\s*([^\n]{3,400}?)\s*\.?\s*$/i;function J(o){const r=String(o||"").trim();let t="label",s=null,e=H.exec(r);if(e?s=e[1]:(e=U.exec(r))&&/\bor\b|,|\//.test(e[2])?(t=e[1].toLowerCase(),s=e[2].replace(/^(?:is|does|fits|best fits|describes)\s+(?:this|it|that)(?:\s+\w+)?\s*[,:—–-]?\s*/i,"")):(e=Q.exec(r))&&(s=e[1]),!s)return null;const i=v(s);return i?{[t]:{type:"choice",instructions:`Which of these ${t==="label"?"labels":`${t} values`} best describes the text?`,options:i}}:null}function K(o){const r=String(o||""),t=/^(.*?)\n\s*\n([\s\S]{20,})$/s.exec(r);if(t&&!/\n\s*\n/.test(t[1]))return{instruction:t[1].trim(),inline:t[2].trim()};const s=/^(.*?)(?::\s*|\n\s*\n)([\s\S]{20,})$/s.exec(r);if(s)return{instruction:s[1].trim(),inline:s[2].trim()};const e=/^(.*?)["“]([\s\S]{20,})["”]\s*$/s.exec(r);return e?{instruction:e[1].trim(),inline:e[2].trim()}:{instruction:r.trim(),inline:""}}function V(o,{material:r="",providers:t={}}={}){if(t.decide){const a=P(o);if(a){const l=Object.keys(a.questions).length;return{capability:"decide",question:a.questions,text:a.text,reason:l===1?"a classification written out — the text, the question and its options":`${l} classifications written out over one text`}}}const{instruction:s,inline:e}=K(o),i=e||String(r||"");if(!i||i.trim().length<20||F.test(s)||s.length>240)return null;if(t.detect&&q.test(s)&&j.test(s)&&(e||M.test(o)||r)){const a=I.filter(([,n])=>n.test(s)).map(([n])=>n),l=!a.length||/\b(entities|named entities|pii|personal (data|information|info))\b/i.test(s);return{capability:"detect",families:l?O:a,text:i,reason:`an extraction of ${l?"entities":a.join(", ").toLowerCase()} over ${e?"the pasted text":"the material"}`}}const u=t.decide?W.exec(i):null,d=u?v(u[1]):null;if(d&&i.slice(0,u.index).trim()){const a=A.test(s)?"sentiment":"label";return{capability:"decide",question:{[a]:{type:"choice",instructions:/^(?:which|what|who|is|are|does|do|should|how|where)\b/i.test(s)?`${s.replace(/[\s:?]+$/,"")}?`:a==="sentiment"?"The overall sentiment of the text.":"Which of these labels best describes the text?",options:d}},text:i.slice(0,u.index).trim(),reason:`a choice among the ${d.length} labels listed with the text`}}const c=t.decide?J(s):null;if(c){const a=Object.keys(c)[0];return{capability:"decide",question:c,text:i,reason:`a choice of ${a} among ${c[a].options.length} labels over the material`}}if(t.decide&&A.test(s)){const a=B(s),l=Object.keys(a)[0];return{capability:"decide",question:a,text:i,reason:`a ${l==="sentiment"?"sentiment":l} judgement over the material`}}return null}const C={PERSON:"People",LOCATION:"Places",ADDRESS:"Addresses",EMAIL:"Emails",PHONE:"Phone numbers",ORG:"Organisations",ID:"Identifiers",CREDITCARD:"Card numbers",SECRET:"Secrets",SSN:"National IDs",IBAN:"IBANs"};function Y(o,r,t={}){const s=new Set(o.families),e=new Map;for(const n of r||[]){if(!n?.value||!s.has(n.type))continue;e.has(n.type)||e.set(n.type,[]);const m=e.get(n.type);m.some(g=>g.toLowerCase()===n.value.toLowerCase())||m.push(n.value)}const i=[];for(const n of o.families){const m=e.get(n);m?.length&&i.push(`**${C[n]||n}** (${m.length}): ${m.join(", ")}`)}const u=o.families.length===O.length?"entities":o.families.map(n=>(C[n]||n).toLowerCase()).join(", "),d=i.length?i.join(`
2
+ `):`No ${u} found in the text (${o.text.length} characters checked).`,c=t.models?.length?t.models.join(" + "):"the local detector",a=t.where||"this device",l=typeof t.ms=="number"?` in ${t.ms} ms`:"";return`${d}
3
3
 
4
- _Answered by ${a} on ${p}${m} — entity detection, no language model._`}function W(i,r,t={}){const s=Object.keys(i.question)[0],e=r?.[s];if(!e)return null;const o=n=>`${Math.round((n||0)*100)}%`,l=typeof e.value=="boolean"?e.value?"yes":"no":e.value,c=typeof e.value=="boolean"?"":(e.options||[]).filter(n=>n.value!==e.value).sort((n,u)=>u.p-n.p).slice(0,2).map(n=>`${n.value} ${o(n.p)}`).join(", "),a=t.models?.length?t.models.map(n=>String(n).split("/").pop()).join(" + "):"the local decision model",p=typeof t.ms=="number"?` in ${t.ms} ms`:"",m=t.calibrated===!1?" The percentage is the model’s preference, not a calibrated probability.":"";return`**${s}: ${l}** (${o(e.p)}${c?`; ${c}`:""})
4
+ _Answered by ${c} on ${a}${l} — entity detection, no language model._`}function Z(o,r,t={}){const s=Object.keys(o.question)[0],e=r?.[s];if(!e)return null;const i=n=>`${Math.round((n||0)*100)}%`,u=typeof e.value=="boolean"?e.value?"yes":"no":e.value,d=typeof e.value=="boolean"?"":(e.options||[]).filter(n=>n.value!==e.value).sort((n,m)=>m.p-n.p).slice(0,2).map(n=>`${n.value} ${i(n.p)}`).join(", "),c=t.models?.length?t.models.map(n=>String(n).split("/").pop()).join(" + "):"the local decision model",a=typeof t.ms=="number"?` in ${t.ms} ms`:"",l=t.calibrated===!1?" The percentage is the model’s preference, not a calibrated probability.":"";return`**${s}: ${u}** (${i(e.p)}${d?`; ${d}`:""})
5
5
 
6
- _Answered by ${a} on ${t.where||"this device"}${p} — a typed decision, no language model.${m}_`}async function Y({prompt:i,material:r="",providers:t={},fetch:s,normalizeEntities:e,id:o="turn",enabled:l=!0}={}){if(l===!1)return null;const c={detect:(t.detect||[]).length>0,decide:(t.decide||[]).length>0},a=K(i,{material:r,providers:c});if(!a)return null;const[{assign:p,describePlan:m},{createExecutor:n},{capabilitySource:u,capabilityRunners:g}]=await Promise.all([import("./plan.js"),import("./plan-executor.js"),import("./capability-providers.js")]),C=a.capability==="detect"?{id:"extract",kind:"detect",title:a.reason,input:{from:"material"},requires:{maxLatencyMs:5e3},fallback:"skip"}:{id:"judge",kind:"decide",title:a.reason,input:{from:"material"},questions:a.question,requires:{maxLatencyMs:5e3},fallback:"skip"};let b;try{b=p({id:`fast-${o}`,origin:"chat",goal:i,steps:[C]},{capability:u(t)})}catch{return null}if(b.unassignable.length||b.steps[0].assigned?.skipped)return null;const O=n({runners:g({fetch:s,normalizeEntities:e})});let y;try{y=await O.run(b,{goal:i,material:a.text})}catch{return null}const d=y.steps[0];if(d.status!=="done"||!d.output)return null;const h=Math.round(d.cost?.ms||0),f=m(y);if(a.capability==="detect"){const{entities:S,models:I,where:N,provider:D}=d.output;return{capability:"detect",content:`${V(a,S,{models:I,ms:h,where:N})}
7
- _Plan: ${f}_`,provider:D,models:I,ms:h,reason:a.reason,plan:f,entities:S}}const{answers:w,models:$,where:L,provider:R,calibrated:x}=d.output,E=W(a,w,{models:$,ms:h,where:L,calibrated:x});return E?{capability:"decide",content:`${E}
8
- _Plan: ${f}_`,provider:R,models:$,ms:h,reason:a.reason,plan:f,answers:w,calibrated:x}:null}export{X as choiceQuestionFor,F as decideQuestionFor,K as fastPathFor,W as renderDecideAnswer,V as renderDetectAnswer,Y as runFastPath,J as splitPrompt};
6
+ _Answered by ${c} on ${t.where||"this device"}${a} — a typed decision, no language model.${l}_`}async function te({prompt:o,material:r="",providers:t={},fetch:s,normalizeEntities:e,id:i="turn",enabled:u=!0}={}){if(u===!1)return null;const d={detect:(t.detect||[]).length>0,decide:(t.decide||[]).length>0},c=V(o,{material:r,providers:d});if(!c)return null;const[{assign:a,describePlan:l},{createExecutor:n},{capabilitySource:m,capabilityRunners:g}]=await Promise.all([import("./plan.js"),import("./plan-executor.js"),import("./capability-providers.js")]),R=c.capability==="detect"?{id:"extract",kind:"detect",title:c.reason,input:{from:"material"},requires:{maxLatencyMs:5e3},fallback:"skip"}:{id:"judge",kind:"decide",title:c.reason,input:{from:"material"},questions:c.question,requires:{maxLatencyMs:5e3},fallback:"skip"};let h;try{h=a({id:`fast-${i}`,origin:"chat",goal:o,steps:[R]},{capability:m(t)})}catch{return null}if(h.unassignable.length||h.steps[0].assigned?.skipped)return null;const L=n({runners:g({fetch:s,normalizeEntities:e})});let y;try{y=await L.run(h,{goal:o,material:c.text})}catch{return null}const p=y.steps[0];if(p.status!=="done"||!p.output)return null;const b=Math.round(p.cost?.ms||0),f=l(y);if(c.capability==="detect"){const{entities:S,models:k,where:_,provider:D}=p.output;return{capability:"detect",content:`${Y(c,S,{models:k,ms:b,where:_})}
7
+ _Plan: ${f}_`,provider:D,models:k,ms:b,reason:c.reason,plan:f,entities:S}}const{answers:w,models:$,where:N,provider:T,calibrated:x}=p.output,E=Z(c,w,{models:$,ms:b,where:N,calibrated:x});return E?{capability:"decide",content:`${E}
8
+ _Plan: ${f}_`,provider:T,models:$,ms:b,reason:c.reason,plan:f,answers:w,calibrated:x}:null}export{J as choiceQuestionFor,B as decideQuestionFor,V as fastPathFor,Z as renderDecideAnswer,Y as renderDetectAnswer,te as runFastPath,K as splitPrompt};
package/gateway-dests.js CHANGED
@@ -1 +1 @@
1
- function l(t){const o=new URL(/^https?:\/\//.test(t)?t:`http://${t}`);return`${o.hostname.replace(/^\[|\]$/g,"")}:${o.port||(o.protocol==="https:"?"443":"80")}`}function u(t,o){try{return!!o&&l(t)===l(o)}catch{return!1}}function f(t){return!t||!t.baseUrl?null:{id:t.name||t.model||t.id,type:"api",baseUrl:t.baseUrl,protocol:t.kind==="anthropic"?"anthropic":"openai",models:[t.model].filter(Boolean),...t.apiKey?{apiKey:t.apiKey}:{}}}function c(t){return{id:t,type:"agent",agent:t,models:[t]}}function p({endpoints:t=[],agentIds:o=[],gatewayUrl:r=""}={}){const s=[];for(const n of t){if(!n||n.builtin||!n.baseUrl||n.enabled===!1||u(n.baseUrl,r))continue;const i=f(n);i&&s.push(i)}for(const n of o)n&&s.push(c(n));return s}function d(t,{pro:o=!1,cap:r=1,preferId:s=""}={}){const n=Array.isArray(t)?t.filter(Boolean):[];if(!n.length)return[];if(o)return n;const i=s&&n.find(e=>e.id===s)||n[0];return n.slice(0,Math.max(0,r-1)).includes(i)?n.slice(0,Math.max(1,r)):[i,...n.filter(e=>e!==i)].slice(0,Math.max(1,r))}function h({current:t=[],seeded:o=!1,available:r=[]}={}){return!o&&!(t||[]).length&&(r||[]).length>0}function m(t=[],o=[],{gatewayUrl:r=""}={}){const s=p({endpoints:o,gatewayUrl:r}),n=new Map(s.map(e=>[e.id,e])),i=[];for(const e of t||[]){if(!e)continue;const a=n.get(e.id);a?(i.push({...e,...a,...a.apiKey?{}:e.apiKey?{apiKey:e.apiKey}:{}}),n.delete(e.id)):i.push(e)}for(const e of n.values())i.push(e);return i}export{p as availableDestinations,c as destinationFromAgent,f as destinationFromEndpoint,m as mergeEndpointDestinations,u as pointsAtGateway,d as seedDestinations,h as shouldSeedDestinations};
1
+ function f(t){const o=new URL(/^https?:\/\//.test(t)?t:`http://${t}`);return`${o.hostname.replace(/^\[|\]$/g,"")}:${o.port||(o.protocol==="https:"?"443":"80")}`}function u(t,o){try{return!!o&&f(t)===f(o)}catch{return!1}}function l(t){return!t||!t.baseUrl?null:{id:t.name||t.model||t.id,type:"api",baseUrl:t.baseUrl,protocol:t.kind==="anthropic"?"anthropic":"openai",models:[t.model].filter(Boolean),...t.apiKey?{apiKey:t.apiKey}:{},fromEndpoint:!0}}function c(t){return{id:t,type:"agent",agent:t,models:[t]}}function p({endpoints:t=[],agentIds:o=[],gatewayUrl:r=""}={}){const s=[];for(const n of t){if(!n||n.builtin||!n.baseUrl||n.enabled===!1||u(n.baseUrl,r))continue;const i=l(n);i&&s.push(i)}for(const n of o)n&&s.push(c(n));return s}function d(t,{pro:o=!1,cap:r=1,preferId:s=""}={}){const n=Array.isArray(t)?t.filter(Boolean):[];if(!n.length)return[];if(o)return n;const i=s&&n.find(e=>e.id===s)||n[0];return n.slice(0,Math.max(0,r-1)).includes(i)?n.slice(0,Math.max(1,r)):[i,...n.filter(e=>e!==i)].slice(0,Math.max(1,r))}function h({current:t=[],seeded:o=!1,available:r=[]}={}){return!o&&!(t||[]).length&&(r||[]).length>0}function m(t=[],o=[],{gatewayUrl:r=""}={}){const s=p({endpoints:o,gatewayUrl:r}),n=new Map(s.map(e=>[e.id,e])),i=[];for(const e of t||[]){if(!e)continue;const a=n.get(e.id);a?(i.push({...e,...a,...a.apiKey?{}:e.apiKey?{apiKey:e.apiKey}:{}}),n.delete(e.id)):e.fromEndpoint||i.push(e)}for(const e of n.values())i.push(e);return i}export{p as availableDestinations,c as destinationFromAgent,l as destinationFromEndpoint,m as mergeEndpointDestinations,u as pointsAtGateway,d as seedDestinations,h as shouldSeedDestinations};
package/history-search.js CHANGED
@@ -1,8 +1,9 @@
1
- import{bm25Search as A,buildGraph as E,buildIndex as H,tokenize as M,topTerms as F}from"./text-index.js";import{withoutOwnInstructions as $}from"./own-instructions.js";const C=1800,b=220,R=new Set("chat chats history source sources search result results local previous prior past meeting meetings meet meets call calls transcript transcripts recording recordings conversation conversations discuss discussed discussing find show list had have".split(/\s+/));function h(t){return String(t||"").replace(/\s+/g," ").trim()}function m(t,n,e,s){const i=Number(t);return Number.isFinite(i)?Math.max(e,Math.min(s,Math.floor(i))):n}function j(t){return String(t||"").toLowerCase()==="exact"?"exact":"best"}function y(t){const n=String(t||"").toLowerCase();return n==="title"||n==="name"?"title":n==="content"||n==="body"||n==="text"||n==="transcript"?"content":"all"}function w(t,n,e){const s=n==="meetings"||n==="chats"||n==="notes"?n:"all";return(t||[]).filter(i=>!e&&i.type==="meeting"?!1:s==="meetings"?i.type==="meeting":s==="chats"?i.type==="chat":s==="notes"?i.type==="note":i.type==="chat"||i.type==="meeting"||i.type==="note")}function g(t,{maxChunkChars:n=C,overlapChars:e=b}={}){const s=h($(t?.text));if(!t?.id||!t?.type||!s)return[];const i=m(n,C,400,8e3),c=m(e,b,0,Math.floor(i/2)),o=[];let r=0,a=0;for(;r<s.length;){let u=Math.min(s.length,r+i);if(u<s.length){const f=s.lastIndexOf(" ",u);f>r+Math.floor(i*.6)&&(u=f)}const l=s.slice(r,u).trim();if(l&&(o.push({id:`${t.id}#${a}`,sourceId:t.id,chunk:a,type:t.type,title:t.title||(t.type==="meeting"?"Meeting":t.type==="note"?"Note":"Chat"),date:t.date||0,text:l,url:t.url||"",meta:t.meta||{}}),a+=1),u>=s.length)break;r=Math.max(0,u-c)}return o}function et(t,n={}){return(t||[]).flatMap(e=>g(e,n))}function N(t,n){return y(n)==="content"&&t&&t.contentText!=null?{...t,text:t.contentText}:t}function T(t,n={},e="all"){return(t||[]).flatMap(s=>g(N(s,e),n))}function L(t){return/\b(?:1\s*[:x]\s*1|1\s*[-\s]*(?:on|to)\s*[-\s]*1|one\s*[-\s]*on\s*[-\s]*one|one\s*[-\s]*to\s*[-\s]*one)\b/i.test(String(t||""))}function D(t){return{terms:[...new Set(M(t).filter(e=>!R.has(e)))],directMeeting:L(t)}}function k(t,n){const e=String(n||"").toLowerCase();let s=0;for(const i of t||[])e.includes(i)&&(s+=1);return s}const O=16,v=12;function B(t,n){const e=n?.get(t);return e==null?1.5:e<=.15?.15:Math.min(e,3)}function P(t,n,e,s){if(!t||s==="content"||!n?.length)return 0;const i=String(t.title||"").toLowerCase(),c=Array.isArray(t.meta?.people)?t.meta.people.join(" ").toLowerCase():"";let o=0;for(const r of n){const a=B(r,e);i.includes(r)&&(o+=a*O),c&&c.includes(r)&&(o+=a*v)}return o}function z(t,n,e){if(!t||t.type!=="meeting"||e==="content")return 0;const s=n?.terms||[];if(!s.length&&!n?.directMeeting)return 0;const i=String(t.title||""),c=Array.isArray(t.meta?.people)?t.meta.people:[],o=c.join(" "),r=k(s,i),a=k(s,o);let u=r*45+a*28;return n?.directMeeting&&(L(i)&&(u+=80),r&&(u+=35),a&&(u+=25),a&&c.length>0&&c.length<=2&&(u+=70)),u}function _(t,n){const e=(t||[]).filter(l=>l?.sourceId).sort((l,f)=>f.score-l.score||(f.date||0)-(l.date||0)),s=e[0]?.score||0,i=s>0?s*.5:0,c=[],o=[],r=[],a=new Set,u=new Set;for(const l of e)a.has(l.sourceId)?u.has(l.sourceId)?r.push(l):o.push(l):(a.add(l.sourceId),l.score>=i?c.push(l):(u.add(l.sourceId),r.push(l)));return[...c,...o,...r].slice(0,n).map((l,f)=>({...l,rank:f+1}))}const q=45,U=.3;function Y(t,n=Date.now()){if(!t)return 1;const e=Math.max(0,(n-t)/864e5);return 1+U*Math.exp(-e/q)}function W(t,n={}){const e=w(t,n.scope||"all",n.includeMeetings!==!1),s=y(n.field),i=T(e,n,s),c=s==="title"?I(e,n).map(r=>({id:r.id,text:r.title})):i.map(r=>({id:r.id,text:s==="content"?r.text:`${r.title}
2
- ${r.text}`})),o=new Map(i.map(r=>[r.id,r]));for(const r of I(e,n))o.set(r.id,r);return{idx:H(c),byId:o,field:s}}function G(t,n,e={}){const s=m(e.limit,8,1,30),i=h(n);if(!i||!t?.idx)return[];const{idx:c,byId:o,field:r}=t,a=i.toLowerCase(),u=M(a),l=D(i),f=A(c,i).map(x=>{const p=o.get(x.id);let d=x.score;const S=String(p?.title||"").toLowerCase();return r!=="content"&&(S===a?d+=80:S.includes(a)&&(d+=50)),d+=P(p,u,c.idf,r),d+=z(p,l,r),e.recency&&(d*=Y(p?.date,e.now)),{...p,score:d}});return _(f,s)}function nt(t,n,e={}){const s=j(e.mode),i=h(n);if(!i)return[];if(s==="exact"){const c=w(t,e.scope||"all",e.includeMeetings!==!1);return K(c,i,{...e,field:y(e.field),limit:m(e.limit,8,1,30)})}return G(W(t,e),n,e)}function I(t,n={}){return(t||[]).map(e=>g(e,n)[0]).filter(Boolean)}function K(t,n,e={}){const s=y(e.field),i=n.toLowerCase(),c=[];if(s==="title")for(const o of t||[]){const r=h(o?.title).toLowerCase();if(!r.includes(i))continue;const a=g(o,e)[0];a&&c.push({...a,score:r===i?1e3:800})}else if(s==="content")for(const o of T(t,e,"content"))h(o.text).toLowerCase().includes(i)&&c.push({...o,score:500});else for(const o of t||[]){const r=h(o?.title).toLowerCase();if(r.includes(i)){const a=g(o,e)[0];a&&c.push({...a,score:r===i?1e3:800});continue}for(const a of g(o,e))h(a.text).toLowerCase().includes(i)&&c.push({...a,score:500})}return _(c,e.limit)}function Q(t){return String(t?.text||"").split(/\r?\n/).map(n=>{let e=n.trim();return!e||/^(agent|date|platform)\s*:/i.test(e)?"":/^(chat|meeting|summary|transcript)\s*:/i.test(e)?e.replace(/^[^:]+:\s*/i,""):(e=e.replace(/^---\s*[^-]+---$/i,""),e=e.replace(/^\[[^\]]+\]\s*[^:]{1,60}:\s*/i,""),e=e.replace(/^(user|assistant|system|you|speaker(?:\s*[-_#]?\s*\d+)?|[A-Z][\w .'’-]{0,40})\s*:\s*/i,""),e=e.replace(/^attached\s*:\s*/i,""),e)}).join(`
1
+ import{bm25Search as A,buildGraph as H,buildIndex as E,tokenize as M,topTerms as F}from"./text-index.js";import{withoutOwnInstructions as $}from"./own-instructions.js";const b=1800,C=220,R=new Set("chat chats history source sources search result results local previous prior past meeting meetings meet meets call calls transcript transcripts recording recordings conversation conversations discuss discussed discussing find show list had have".split(/\s+/));function h(t){return String(t||"").replace(/\s+/g," ").trim()}function m(t,n,e,i){const s=Number(t);return Number.isFinite(s)?Math.max(e,Math.min(i,Math.floor(s))):n}function j(t){return String(t||"").toLowerCase()==="exact"?"exact":"best"}function y(t){const n=String(t||"").toLowerCase();return n==="title"||n==="name"?"title":n==="content"||n==="body"||n==="text"||n==="transcript"?"content":"all"}function w(t,n,e){const i=n==="meetings"||n==="chats"||n==="notes"?n:"all";return(t||[]).filter(s=>!e&&s.type==="meeting"?!1:i==="meetings"?s.type==="meeting":i==="chats"?s.type==="chat":i==="notes"?s.type==="note":s.type==="chat"||s.type==="meeting"||s.type==="note")}function g(t,{maxChunkChars:n=b,overlapChars:e=C}={}){const i=h($(t?.text));if(!t?.id||!t?.type||!i)return[];const s=m(n,b,400,8e3),c=m(e,C,0,Math.floor(s/2)),o=[];let r=0,a=0;for(;r<i.length;){let u=Math.min(i.length,r+s);if(u<i.length){const f=i.lastIndexOf(" ",u);f>r+Math.floor(s*.6)&&(u=f)}const l=i.slice(r,u).trim();if(l&&(o.push({id:`${t.id}#${a}`,sourceId:t.id,chunk:a,type:t.type,title:t.title||(t.type==="meeting"?"Meeting":t.type==="note"?"Note":"Chat"),date:t.date||0,text:l,url:t.url||"",meta:t.meta||{}}),a+=1),u>=i.length)break;r=Math.max(0,u-c)}return o}function et(t,n={}){return(t||[]).flatMap(e=>g(e,n))}function N(t,n){return y(n)==="content"&&t&&t.contentText!=null?{...t,text:t.contentText}:t}function T(t,n={},e="all"){return(t||[]).flatMap(i=>g(N(i,e),n))}function L(t){return/\b(?:1\s*[:x]\s*1|1\s*[-\s]*(?:on|to)\s*[-\s]*1|one\s*[-\s]*on\s*[-\s]*one|one\s*[-\s]*to\s*[-\s]*one)\b/i.test(String(t||""))}function D(t){return{terms:[...new Set(M(t).filter(e=>!R.has(e)))],directMeeting:L(t)}}function k(t,n){const e=String(n||"").toLowerCase();let i=0;for(const s of t||[])e.includes(s)&&(i+=1);return i}const O=16,v=12;function B(t,n){const e=n?.get(t);return e==null?1.5:e<=.15?.15:Math.min(e,3)}function P(t,n,e,i){if(!t||i==="content"||!n?.length)return 0;const s=String(t.title||"").toLowerCase(),c=Array.isArray(t.meta?.people)?t.meta.people.join(" ").toLowerCase():"";let o=0;for(const r of n){const a=B(r,e);s.includes(r)&&(o+=a*O),c&&c.includes(r)&&(o+=a*v)}return o}function q(t,n,e){if(!t||t.type!=="meeting"||e==="content")return 0;const i=n?.terms||[];if(!i.length&&!n?.directMeeting)return 0;const s=String(t.title||""),c=Array.isArray(t.meta?.people)?t.meta.people:[],o=c.join(" "),r=k(i,s),a=k(i,o);let u=r*45+a*28;return n?.directMeeting&&(L(s)&&(u+=80),r&&(u+=35),a&&(u+=25),a&&c.length>0&&c.length<=2&&(u+=70)),u}function I(t,n){const e=(t||[]).filter(l=>l?.sourceId).sort((l,f)=>f.score-l.score||(f.date||0)-(l.date||0)),i=e[0]?.score||0,s=i>0?i*.5:0,c=[],o=[],r=[],a=new Set,u=new Set;for(const l of e)a.has(l.sourceId)?u.has(l.sourceId)?r.push(l):o.push(l):(a.add(l.sourceId),l.score>=s?c.push(l):(u.add(l.sourceId),r.push(l)));return[...c,...o,...r].slice(0,n).map((l,f)=>({...l,rank:f+1}))}const z=45,U=.3;function Y(t,n=Date.now()){if(!t)return 1;const e=Math.max(0,(n-t)/864e5);return 1+U*Math.exp(-e/z)}function W(t,n={}){const e=w(t,n.scope||"all",n.includeMeetings!==!1),i=y(n.field),s=T(e,n,i),c=i==="title"?_(e,n).map(r=>({id:r.id,text:r.title})):s.map(r=>({id:r.id,text:i==="content"?r.text:`${r.title}
2
+ ${r.text}`})),o=new Map(s.map(r=>[r.id,r]));for(const r of _(e,n))o.set(r.id,r);return{idx:E(c),byId:o,field:i}}function G(t,n,e={}){const i=m(e.limit,8,1,30),s=h(n);if(!s||!t?.idx)return[];const{idx:c,byId:o,field:r}=t,a=s.toLowerCase(),u=M(a),l=D(s),f=A(c,s).map(x=>{const p=o.get(x.id);let d=x.score;const S=String(p?.title||"").toLowerCase();return r!=="content"&&(S===a?d+=80:S.includes(a)&&(d+=50)),d+=P(p,u,c.idf,r),d+=q(p,l,r),e.recency&&(d*=Y(p?.date,e.now)),{...p,score:d}});return I(f,i)}function nt(t,n,e={}){const i=j(e.mode),s=h(n);if(!s)return[];if(i==="exact"){const c=w(t,e.scope||"all",e.includeMeetings!==!1);return K(c,s,{...e,field:y(e.field),limit:m(e.limit,8,1,30)})}return G(W(t,e),n,e)}function _(t,n={}){return(t||[]).map(e=>g(e,n)[0]).filter(Boolean)}function K(t,n,e={}){const i=y(e.field),s=n.toLowerCase(),c=[];if(i==="title")for(const o of t||[]){const r=h(o?.title).toLowerCase();if(!r.includes(s))continue;const a=g(o,e)[0];a&&c.push({...a,score:r===s?1e3:800})}else if(i==="content")for(const o of T(t,e,"content"))h(o.text).toLowerCase().includes(s)&&c.push({...o,score:500});else for(const o of t||[]){const r=h(o?.title).toLowerCase();if(r.includes(s)){const a=g(o,e)[0];a&&c.push({...a,score:r===s?1e3:800});continue}for(const a of g(o,e))h(a.text).toLowerCase().includes(s)&&c.push({...a,score:500})}return I(c,e.limit)}function Q(t){return String(t?.text||"").split(/\r?\n/).map(n=>{let e=n.trim();return!e||/^(agent|date|platform)\s*:/i.test(e)?"":/^(chat|meeting|summary|transcript)\s*:/i.test(e)?e.replace(/^[^:]+:\s*/i,""):(e=e.replace(/^---\s*[^-]+---$/i,""),e=e.replace(/^\[[^\]]+\]\s*[^:]{1,60}:\s*/i,""),e=e.replace(/^(user|assistant|system|you|speaker(?:\s*[-_#]?\s*\d+)?|[A-Z][\w .'’-]{0,40})\s*:\s*/i,""),e=e.replace(/^attached\s*:\s*/i,""),e)}).join(`
3
3
  `)}function V(t){return Array.isArray(t?.meta?.terms)&&t.meta.terms.length?t.meta.terms:F(`${t?.title||""}
4
- ${Q(t)}`,10)}function X(t){const n=t.sharedPeople||[],e=t.sharedTopics||[],s=t.sharedTitleTerms||[],i=[];return n.length&&i.push(`shares ${n.join(", ")}`),e.length&&i.push(`shared topics: ${e.join(", ")}`),s.length&&i.push(`similar title: ${s.join(", ")}`),i.join(" · ")||`relationship score ${t.weight||0}`}function rt(t,n,e={}){const s=m(e.limit,8,1,30),i=w(t,e.scope||"all",e.includeMeetings!==!1),c=new Map(i.map(r=>[r.id,r]));return c.has(n)?E(i.map(r=>({id:r.id,title:r.title||r.id,platform:r.meta?.platform||r.type,startedAt:r.date||0,people:[],terms:V(r)}))).relatedMeetings(n,{limit:s}).map(r=>{const a=c.get(r.id),u=r.sharedPeople||[];return{sourceId:r.id,type:a?.type||"",title:a?.title||r.id,date:a?.date||0,url:a?.url||"",weight:r.weight,shared:u,reason:X(r)}}):[]}function Z(t,{query:n="",maxChars:e=12e3}={}){const s=m(e,12e3,1e3,5e4),i=[`History search results for: ${n||"(no query)"}`,'These are truncated excerpts, not the records. Before reporting details (action items, decisions, who said what, dates), read the full record: history_get_meeting with a meeting: id, history_get_source with any other id. Cite labels inline with <sup>[1]</sup> and add a bottom "Sources" list with labels/links/IDs.',""];let c=i.join(`
5
- `).length;for(const o of t||[]){const r=`[${o.sourceId}#${o.chunk}] ${o.title||o.sourceId}`,a=o.date?` · ${new Date(o.date).toLocaleString()}`:"",u=Number.isFinite(o.score)?` · score ${o.score.toFixed(2)}`:"",l=o.url?` · Open: [Open in Chap](${o.url})`:"",f=`${r}${a}${u}${l}`,x=s<=1200?Math.min(120,Math.max(80,s-c-f.length-80)):Math.max(240,s-c-f.length-80),p=o.text.length>x?`${o.text.slice(0,x).trim()}...`:o.text,d=`${f}
4
+ ${Q(t)}`,10)}function X(t){const n=t.sharedPeople||[],e=t.sharedTopics||[],i=t.sharedTitleTerms||[],s=[];return n.length&&s.push(`shares ${n.join(", ")}`),e.length&&s.push(`shared topics: ${e.join(", ")}`),i.length&&s.push(`similar title: ${i.join(", ")}`),s.join(" · ")||`relationship score ${t.weight||0}`}function rt(t,n,e={}){const i=m(e.limit,8,1,30),s=w(t,e.scope||"all",e.includeMeetings!==!1),c=new Map(s.map(r=>[r.id,r]));return c.has(n)?H(s.map(r=>({id:r.id,title:r.title||r.id,platform:r.meta?.platform||r.type,startedAt:r.date||0,people:[],terms:V(r)}))).relatedMeetings(n,{limit:i}).map(r=>{const a=c.get(r.id),u=r.sharedPeople||[];return{sourceId:r.id,type:a?.type||"",title:a?.title||r.id,date:a?.date||0,url:a?.url||"",weight:r.weight,shared:u,reason:X(r)}}):[]}function Z(t,{query:n="",maxChars:e=12e3}={}){const i=m(e,12e3,1e3,5e4);if(!(t||[]).length)return[`History search results for: ${n||"(no query)"}`,"","No matching local history sources were found.","Nothing in the user's own history matches, and rewording will not find what is not there. If the question was about the user's own records, say nothing was found; if it is general knowledge, answer it; if it needs facts from outside, search the web."].join(`
5
+ `);const s=[`History search results for: ${n||"(no query)"}`,'These are truncated excerpts, not the records. Before reporting details (action items, decisions, who said what, dates), read the full record: history_get_meeting with a meeting: id, history_get_source with any other id. Cite labels inline with <sup>[1]</sup> and add a bottom "Sources" list with labels/links/IDs.',""];let c=s.join(`
6
+ `).length;for(const o of t||[]){const r=`[${o.sourceId}#${o.chunk}] ${o.title||o.sourceId}`,a=o.date?` · ${new Date(o.date).toLocaleString()}`:"",u=Number.isFinite(o.score)?` · score ${o.score.toFixed(2)}`:"",l=o.url?` · Open: [Open in Chap](${o.url})`:"",f=`${r}${a}${u}${l}`,x=i<=1200?Math.min(120,Math.max(80,i-c-f.length-80)):Math.max(240,i-c-f.length-80),p=o.text.length>x?`${o.text.slice(0,x).trim()}...`:o.text,d=`${f}
6
7
  ${p}
7
- `;if(c+d.length>s&&i.length>3||(i.push(d),c+=d.length,c>=s))break}return(t||[]).length===0&&i.push("No matching local history sources were found."),i.join(`
8
- `).trim()}function it(t,n,e={}){const s=new Set((n||[]).map(c=>c.sourceId)).size,i=Z(n,{query:t,maxChars:e.maxChars});return{id:`history_rag_${Date.now()}`,kind:"history-rag",title:`History search · ${s} source${s===1?"":"s"}`,text:i,chars:i.length}}function st(t,n,{maxChars:e=2e4}={}){const s=(t||[]).find(a=>a.id===n);if(!s)return{sourceId:n,found:!1,text:""};const i=m(e,2e4,1e3,1e5),c=h($(s.text)),o=c.length>i,r=o?`${c.slice(0,i).trim()}...`:c;return{sourceId:n,type:s.type,title:s.title||n,date:s.date||0,url:s.url||"",found:!0,truncated:o,text:r}}export{et as buildHistoryChunks,it as buildHistoryRagAttachment,W as buildSearchIndex,g as chunkHistorySource,Z as formatHistoryResults,st as getHistorySource,rt as relatedHistorySources,G as runSearch,nt as searchHistorySources};
8
+ `;if(c+d.length>i&&s.length>3||(s.push(d),c+=d.length,c>=i))break}return s.join(`
9
+ `).trim()}function it(t,n,e={}){const i=new Set((n||[]).map(c=>c.sourceId)).size,s=Z(n,{query:t,maxChars:e.maxChars});return{id:`history_rag_${Date.now()}`,kind:"history-rag",title:`History search · ${i} source${i===1?"":"s"}`,text:s,chars:s.length}}function st(t,n,{maxChars:e=2e4}={}){const i=(t||[]).find(a=>a.id===n);if(!i)return{sourceId:n,found:!1,text:""};const s=m(e,2e4,1e3,1e5),c=h($(i.text)),o=c.length>s,r=o?`${c.slice(0,s).trim()}...`:c;return{sourceId:n,type:i.type,title:i.title||n,date:i.date||0,url:i.url||"",found:!0,truncated:o,text:r}}export{et as buildHistoryChunks,it as buildHistoryRagAttachment,W as buildSearchIndex,g as chunkHistorySource,Z as formatHistoryResults,st as getHistorySource,rt as relatedHistorySources,G as runSearch,nt as searchHistorySources};