@chatpanel/events 0.429.0 → 0.432.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.
- package/a2ui-catalog.js +2 -0
- package/a2ui-chart.js +1 -0
- package/a2ui-express.js +5 -0
- package/a2ui-html.js +1 -0
- package/a2ui-reply.js +11 -0
- package/a2ui-surface.js +1 -0
- package/a2ui-text.js +2 -0
- package/a2ui-tool-cards.js +12 -0
- package/endpoint-jobs.js +1 -1
- package/index.js +1 -1
- package/markdown-render.js +0 -0
- package/model-catalog.js +1 -1
- package/package.json +17 -1
- package/prefetch.js +6 -4
- package/settings-registry.js +1 -1
- package/turn-gather.js +1 -1
- package/turn-pipeline.js +1 -1
- package/weather-tool.js +6 -6
package/turn-pipeline.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
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,...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}
|
|
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}
|
|
3
3
|
|
|
4
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};
|
package/weather-tool.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{getWeather as
|
|
1
|
+
import{getWeather as d,isHere as w}from"./weather.js";import{namesSubject as p}from"./subject-match.js";import{weatherCard as y}from"./a2ui-tool-cards.js";const T="weather",g="For weather, call `weather` FIRST — it answers the whole question in one request. Only fall back to web_search if it tells you to. Report the location it says it resolved, because a bare town name can geocode to the wrong place.";function x({fetchJson:l,search:a=null}={}){if(typeof l!="function")throw new Error("weatherToolProvider: fetchJson required");return{specs:[{name:"weather",annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:"Current conditions and a short forecast for one place, in a single request. Use this for any weather question instead of searching. Returns the location it actually resolved to — say which place the answer is for.",parameters:{type:"object",properties:{location:{type:"string",description:'A place, as the user said it. Add a state or country only if THEY did — "Fairview, OR" if they said so, plain "Fairview" if they did not.'}},required:["location"],additionalProperties:!1}}],system:g,async execute(c,n){if(c!=="weather")return JSON.stringify({error:`Unknown tool: ${c}`});const h=String(n?.location||"").trim(),s=w(h)?"":h,o=await d(s,{fetchJson:l});if(!o.ok){const e=s||"my area";if(typeof a=="function"){const r=`weather in ${e}`,t=await Promise.resolve().then(()=>a(r)).catch(()=>null),u=typeof t=="string"?t:t?.text,f=b(u,{place:s});if(f)return{text:`Weather for "${e}", from a web search for "${r}" (the weather service did not know the place). Report it as the forecast for the place the sources name; say which place that is.
|
|
2
2
|
|
|
3
|
-
`+
|
|
4
|
-
`).filter(
|
|
5
|
-
`)){const r
|
|
6
|
-
`);return
|
|
3
|
+
`+f,note:"ChatPanel · web search"}}return`The weather service could not answer for "${e}" (${o.reason}). Now call web_search for "weather in ${e}" and answer from the results — do not tell the user a tool failed.`}const i=y(o.weather);return{text:o.text,note:"ChatPanel · wttr.in",...i?{card:{lang:"a2ui",source:i}}:{}}}}}const m=/(?:-?\d{1,3}\s?°|°\s?[FC]\b|\b(?:high|low|feels like|currently|tonight|today|tomorrow)\b.*\d|\b(?:rain|showers|snow|sunny|sun|cloud(?:y|s)?|overcast|fog|clear|storm|wind|humidity|breeze)\b)/i;function b(l,{maxChars:a=1600,place:c=""}={}){const n=String(l||"");if(!n.trim()||c&&!p(n,c))return"";const h=n.replace(/<svg[\s\S]*?<\/svg>/gi," ").replace(/<[^>]+>/g," ").replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\]\((?:https?:)?[^)]*\)/g,"]"),s=(/(?:^|\n)Sources:\n([\s\S]*?)(?:\n---|\n\n#|$)/.exec(n)?.[1]||"").split(`
|
|
4
|
+
`).filter(r=>/^\[\d+\]/.test(r.trim())).slice(0,5),o=new Set,i=[];for(const r of h.split(`
|
|
5
|
+
`)){const t=r.replace(/[\t ]+/g," ").replace(/^[\s\d.,#*[\]-]{0,6}/,"").trim();if(t.length<4||t.length>200||!m.test(t)||/citation rules|cite it inline|sources section/i.test(t))continue;const u=t.toLowerCase();o.has(u)||(o.add(u),i.push(`- ${t}`))}if(!i.some(r=>/\d\s?°|°\s?[FC]/.test(r)))return"";let e=i.join(`
|
|
6
|
+
`);return e.length>a&&(e=e.slice(0,a).replace(/\n[^\n]*$/,"")),s.length?`${e}
|
|
7
7
|
|
|
8
8
|
Sources:
|
|
9
9
|
${s.join(`
|
|
10
|
-
`)}`:
|
|
10
|
+
`)}`:e}export{T as WEATHER_TOOL_NAME,g as WEATHER_TOOL_SYSTEM,b as weatherFromSearch,x as weatherToolProvider};
|