@chatpanel/events 0.458.1 → 0.459.0

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