reasoning.run 0.1.2 → 0.2.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/dist/bundle.mjs +18 -18
- package/package.json +4 -4
package/dist/bundle.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)[0].trim();return n.length>72?n.slice(0,72).trimEnd()+"\u2026":n}function ot(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Mo(t,e){let n;try{n=JSON.parse(e)}catch{n={}}let r=typeof n.query=="string"?n.query:typeof n.pattern=="string"?n.pattern:typeof n.url=="string"?n.url:typeof n.filename=="string"?n.filename:"";return r?`"${r.length>48?r.slice(0,48)+"\u2026":r}"`:""}function _o(t,e){try{let r=JSON.parse(e);if(t==="web_search"&&Array.isArray(r)){let o=r,s=Array.from(new Set(o.map(a=>a.url?ot(a.url):"").filter(Boolean))).slice(0,3);return{summary:`${o.length} results`,hosts:s,resultCount:o.length,preview:o[0]?.title??null}}if(t==="search"&&Array.isArray(r)){let o=r;return{summary:`${o.length} results`,hosts:[],resultCount:o.length,preview:o[0]?.heading??null}}if(t==="grep"&&typeof r=="object"&&r!==null){let o=r;return{summary:`${o.totalMatches??0} matches`,hosts:[],resultCount:o.totalMatches??null,preview:null}}if(t==="fetch_page"&&typeof r=="object"&&r!==null){let o=r;if(o.error)return{summary:o.error,hosts:[],resultCount:null,preview:null};let s=o.url?[ot(o.url)]:[];return{summary:`${e.length}b`,hosts:s,resultCount:null,preview:o.title??null}}if(t==="web_fetch"&&typeof r=="object"&&r!==null){let o=r,s=o.url?[ot(o.url)]:[];return{summary:`${e.length}b`,hosts:s,resultCount:null,preview:o.title??null}}}catch{}let n=Array.from(e.matchAll(/https?:\/\/[^\s\])>"]+/g)).map(r=>r[0]);if(n.length>0){let r=Array.from(new Set(n.map(ot))).slice(0,3);return{summary:`${n.length} links`,hosts:r,resultCount:n.length,preview:null}}return{summary:`${e.length}b`,hosts:[],resultCount:null,preview:null}}function se(t,e,n){let r=t.agents.get(e);if(!r)return t;let o=new Map(t.agents);return o.set(e,n(r)),{...t,agents:o}}function Dn(t,e,n={}){if(t.agents.has(e))return t;let r={id:e,label:`A${t.nextLabelIdx}`,phase:"idle",tokenCount:0,toolCallCount:0,taskIndex:null,taskDescription:null,dependencyHint:null,currentThinkId:null,pendingToolCallId:null,contentBuffer:"",timeline:[],...n},o=new Map(t.agents);return o.set(e,r),{...t,agents:o,nextLabelIdx:t.nextLabelIdx+1}}function it(t,e){return{...t,timeline:[...t.timeline,e]}}function Nn(t,e,n){return{...t,timeline:t.timeline.map(r=>r.id===e?n(r):r)}}function qn(t,e){let n=t.nextTimelineId;return{...se(t,e,o=>it({...o,currentThinkId:n,phase:"thinking"},{kind:"think",id:n,title:"Thinking\u2026",body:"",live:!0,openedAt:Date.now(),closedAt:null})),nextTimelineId:t.nextTimelineId+1}}function st(t,e,n){let r=t.agents.get(e);if(!r||r.currentThinkId===null)return t;let o=r.currentThinkId,s=Io(n);return se(t,e,a=>Nn({...a,currentThinkId:null,phase:"content"},o,i=>i.kind==="think"?{...i,body:n,title:s,live:!1,closedAt:Date.now()}:i))}function Ot(t,e){switch(e.type){case"query":return{...rt,config:t.config,configOrigin:t.configOrigin,uiPhase:t.uiPhase,mode:t.mode,nextToastId:t.nextToastId,toast:t.toast,scrollback:t.scrollback,query:e.query,warm:e.warm,phase:"plan",startedAt:Date.now()};case"plan":return{...t,uiPhase:e.intent==="clarify"?"clarifying":t.uiPhase,phase:e.intent==="research"?"plan":"done",plan:{intent:e.intent,tasks:e.tasks,clarifyQuestions:e.clarifyQuestions,tokenCount:e.tokenCount,timeMs:e.timeMs},clarifyContext:e.intent==="clarify"?{originalQuery:t.query,questions:e.clarifyQuestions}:null};case"plan:task_updated":{if(!t.plan||e.index<0||e.index>=t.plan.tasks.length)return t;let n=t.plan.tasks.map((r,o)=>o===e.index?{...r,description:e.description}:r);return{...t,plan:{...t.plan,tasks:n}}}case"plan:task_added":{if(!t.plan)return t;let n=Math.max(0,Math.min(t.plan.tasks.length,e.afterIndex+1)),r=[...t.plan.tasks.slice(0,n),{description:""},...t.plan.tasks.slice(n)];return{...t,plan:{...t.plan,tasks:r}}}case"plan:task_deleted":{if(!t.plan||t.plan.tasks.length<=1||e.index<0||e.index>=t.plan.tasks.length)return t;let n=t.plan.tasks.filter((r,o)=>o!==e.index);return{...t,plan:{...t.plan,tasks:n}}}case"plan:task_moved":{if(!t.plan)return t;let n=t.plan.tasks.length;if(e.from===e.to||e.from<0||e.from>=n||e.to<0||e.to>=n)return t;let r=[...t.plan.tasks],[o]=r.splice(e.from,1);return r.splice(e.to,0,o),{...t,plan:{...t.plan,tasks:r}}}case"research:start":return{...t,uiPhase:"research",phase:"research",mode:e.mode==="flat"?"flat":"deep",pipelineResumedAt:Date.now()};case"research:done":return{...t,phase:"synth"};case"fanout:tasks":return t;case"spine:task":return{...t,pendingTaskIndex:e.taskIndex,pendingTaskDescription:e.description};case"spine:source":case"spine:task:done":return t;case"synthesize:start":return{...t,phase:"synth",synth:{open:!0,buffer:"",done:!1,stats:null}};case"synthesize:done":{let n=t.synth.buffer.trim(),r=n?[...t.scrollback,{key:`synth-${t.scrollback.length}-${Date.now()}`,kind:"synth",body:n}]:t.scrollback;return{...t,scrollback:r,synth:{...t.synth,open:!1,done:!0,stats:{tokens:e.tokenCount,toolCalls:e.toolCallCount,ppl:e.ppl,timeMs:e.timeMs}}}}case"answer":return{...t,answer:e.text};case"stats":return{...t,timings:e.timings,pressure:{pct:e.ctxPct,cellsUsed:e.ctxPos,nCtx:e.ctxTotal}};case"complete":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,phase:"done",uiPhase:"done",pipelineElapsedMs:n,pipelineResumedAt:null}}case"config:loaded":return{...t,config:e.config,configOrigin:e.origin};case"config:updated":{let n=t.nextToastId+1,r=e.skipped.length>0?`saved \u2192 ${_t(e.savedTo)} (skipped: ${e.skipped.join(", ")} \u2014 env active)`:e.gitignored?`saved \u2192 ${_t(e.savedTo)} (added to .gitignore)`:`saved \u2192 ${_t(e.savedTo)}`;return{...t,config:e.config,configOrigin:e.origin,toast:{id:n,message:r,tone:e.skipped.length>0?"warn":"success"},nextToastId:n}}case"plan:start":{let r=t.uiPhase==="composer"||t.uiPhase==="done"||t.uiPhase==="boot"?{pipelineElapsedMs:0,startedAt:Date.now()}:{};return{...t,...r,uiPhase:"planning",phase:"plan",plan:null,query:e.query,mode:e.mode==="flat"?"flat":"deep",pipelineResumedAt:Date.now()}}case"ui:composer":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,uiPhase:"composer",composerPrefill:e.prefill??"",clarifyContext:null,pipelineElapsedMs:n,pipelineResumedAt:null}}case"ui:plan_review":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,uiPhase:"plan_review",pipelineElapsedMs:n,pipelineResumedAt:null}}case"ui:error":{let n=t.nextToastId+1;return{...t,uiPhase:"composer",toast:{id:n,message:e.message,tone:"error"},nextToastId:n}}case"download:plan":return{...t,uiPhase:"downloading",downloads:e.entries.map(n=>({id:n.id,label:n.label,got:0,total:n.sizeBytes,done:!1,started:!1}))};case"download:start":return{...t,uiPhase:"downloading",downloads:t.downloads.map(n=>n.id===e.id?{...n,started:!0}:n)};case"download:progress":return{...t,downloads:t.downloads.map(n=>n.id===e.id?{...n,started:!0,got:e.got,total:e.total,url:e.url??n.url}:n)};case"download:complete":return{...t,downloads:t.downloads.map(n=>n.id===e.id?{...n,got:n.total||n.got,done:!0}:n)};case"weights:start":return{...t,uiPhase:"loading",loadingLabel:e.label};case"weights:label":return{...t,loadingLabel:e.label};case"weights:done":return{...t,loadingLabel:null};case"corpus:indexed":return{...t,corpusStatus:{fileCount:e.fileCount,chunkCount:e.chunkCount}};case"boot:error":return{...t,uiPhase:"boot_error",bootError:{kind:e.kind,message:e.message}};case"agent:spawn":{if(t.phase!=="research")return Dn(t,e.agentId,{phase:"idle",taskIndex:null});let n,r,o=t.pendingTaskIndex,s=t.pendingTaskDescription;t.mode==="deep"?(n=o??t.researchSpawnCount,r=s??t.plan?.tasks[n]?.description??null,o=null,s=null):(n=t.researchSpawnCount,r=t.plan?.tasks[n]?.description??null);let a=t.mode==="deep"&&n>0?`builds on Task ${n}`:null,i=Dn(t,e.agentId,{phase:"thinking",taskIndex:n,taskDescription:r,dependencyHint:a});return i={...i,researchAgentIds:[...i.researchAgentIds,e.agentId],researchSpawnCount:t.researchSpawnCount+1,pendingTaskIndex:o,pendingTaskDescription:s},qn(i,e.agentId)}case"agent:produce":{if(t.phase==="synth"&&t.synth.open)return{...t,synth:{...t.synth,buffer:t.synth.buffer+e.text}};if(t.phase!=="research")return t;let n=t.agents.get(e.agentId);if(!n||n.taskIndex===null)return t;let r=t,o=n;if(o.phase==="content")return se(r,o.id,w=>({...w,tokenCount:e.tokenCount,contentBuffer:w.contentBuffer+e.text}));if(o.phase!=="thinking"||o.currentThinkId===null)if(o.phase==="tool"||o.phase==="idle")r=qn(r,o.id),o=r.agents.get(o.id);else return se(r,o.id,w=>({...w,tokenCount:e.tokenCount}));let s=o.currentThinkId,a=o.timeline.find(w=>w.id===s);if(!a||a.kind!=="think")return r;let i=a.body+e.text,d=i.indexOf(Bn);if(d===-1)return se(r,o.id,w=>Nn({...w,tokenCount:e.tokenCount},s,v=>v.kind==="think"?{...v,body:i}:v));let c=i.slice(0,d),u=i.slice(d+Bn.length),m=st(r,o.id,c);return se(m,o.id,w=>({...w,tokenCount:e.tokenCount,contentBuffer:u}))}case"agent:tool_call":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let a=n.timeline.find(d=>d.id===n.currentThinkId),i=a&&a.kind==="think"?a.body:"";r=st(r,e.agentId,i)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,a=>({...a,phase:"tool",toolCallCount:a.toolCallCount+1}));let o=r.nextTimelineId;return{...se(r,e.agentId,a=>it({...a,phase:"tool",toolCallCount:a.toolCallCount+1,pendingToolCallId:o,contentBuffer:""},{kind:"tool_call",id:o,tool:e.tool,argsSummary:Mo(e.tool,e.args)})),nextTimelineId:r.nextTimelineId+1}}case"agent:tool_result":{let n=t.agents.get(e.agentId);if(!n)return t;if(n.taskIndex==null)return se(t,e.agentId,i=>({...i,phase:"idle"}));let r=_o(e.tool,e.result),o=t.nextTimelineId,s=Array.from(new Set(r.hosts));return{...se(t,e.agentId,i=>it({...i,phase:"idle",pendingToolCallId:null},{kind:"tool_result",id:o,tool:e.tool,callId:n.pendingToolCallId,byteLength:e.result.length,preview:r.preview,hosts:s,resultCount:r.resultCount})),nextTimelineId:t.nextTimelineId+1,sourceCount:t.sourceCount+s.length}}case"agent:tool_progress":return t;case"agent:report":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let u=n.timeline.find(w=>w.id===n.currentThinkId),m=u&&u.kind==="think"?u.body:"";r=st(r,e.agentId,m)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,u=>({...u,phase:"done",contentBuffer:""}));let o=r.nextTimelineId,s=se(r,e.agentId,u=>it({...u,phase:"done",contentBuffer:""},{kind:"report",id:o,body:e.result,tokenCount:u.tokenCount})),a=s.agents.get(e.agentId),i=s.researchAgentIds.includes(e.agentId),d=i&&a?[...s.scrollback,{key:`agent-${e.agentId}-${s.scrollback.length}`,kind:"agent",agent:a}]:s.scrollback,c=i?s.researchAgentIds.filter(u=>u!==e.agentId):s.researchAgentIds;return{...s,nextTimelineId:r.nextTimelineId+1,scrollback:d,researchAgentIds:c}}case"agent:done":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let o=n.timeline.find(a=>a.id===n.currentThinkId),s=o&&o.kind==="think"?o.body:"";r=st(r,e.agentId,s)}return se(r,e.agentId,o=>({...o,phase:"idle"}))}case"agent:tick":return{...t,pressure:{pct:e.nCtx>0?Math.round(100*e.cellsUsed/e.nCtx):0,cellsUsed:e.cellsUsed,nCtx:e.nCtx}};default:return t}}var Bn,Ln=q(()=>{"use strict";Mt();Bn="</think>"});import{useEffect as Oo,useReducer as Bo}from"react";function Fn(t,e=[]){let[n,r]=Bo(Ot,e,o=>o.reduce(Ot,rt));return Oo(()=>t.subscribe(r),[t]),n}var Un=q(()=>{"use strict";Mt();Ln()});import{createContext as Do,useContext as qo}from"react";function at(){return qo(Bt)}var No,Bt,lt=q(()=>{"use strict";No=()=>{},Bt=Do(No)});import{memo as Lo}from"react";import{Box as Fo,Text as $n}from"ink";import{jsx as Wn,jsxs as Uo}from"react/jsx-runtime";var zn,Hn=q(()=>{"use strict";zn=Lo(function({query:e,warm:n}){return e?Uo(Fo,{flexDirection:"column",marginBottom:1,children:[Wn($n,{bold:!0,children:e}),n?Wn($n,{dimColor:!0,children:"follow-up \xB7 warm session"}):null]}):null})});function ct(t){let e=Number.parseInt(t.slice(1),10);return!Number.isFinite(e)||e<0?Dt[0]:Dt[e%Dt.length]}var Dt,qt=q(()=>{"use strict";Dt=["cyan","yellow","green","magenta","red","blue"]});var de,ut=q(()=>{"use strict";de=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});import{memo as _e,useEffect as $o,useState as Wo}from"react";import{Box as W,Text as M}from"ink";import{jsx as R,jsxs as $}from"react/jsx-runtime";function Ho(t){return zo.includes(t.phase)}function Yo(t){let e=t.indexOf(`
|
|
4
|
-
`);if(e<=0)return"Thinking\u2026";let n=t.slice(0,e).trim();return n?n.length>72?n.slice(0,72).trimEnd()+"\u2026":n:"Thinking\u2026"}function
|
|
5
|
-
`);return e<=0?"":t.slice(e+1).trimStart()}var
|
|
6
|
-
`)?Yo(e.body):"Thinking\u2026":e.title,o=e.live?Yn(e.body):Yn(e.body).trim();return $(W,{flexDirection:"column",marginBottom:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u2726 "}),R(M,{bold:!0,children:r})]}),o?R(W,{paddingLeft:2,children:$(M,{children:[o,e.live?"\u258E":""]})}):e.live?R(W,{paddingLeft:2,children:R(M,{dimColor:!0,children:"\u258E"})}):null]})});Lt=_e(function({item:e,pending:n=!1}){let[r,o]=Wo(0);return $o(()=>{if(!n)return;let s=setInterval(()=>o(a=>(a+1)%de.length),80);return()=>clearInterval(s)},[n]),$(W,{flexShrink:0,children:[n?$(M,{color:"cyan",children:[de[r]," "]}):R(M,{dimColor:!0,children:"\u203A "}),R(M,{color:"cyan",children:e.tool}),e.argsSummary?$(M,{dimColor:!0,children:[" ",e.argsSummary]}):null]})}),Ft=_e(function({item:e}){let n=e.hosts.length>0?e.hosts.join(" \xB7 "):null;return $(W,{flexDirection:"column",flexShrink:0,children:[$(W,{paddingLeft:2,children:[R(M,{color:"green",children:"\u2713 "}),R(M,{children:e.resultCount??e.byteLength+"b"}),typeof e.resultCount=="number"?R(M,{children:" results"}):null]}),n?R(W,{paddingLeft:4,children:R(M,{dimColor:!0,children:n})}):e.preview?R(W,{paddingLeft:4,children:R(M,{dimColor:!0,children:e.preview.length>60?e.preview.slice(0,60)+"\u2026":e.preview})}):null]})}),Ut=_e(function({item:e,color:n}){let r=e.body.trim();return $(W,{flexDirection:"column",marginTop:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u2713 "}),R(M,{bold:!0,children:"report"}),$(M,{dimColor:!0,children:[" \xB7 ",e.tokenCount," tok"]})]}),r?R(W,{paddingLeft:2,children:R(M,{children:r})}):null]})}),jo=_e(function({buffer:e,color:n}){return $(W,{flexDirection:"column",marginTop:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u25B8 "}),R(M,{dimColor:!0,bold:!0,children:"streaming"})]}),R(W,{paddingLeft:2,children:$(M,{dimColor:!0,children:[e,"\u258E"]})})]})}),Ko=3,dt=_e(function({agent:e,headerPrefix:n,bodyHeight:r,width:o}){let s=ct(e.label),a=Ho(e),i=e.taskDescription??null,d=r+Ko;return $(W,{flexDirection:"column",width:o,height:d,paddingX:1,marginRight:1,flexShrink:0,overflow:"hidden",children:[$(W,{flexShrink:0,children:[n?$(M,{dimColor:!0,children:[n," \xB7 "]}):null,R(M,{color:s,bold:!0,children:e.label}),R(W,{flexGrow:1}),R(M,{color:a?s:"green",children:a?"\u25CF":"\u2713"})]}),i?R(M,{dimColor:!0,children:i}):null,e.dependencyHint?$(M,{dimColor:!0,children:["\u2191 ",e.dependencyHint]}):null,$(W,{flexDirection:"column",flexGrow:1,justifyContent:"flex-end",overflow:"hidden",children:[e.timeline.map(c=>c.kind==="think"?R(Nt,{item:c,color:s},c.id):c.kind==="tool_call"?R(Lt,{item:c,pending:e.pendingToolCallId===c.id},c.id):c.kind==="tool_result"?R(Ft,{item:c},c.id):c.kind==="report"?R(Ut,{item:c,color:s},c.id):null),e.contentBuffer?R(jo,{buffer:e.contentBuffer,color:s}):null]})]})})});import{Box as pt,Text as ht}from"ink";import{jsx as be,jsxs as Wt}from"react/jsx-runtime";function jn({agent:t}){let e=ct(t.label),n=t.taskDescription?t.taskDescription.length>80?t.taskDescription.slice(0,80)+"\u2026":t.taskDescription:null;return Wt(pt,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,marginBottom:1,children:[Wt(pt,{flexShrink:0,children:[be(ht,{color:e,bold:!0,children:t.label}),be(pt,{flexGrow:1}),be(ht,{color:"green",children:"\u2713"})]}),n?be(ht,{dimColor:!0,children:n}):null,t.dependencyHint?Wt(ht,{dimColor:!0,children:["\u2191 ",t.dependencyHint]}):null,be(pt,{flexDirection:"column",children:t.timeline.map(r=>r.kind==="think"?be(Nt,{item:r,color:e},r.id):r.kind==="tool_call"?be(Lt,{item:r},r.id):r.kind==="tool_result"?be(Ft,{item:r},r.id):r.kind==="report"?be(Ut,{item:r,color:e},r.id):null)})]})}var Kn=q(()=>{"use strict";qt();$t()});import{useEffect as Go,useState as Qo}from"react";import{useStdout as Vo}from"ink";function Gn(){let{stdout:t}=Vo(),[e,n]=Qo(()=>[t?.columns??120,t?.rows??40]);return Go(()=>{if(!t)return;let r=()=>{n([t.columns??120,t.rows??40])};return t.on("resize",r),()=>{t.off("resize",r)}},[t]),e}function Qn(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),r=e%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}var zt=q(()=>{"use strict"});import{Box as Ht}from"ink";import{jsx as Oe}from"react/jsx-runtime";function Xn({state:t}){let[e,n]=Gn(),r=t.researchAgentIds.map(a=>t.agents.get(a)).filter(a=>!!a);if(r.length===0)return null;let o=Math.max(Yt,n-Xo);if(t.mode==="flat"){let a=r.length,i=Math.max(Vn*a,e-4),d=Math.max(Vn,Math.floor(i/a)-1);return d*a+a<=e?Oe(Ht,{flexDirection:"row",marginBottom:1,children:r.map(u=>Oe(dt,{agent:u,headerPrefix:null,bodyHeight:o,width:d},u.id))}):Oe(Ht,{flexDirection:"column",marginBottom:1,children:r.map(u=>Oe(dt,{agent:u,headerPrefix:null,bodyHeight:Math.max(Yt,Math.floor(o/a))},u.id))})}let s=Math.max(Yt,Math.floor(o/Math.max(1,r.length)));return Oe(Ht,{flexDirection:"column",marginBottom:1,children:r.map(a=>Oe(dt,{agent:a,headerPrefix:`Task ${(a.taskIndex??0)+1}`,bodyHeight:s},a.id))})}var Xo,Vn,Yt,Jn=q(()=>{"use strict";$t();zt();Xo=18,Vn=26,Yt=10});import{Box as je,Text as ve}from"ink";import{jsx as Re,jsxs as Ke}from"react/jsx-runtime";function Zn({state:t}){let{synth:e}=t;if(!e.open&&!e.done)return null;let n=e.done?Ke(je,{children:[Re(ve,{bold:!0,children:"Synthesis "}),Re(ve,{color:"green",children:"\u2713"}),e.stats?Ke(ve,{dimColor:!0,children:[" ","\xB7 ",e.stats.tokens," tok \xB7 ",e.stats.toolCalls," tools \xB7"," ",Number.isFinite(e.stats.ppl)?`ppl ${e.stats.ppl.toFixed(2)} \xB7 `:"",Jo(e.stats.timeMs)]}):null]}):Ke(je,{children:[Re(ve,{bold:!0,children:"Synthesis"}),Re(ve,{color:"cyan",children:" \u25CF"})]}),r=e.buffer.trim();return Ke(je,{flexDirection:"column",marginBottom:1,children:[n,e.open&&r?Re(je,{paddingLeft:2,marginTop:0,children:Ke(ve,{children:[r,"\u258E"]})}):e.open?Re(je,{paddingLeft:2,children:Re(ve,{dimColor:!0,children:"\u258E"})}):null]})}var Jo,er=q(()=>{"use strict";Jo=t=>`${(t/1e3).toFixed(1)}s`});import{Box as tr,Text as nr}from"ink";import{jsx as jt,jsxs as Zo}from"react/jsx-runtime";function rr({state:t}){return!t.answer||t.synth.done&&t.synth.buffer.trim().length>0?null:Zo(tr,{flexDirection:"column",marginBottom:1,children:[jt(nr,{dimColor:!0,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"}),jt(tr,{marginTop:1,paddingLeft:2,children:jt(nr,{children:t.answer.trim()})})]})}var or=q(()=>{"use strict"});import{useEffect as es,useState as ts}from"react";import{Box as sr,Text as ae}from"ink";import{Fragment as is,jsx as pe,jsxs as Ge}from"react/jsx-runtime";function ns(t,e=12){let n=Math.min(e,Math.max(0,Math.round(t/100*e)));return"\u2588".repeat(n)+"\u2591".repeat(e-n)}function rs(t){return t>=90?"red":t>=70?"yellow":"green"}function os(t){let e=0;for(let n of t.agents.values())n.phase!=="done"&&n.phase!=="idle"&&e++;return e}function ss(t){let e=t.pipelineResumedAt,[,n]=ts(0);return es(()=>{if(e===null)return;let r=setInterval(()=>n(o=>o+1),250);return()=>clearInterval(r)},[e]),e===null?t.pipelineElapsedMs:t.pipelineElapsedMs+(Date.now()-e)}function ir({state:t}){let e=ss(t),n=t.pressure?.pct??0,r=os(t),o=rs(n);return pe(sr,{borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,paddingTop:0,children:Ge(sr,{flexDirection:"row",children:[pe(ae,{dimColor:!0,children:"KV "}),pe(ae,{color:o,children:ns(n)}),Ge(ae,{children:[" ",String(n).padStart(2," "),"%"]}),pe(ae,{dimColor:!0,children:" \xB7 "}),pe(ae,{children:t.phase}),pe(ae,{dimColor:!0,children:" \xB7 \u23F1 "}),pe(ae,{children:Qn(e)}),pe(ae,{dimColor:!0,children:" \xB7 "}),Ge(ae,{children:[r," active"]}),t.sourceCount>0?Ge(is,{children:[pe(ae,{dimColor:!0,children:" \xB7 "}),pe(ae,{dimColor:!0,children:"\u2315 "}),Ge(ae,{children:[t.sourceCount," sources"]})]}):null]})})}var ar=q(()=>{"use strict";zt()});import{useState as as}from"react";import{Text as Be,useInput as ls}from"ink";import{jsx as mt,jsxs as cr}from"react/jsx-runtime";function xe({value:t,onChange:e,onSubmit:n,onCancel:r,placeholder:o="",focused:s=!0,mask:a=!1,color:i}){let[d,c]=as(t.length),u=Math.min(d,t.length);ls((p,g)=>{if(g.return){n?.(t);return}if(g.escape){r?.();return}if(g.leftArrow){g.meta||g.ctrl?c(lr(t,u)):c(Math.max(0,u-1));return}if(g.rightArrow){g.meta||g.ctrl?c(cs(t,u)):c(Math.min(t.length,u+1));return}if(p==="\x1B[H"||p==="\x1BOH"){c(0);return}if(p==="\x1B[F"||p==="\x1BOF"){c(t.length);return}if(g.backspace||g.delete){if(u===0)return;if(g.meta||g.ctrl){let A=lr(t,u);e(t.slice(0,A)+t.slice(u)),c(A);return}let C=t.slice(0,u-1)+t.slice(u);c(u-1),e(C);return}if(g.ctrl&&p==="a"){c(0);return}if(g.ctrl&&p==="e"){c(t.length);return}if(g.ctrl&&p==="u"){e(t.slice(u)),c(0);return}if(g.ctrl&&p==="k"){e(t.slice(0,u));return}if(g.ctrl&&p==="w"){let C=t.slice(0,u),A=/\S+\s*$/.exec(C),T=A?A.index:0;e(t.slice(0,T)+t.slice(u)),c(T);return}if(!(g.ctrl||g.meta||g.tab||g.upArrow||g.downArrow)&&p.length>0){let C=t.slice(0,u)+p+t.slice(u);c(u+p.length),e(C)}},{isActive:s});let m=a?"*".repeat(t.length):t;if(t.length===0)return cr(Be,{children:[mt(Be,{color:i,children:s?"\u258E":""}),mt(Be,{dimColor:!0,children:o})]});if(!s)return mt(Be,{color:i,children:m});let v=m.slice(0,u),L=m.slice(u,u+1),P=m.slice(u+1);return cr(Be,{color:i,children:[v,mt(Be,{inverse:!0,children:L||" "}),P]})}function lr(t,e){if(e<=0)return 0;let n=e;for(;n>0&&/\s/.test(t[n-1]);)n--;for(;n>0&&!/\s/.test(t[n-1]);)n--;return n}function cs(t,e){let n=t.length;if(e>=n)return n;let r=e;for(;r<n&&/\s/.test(t[r]);)r++;for(;r<n&&!/\s/.test(t[r]);)r++;return r}var Kt=q(()=>{"use strict"});import{memo as qe,useEffect as Gt,useState as De}from"react";import{Box as ee,Text as O,useInput as us}from"ink";import{jsx as k,jsxs as re}from"react/jsx-runtime";function ur(t){if(!t.startsWith("/"))return null;let e=t.slice(1).trimStart();if(!e)return{name:"",value:""};let n=e.search(/\s/),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1).trim();return{name:r,value:o}}function ds(t){if(!t)return[];if(!t.name)return ft;let e=t.name.toLowerCase();return ft.filter(n=>n.name.startsWith(e))}var ft,hr,dr,Qt,ps,hs,pr,mr=q(()=>{"use strict";lt();Kt();ft=[{name:"scan",desc:"Set local file source (path or glob)",kind:"value"},{name:"web",desc:"Set web search key",kind:"value"},{name:"model",desc:"Set local LLM .gguf path",kind:"value"},{name:"reranker",desc:"Set local reranker .gguf path",kind:"value"},{name:"output",desc:"Set output directory",kind:"value"},{name:"deep",desc:"Use deep (chain) reasoning",kind:"instant"},{name:"flat",desc:"Use flat (parallel) reasoning",kind:"instant"},{name:"help",desc:"Show this list",kind:"instant"},{name:"quit",desc:"Quit",kind:"instant"}];hr=qe(function({state:e}){let n=at(),r=e.config?.defaults.reasoningMode??"flat",[o,s]=De(r),[a,i]=De("query"),[d,c]=De(""),[u,m]=De(""),[w,v]=De(!1),L=e.scrollback.length>0,[P,p]=De(L?"start":"plan");Gt(()=>{L&&p("start")},[L]),Gt(()=>{e.composerPrefill&&e.composerPrefill!==d&&c(e.composerPrefill)},[e.composerPrefill]),Gt(()=>{s(r)},[r]);let g=e.configOrigin?.tavilyKey??"unset",C=e.configOrigin?.corpusPath??"unset",A=e.configOrigin?.outputDir??"default",T=g!=="unset",F=T||C!=="unset",J=g==="env",K=e.clarifyContext!==null,B=ur(d),D=B!==null,U=ds(B);us((x,h)=>{if(h.ctrl&&x==="c"){n({type:"quit"});return}if(h.tab&&h.shift){!D&&!K&&p(l=>l==="plan"?"start":"plan");return}if(h.tab){if(D&&B&&B.name&&U.length===1){let l=U[0];c("/"+l.name+(l.kind==="value"?" ":""));return}return}if(h.escape){if(K){n({type:"cancel_plan"}),c("");return}c(""),v(!1);return}},{isActive:a==="query"});let Se=x=>{let h=x.trim();if(h){if(!K){let l=ur(h);if(l){Ee(l);return}}if(K){n({type:"submit_clarification",answer:h}),c("");return}F&&(n({type:"submit_query",query:h,mode:o,skipPlanner:P==="start"}),c(""))}},Ee=({name:x,value:h})=>{if(!x)return;let l=ft.find(f=>f.name===x);if(l){if(c(""),v(!1),l.kind==="instant"){x==="deep"?s("deep"):x==="flat"?s("flat"):x==="quit"?n({type:"quit"}):x==="help"&&v(!0);return}if(h){x==="web"?n({type:"set_tavily_key",key:h}):x==="scan"?n({type:"set_corpus_path",path:h}):x==="output"?n({type:"set_output_dir",path:h}):x==="model"?n({type:"set_model_path",path:h}):x==="reranker"&&n({type:"set_reranker_path",path:h});return}if(x==="web"){if(J)return;m(e.config?.sources.tavilyKey??""),i("web")}else x==="scan"?(m(e.config?.sources.corpusPath??""),i("scan")):x==="output"?(m(e.config?.sources.outputDir??""),i("output")):x==="model"?(m(e.config?.model.path??""),i("model")):x==="reranker"&&(m(e.config?.model.reranker??""),i("reranker"))}};return re(ee,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[a==="query"?re(ee,{children:[k(O,{children:"\u203A "}),k(xe,{value:d,onChange:c,onSubmit:Se,focused:!0,placeholder:K?"Answer the questions above, or Esc to cancel\u2026":F?"Ask a research question, or / for commands\u2026":"Type / for commands (e.g. /web, /scan) to add a source"})]}):a==="web"?re(ee,{children:[k(O,{color:"yellow",children:"Web search key \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_tavily_key",key:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,mask:!0,placeholder:"tvly-..."})]}):a==="scan"?re(ee,{children:[k(O,{color:"yellow",children:"Scan path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_corpus_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/docs or /path/**/*.md"})]}):a==="output"?re(ee,{children:[k(O,{color:"yellow",children:"Output dir \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_output_dir",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:`${process.cwd()} (default)`})]}):a==="model"?re(ee,{children:[k(O,{color:"yellow",children:"Model path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_model_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/qwen3.5-4b.gguf"})]}):re(ee,{children:[k(O,{color:"yellow",children:"Reranker path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_reranker_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/qwen3-reranker.gguf"})]}),a==="query"&&!K&&D?k(ee,{flexDirection:"column",marginTop:0,children:U.length===0?k(O,{color:"red",children:"no matching command"}):U.map(x=>k(dr,{cmd:x},x.name))}):null,a==="query"&&!D&&w?k(ee,{flexDirection:"column",marginTop:0,children:ft.map(x=>k(dr,{cmd:x},x.name))}):null,re(ee,{marginTop:0,children:[k(Qt,{label:"Web",origin:g,value:T?"set":null,disabled:J}),k(O,{children:" "}),k(Qt,{label:"Scan",origin:C,value:e.config?.sources.corpusPath?e.corpusStatus?`${e.corpusStatus.fileCount} files`:e.config.sources.corpusPath:null}),k(O,{children:" "}),k(Qt,{label:"Output",origin:A,value:e.config?.sources.outputDir??null}),k(ee,{flexGrow:1}),a==="query"&&!K&&!D?k(hs,{submitMode:P}):null]}),k(ee,{marginTop:0,children:k(ps,{field:a,hasSource:F,inSlash:D,clarifying:K})}),e.toast?k(ee,{marginTop:0,children:k(O,{color:e.toast.tone==="error"?"red":e.toast.tone==="warn"?"yellow":"green",children:e.toast.message})}):null]})}),dr=qe(function({cmd:e}){return re(ee,{children:[re(O,{color:"cyan",children:["/",e.name]}),re(O,{dimColor:!0,children:[" \xB7 ",e.desc]}),e.kind==="value"?k(O,{dimColor:!0,children:" <value>"}):null]})}),Qt=qe(function({label:e,origin:n,value:r,disabled:o=!1}){let s=n!=="unset";return re(O,{children:[re(O,{color:s?"green":"gray",dimColor:o,children:[e," ",s?e==="Scan"&&r?r:"\u2713":"\u2014"]}),k(O,{dimColor:!0,children:n==="env"?" (env)":n==="cli"?" (cli)":""})]})}),ps=qe(function({field:e,hasSource:n,inSlash:r,clarifying:o}){return e==="web"||e==="scan"||e==="output"||e==="model"||e==="reranker"?k(O,{dimColor:!0,children:"\u23CE save (empty to clear) \xB7 Ctrl+U clear \xB7 Esc cancel"}):o?k(O,{color:"yellow",children:"\u23CE submit answer \xB7 Esc cancel"}):r?k(O,{dimColor:!0,children:"Tab complete \xB7 \u23CE run \xB7 Esc clear"}):n?k(O,{dimColor:!0,children:"\u21E7Tab Plan/Start \xB7 / commands"}):k(O,{color:"yellow",children:"\u26A0 Add a source via /web or /scan"})}),hs=qe(function({submitMode:e}){return re(ee,{children:[k(pr,{label:"PLAN",focused:e==="plan",hue:"cyan"}),k(O,{children:" "}),k(pr,{label:"START",focused:e==="start",hue:"green"})]})}),pr=qe(function({label:e,focused:n,hue:r}){let s=` ${n?"\u25C9":"\u25CB"} ${e} `;return n?k(O,{backgroundColor:r,color:"black",bold:!0,children:s}):k(O,{dimColor:!0,children:s})})});import{memo as Vt,useEffect as fr,useRef as ms,useState as gt}from"react";import{Box as Y,Text as _,useInput as fs}from"ink";import{jsx as E,jsxs as Q}from"react/jsx-runtime";var gr,gs,ys,yr=q(()=>{"use strict";lt();Kt();gr=Vt(function({state:e}){let n=at(),r=e.plan,[o,s]=gt(e.mode??"flat"),[a,i]=gt(()=>r?.tasks.length??0),[d,c]=gt(null),[u,m]=gt("");fr(()=>{e.mode&&e.mode!==o&&s(e.mode),c(null),i(r?.tasks.length??0)},[e.mode]),fr(()=>{r&&a>r.tasks.length&&i(r.tasks.length)},[r?.tasks.length]);let w=ms({focusedIndex:a,editingIndex:d,mode:o,plan:r,query:e.query});if(w.current={focusedIndex:a,editingIndex:d,mode:o,plan:r,query:e.query},fs((P,p)=>{let g=w.current,C=g.plan,A=g.editingIndex,T=g.focusedIndex,le=g.mode;if(!C||A!==null)return;if(C.intent!=="research"){if(p.return){C.intent==="clarify"&&n({type:"edit_plan",query:g.query});return}p.escape&&n({type:"cancel_plan"}),p.ctrl&&P==="c"&&n({type:"quit"});return}if(p.ctrl&&P==="c"){n({type:"quit"});return}if(p.escape){n({type:"cancel_plan"});return}let F=T>=C.tasks.length;if(p.shift&&p.upArrow){!F&&T>0&&(n({type:"move_task",from:T,to:T-1}),i(T-1));return}if(p.shift&&p.downArrow){!F&&T<C.tasks.length-1&&(n({type:"move_task",from:T,to:T+1}),i(T+1));return}if(p.upArrow){i(Math.max(0,T-1));return}if(p.downArrow){i(Math.min(C.tasks.length,T+1));return}if(p.return){F?n({type:"accept_plan"}):(m(C.tasks[T]?.description??""),c(T));return}if(P==="a"||P==="A"||P==="+"){let J=F?C.tasks.length-1:T,K=J+1;n({type:"add_task",afterIndex:J}),i(K),m(""),c(K);return}if(P==="d"||P==="D"||p.delete){!F&&C.tasks.length>1&&n({type:"delete_task",index:T});return}if(P==="t"||P==="T"){let J=le==="deep"?"flat":"deep";s(J),n({type:"change_mode",mode:J});return}}),!r)return null;if(r.intent==="clarify")return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(Y,{marginBottom:1,children:E(_,{bold:!0,children:e.query})}),E(_,{dimColor:!0,children:"A few questions to narrow this down."}),E(Y,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.clarifyQuestions.map((P,p)=>Q(_,{children:[Q(_,{dimColor:!0,children:["(",p+1,")"]})," ",P]},p))}),E(Y,{marginTop:1,children:E(_,{dimColor:!0,children:"\u23CE answer \xB7 Esc cancel"})})]});if(r.intent==="passthrough")return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(_,{bold:!0,children:e.query}),E(_,{dimColor:!0,children:"Answering directly \u2014 no research needed."})]});let v=o==="flat"?"parallel":"chained",L=d!==null;return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(Y,{marginBottom:1,children:E(_,{bold:!0,children:e.query})}),Q(Y,{marginBottom:1,children:[E(_,{dimColor:!0,children:"Research plan"}),Q(_,{dimColor:!0,children:[" \xB7 ",r.tasks.length," ",v," tasks"]}),L?Q(_,{color:"yellow",children:[" \xB7 editing row ",d+1]}):null]}),Q(Y,{flexDirection:"column",children:[r.tasks.map((P,p)=>E(ys,{index:p,description:P.description,focused:p===a,editing:p===d,draft:u,onDraftChange:m,onSubmit:g=>{n({type:"update_task_description",index:p,description:g.trim()}),c(null)},onCancel:()=>c(null)},p)),E(gs,{focused:a>=r.tasks.length&&!L})]}),Q(Y,{marginTop:1,children:[Q(_,{color:o==="deep"?"cyan":void 0,bold:o==="deep",children:[o==="deep"?"\u25C6":"\u25CB"," Deep"]}),E(_,{children:" "}),Q(_,{color:o==="flat"?"cyan":void 0,bold:o==="flat",children:[o==="flat"?"\u25C6":"\u25CB"," Flat"]}),E(_,{dimColor:!0,children:" T toggle mode (re-plans, discards edits)"})]}),E(Y,{marginTop:1,children:L?E(_,{dimColor:!0,children:"\u23CE save \xB7 Esc revert"}):Q(_,{dimColor:!0,children:["\u2191\u2193 select \xB7 \u23CE ",a>=r.tasks.length?"start research":"edit"," \xB7 A add \xB7 D delete \xB7 \u21E7\u2191\u2193 reorder \xB7 Esc cancel"]})})]})}),gs=Vt(function({focused:e}){return e?E(Y,{paddingLeft:2,marginTop:1,children:E(_,{backgroundColor:"green",color:"black",bold:!0,children:" \u25B6 START research "})}):E(Y,{paddingLeft:2,marginTop:1,children:E(_,{dimColor:!0,children:" \u25B6 START research"})})}),ys=Vt(function({index:e,description:n,focused:r,editing:o,draft:s,onDraftChange:a,onSubmit:i,onCancel:d}){return o?Q(Y,{paddingLeft:2,children:[E(_,{color:"yellow",bold:!0,children:`\u25B6 ${e+1}. `}),E(Y,{flexGrow:1,children:E(xe,{value:s,onChange:a,onSubmit:i,onCancel:d,focused:!0,placeholder:"(empty \u2014 type a task description)"})})]}):r?Q(Y,{paddingLeft:2,children:[E(_,{color:"cyan",bold:!0,children:`\u203A ${e+1}. `}),E(_,{bold:!0,children:n||E(_,{dimColor:!0,children:"(empty)"})})]}):Q(Y,{paddingLeft:2,children:[E(_,{dimColor:!0,children:` ${e+1}. `}),E(_,{dimColor:!0,children:n||"(empty)"})]})})});import{memo as bs,useEffect as xs,useState as ks}from"react";import{Box as br,Text as Xt}from"ink";import{jsx as xr,jsxs as Jt}from"react/jsx-runtime";var kr,wr=q(()=>{"use strict";ut();kr=bs(function({state:e}){let[n,r]=ks(0);return xs(()=>{let o=setInterval(()=>r(s=>(s+1)%de.length),80);return()=>clearInterval(o)},[]),Jt(br,{flexDirection:"column",marginBottom:1,children:[xr(Xt,{bold:!0,children:e.query}),Jt(br,{marginTop:1,children:[Jt(Xt,{color:"cyan",children:[de[n]," "]}),xr(Xt,{dimColor:!0,children:"Planning\u2026"})]})]})})});import{memo as ws}from"react";import{Box as Tr,Text as yt}from"ink";import{jsx as Zt,jsxs as en}from"react/jsx-runtime";var Sr,Cr=q(()=>{"use strict";Sr=ws(function({state:e}){if(!e.clarifyContext)return null;let{originalQuery:n,questions:r}=e.clarifyContext;return en(Tr,{flexDirection:"column",marginBottom:1,children:[Zt(yt,{bold:!0,children:n}),Zt(yt,{dimColor:!0,children:"A few questions to narrow this down."}),Zt(Tr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.map((o,s)=>en(yt,{children:[en(yt,{dimColor:!0,children:["(",s+1,")"]})," ",o]},s))})]})})});import{memo as vr,useEffect as Ts,useState as Ss}from"react";import{Box as Pe,Text as N}from"ink";import{Fragment as Rs,jsx as oe,jsxs as V}from"react/jsx-runtime";function vs(t){try{return new URL(t).host}catch{return null}}function bt(t){return t>=1e9?(t/1e9).toFixed(1)+" GB":t>=1e6?(t/1e6).toFixed(0)+" MB":t>=1e3?(t/1e3).toFixed(0)+" KB":`${t} B`}var Rr,Cs,Pr=q(()=>{"use strict";ut();Rr=vr(function({state:e}){let[n,r]=Ss(0);if(Ts(()=>{let o=setInterval(()=>r(s=>(s+1)%de.length),80);return()=>clearInterval(o)},[]),e.uiPhase==="boot_error"){let o=e.bootError,s=o?.kind??"llm",a=s==="llm"?"LLM":"reranker",i=s==="llm"?"/model":"/reranker",d=s==="llm"?"/reranker":"/model";return V(Pe,{flexDirection:"column",marginBottom:1,children:[V(N,{color:"red",bold:!0,children:["\u2717 Boot failed (",a,")"]}),oe(Pe,{paddingLeft:2,children:oe(N,{children:o?.message??"Unknown error"})}),oe(Pe,{paddingLeft:2,marginTop:1,children:V(N,{dimColor:!0,children:["Type ",V(N,{color:"cyan",children:[i," "]}),oe(N,{dimColor:!0,children:"<path-to-gguf>"}),V(N,{dimColor:!0,children:[" to use a local ",a,", or "]}),oe(N,{color:"cyan",children:d}),oe(N,{dimColor:!0,children:" for the other, or "}),oe(N,{color:"cyan",children:"/quit"}),oe(N,{dimColor:!0,children:" to exit."})]})})]})}return e.uiPhase==="downloading"?V(Pe,{flexDirection:"column",marginBottom:1,children:[V(Pe,{children:[V(N,{color:"cyan",children:[de[n]," "]}),oe(N,{bold:!0,children:"Downloading models"})]}),e.downloads.map(o=>oe(Cs,{item:o},o.id))]}):V(Pe,{marginBottom:1,children:[V(N,{color:"cyan",children:[de[n]," "]}),oe(N,{bold:!0,children:e.loadingLabel??"Loading\u2026"})]})}),Cs=vr(function({item:e}){let n=e.total>0?Math.min(100,Math.floor(e.got/e.total*100)):0,r=16,o=Math.floor(n/100*r),s="\u2588".repeat(o)+"\u2591".repeat(r-o),a=e.url?vs(e.url):null,i=e.started&&a!==null,d=e.done?"\u2713 ":i?"\u25CF ":"\u25CB ",c=e.done?"green":i?"cyan":void 0,u=!i&&!e.done;return V(Pe,{paddingLeft:2,children:[oe(N,{color:c,dimColor:u,children:d}),V(N,{dimColor:u,children:[e.label.padEnd(28)," "]}),e.done?oe(N,{dimColor:!0,children:bt(e.got)}):i?V(Rs,{children:[oe(N,{color:"cyan",children:s}),V(N,{children:[" ",String(n).padStart(2),"% \xB7 ",bt(e.got)," / ",bt(e.total)]}),V(N,{dimColor:!0,children:[" \xB7 ",a]})]}):V(N,{dimColor:!0,children:["queued \xB7 ",bt(e.total)]})]})})});import{Box as xt,Static as Ps,Text as Ar}from"ink";import{jsx as X,jsxs as tn}from"react/jsx-runtime";function Er({bus:t,dispatch:e,bootstrap:n}){let r=Fn(t,n),o=r.uiPhase!=="composer"&&r.uiPhase!=="boot"&&r.uiPhase!=="downloading"&&r.uiPhase!=="loading"&&r.uiPhase!=="planning"&&r.uiPhase!=="plan_review"&&r.uiPhase!=="clarifying",s=r.uiPhase==="research"||r.uiPhase==="done",a=r.uiPhase==="composer"||r.uiPhase==="done"||r.uiPhase==="clarifying"||r.uiPhase==="boot_error";return tn(Bt.Provider,{value:e,children:[X(Ps,{items:r.scrollback,children:i=>i.kind==="agent"?X(xt,{paddingX:2,children:X(jn,{agent:i.agent})},i.key):tn(xt,{flexDirection:"column",paddingX:2,marginBottom:1,children:[X(Ar,{dimColor:!0,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"}),X(xt,{paddingLeft:2,marginTop:1,children:X(Ar,{children:i.body})})]},i.key)}),tn(xt,{flexDirection:"column",paddingX:2,paddingY:1,children:[o&&X(zn,{query:r.query,warm:r.warm}),(r.uiPhase==="downloading"||r.uiPhase==="loading"||r.uiPhase==="boot_error")&&X(Rr,{state:r}),r.uiPhase==="planning"&&X(kr,{state:r}),r.uiPhase==="plan_review"&&X(gr,{state:r}),r.uiPhase==="clarifying"&&X(Sr,{state:r}),s&&X(Xn,{state:r}),s&&X(Zn,{state:r}),r.uiPhase==="done"&&X(rr,{state:r}),a&&X(hr,{state:r}),X(ir,{state:r})]})]})}var Ir=q(()=>{"use strict";Un();lt();Hn();Kn();Jn();er();or();ar();mr();yr();wr();Cr();Pr()});var Mr={};zr(Mr,{render:()=>Is});import As from"react";import{render as Es}from"ink";function Is(t,e,n=[]){return Es(As.createElement(Er,{bus:t,dispatch:e,bootstrap:n}),{incrementalRendering:!0})}var _r=q(()=>{"use strict";Ir()});import*as H from"node:fs";import*as ge from"node:path";import{parseArgs as Ms}from"node:util";import{main as _s,ensure as kt,createSignal as Os,spawn as Or,each as Ae,call as Fe}from"effection";import{createContext as Bs}from"@lloyal-labs/lloyal.node";import{initAgents as Ds,JsonlTraceWriter as qs}from"@lloyal-labs/lloyal-agents";var wt=!1,Hr=!1;function un(t){wt=t}function dn(t){Hr=t}var Tt=!!process.stdout.isTTY,St=Tt?{bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m",green:"\x1B[32m",cyan:"\x1B[36m",yellow:"\x1B[33m",red:"\x1B[31m"}:{bold:"",dim:"",reset:"",green:"",cyan:"",yellow:"",red:""},cn="";function Yr(){cn&&(cn="",process.stdout.write("\r\x1B[K"))}var Je=(...t)=>{wt||(Yr(),console.log(...t))};function pn(t,e){wt&&console.log(JSON.stringify({event:t,...e}))}import*as ne from"node:fs";import*as Z from"node:path";import*as Ct from"node:os";import*as Ze from"node:path";function ke(t){if(!t)return"";let e=t==="~"?Ct.homedir():t.startsWith("~/")?Ze.join(Ct.homedir(),t.slice(2)):t;return Ze.resolve(e)}function vt(){return{version:1,sources:{},defaults:{reasoningMode:"flat",maxTurns:10},model:{}}}function mn(t){try{let e=ne.readFileSync(t,"utf8"),n=JSON.parse(e);if(n.version!==1)return null;let r=vt();return{version:1,sources:{...r.sources,...n.sources??{}},defaults:{...r.defaults,...n.defaults??{}},model:{...r.model,...n.model??{}}}}catch{return null}}function Ce(t,e,n=process.env){let r=Z.resolve(t),o=mn(r),s=o??vt(),a=n.TAVILY_API_KEY?.trim()||void 0,i=n.LLAMA_CTX_SIZE?.trim(),d=i&&/^\d+$/.test(i)?parseInt(i,10):void 0,c=e.tavilyKey??a??s.sources.tavilyKey,u=e.corpusPath??s.sources.corpusPath,m=u?ke(u):void 0,w=e.outputDir??s.sources.outputDir,v=w?ke(w):void 0,L=e.reasoningMode??s.defaults.reasoningMode??"flat",P=e.modelPath??s.model.path,p=P?ke(P):void 0,g=e.reranker??s.model.reranker,C=e.nCtx??d??s.model.nCtx,A={version:1,sources:{tavilyKey:c,corpusPath:m,outputDir:v},defaults:{reasoningMode:L,maxTurns:s.defaults.maxTurns},model:{path:p,reranker:g,nCtx:C}},T={tavilyKey:e.tavilyKey?"cli":a?"env":s.sources.tavilyKey?"file":"unset",corpusPath:e.corpusPath?"cli":s.sources.corpusPath?"file":"unset",reasoningMode:e.reasoningMode?"cli":o?.defaults.reasoningMode?"file":"default",modelPath:e.modelPath?"cli":o?.model.path?"file":"default",reranker:e.reranker?"cli":o?.model.reranker?"file":"default",nCtx:e.nCtx!==void 0?"cli":d!==void 0?"env":o?.model.nCtx!==void 0?"file":"default",outputDir:e.outputDir?"cli":o?.sources.outputDir?"file":"default"};return{config:A,origin:T,path:r,loadedFromFile:!!o}}function we(t,e,n=process.env){let r=Z.resolve(e),o=mn(r)??vt(),s=[],a={...o.sources,...t.sources??{}};t.sources?.tavilyKey===""&&delete a.tavilyKey,t.sources?.corpusPath===""&&delete a.corpusPath,t.sources?.outputDir===""&&delete a.outputDir,n.TAVILY_API_KEY&&t.sources&&"tavilyKey"in t.sources&&(delete a.tavilyKey,s.push("sources.tavilyKey"));let i={version:1,sources:a,defaults:{...o.defaults,...t.defaults??{}},model:{...o.model,...t.model??{}}},d=Z.dirname(r);ne.mkdirSync(d,{recursive:!0});let c=r+".tmp-"+process.pid;ne.writeFileSync(c,JSON.stringify(i,null,2)+`
|
|
7
|
-
`,"utf8"),ne.renameSync(c,r);let u=
|
|
2
|
+
var $r=Object.defineProperty;var q=(t,e)=>()=>(t&&(e=t(t=0)),e);var Wr=(t,e)=>{for(var n in e)$r(t,n,{get:e[n],enumerable:!0})};var rt,Mt=q(()=>{"use strict";rt={query:"",warm:!1,uiPhase:"boot",phase:"idle",mode:null,plan:null,agents:new Map,researchAgentIds:[],sourceCount:0,synth:{open:!1,buffer:"",done:!1,stats:null},answer:null,pressure:null,timings:[],startedAt:Date.now(),pipelineElapsedMs:0,pipelineResumedAt:null,nextTimelineId:0,nextLabelIdx:0,pendingTaskIndex:null,pendingTaskDescription:null,researchSpawnCount:0,config:null,configOrigin:null,toast:null,composerPrefill:"",clarifyContext:null,downloads:[],loadingLabel:null,nextToastId:0,scrollback:[],corpusStatus:null,bootError:null}});function _t(t){let e=process.env.HOME;return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Eo(t){let e=t.replace(/^\s*\n/,"").replace(/\*\*/g,"").replace(/^#+\s*/,"").trim();if(!e)return"Thinking\u2026";let n=e.split(`
|
|
3
|
+
`)[0].trim();return n.length>72?n.slice(0,72).trimEnd()+"\u2026":n}function ot(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Io(t,e){let n;try{n=JSON.parse(e)}catch{n={}}let r=typeof n.query=="string"?n.query:typeof n.pattern=="string"?n.pattern:typeof n.url=="string"?n.url:typeof n.filename=="string"?n.filename:"";return r?`"${r.length>48?r.slice(0,48)+"\u2026":r}"`:""}function Mo(t,e){try{let r=JSON.parse(e);if(t==="web_search"&&Array.isArray(r)){let o=r,s=Array.from(new Set(o.map(a=>a.url?ot(a.url):"").filter(Boolean))).slice(0,3);return{summary:`${o.length} results`,hosts:s,resultCount:o.length,preview:o[0]?.title??null}}if(t==="search"&&Array.isArray(r)){let o=r;return{summary:`${o.length} results`,hosts:[],resultCount:o.length,preview:o[0]?.heading??null}}if(t==="grep"&&typeof r=="object"&&r!==null){let o=r;return{summary:`${o.totalMatches??0} matches`,hosts:[],resultCount:o.totalMatches??null,preview:null}}if(t==="fetch_page"&&typeof r=="object"&&r!==null){let o=r;if(o.error)return{summary:o.error,hosts:[],resultCount:null,preview:null};let s=o.url?[ot(o.url)]:[];return{summary:`${e.length}b`,hosts:s,resultCount:null,preview:o.title??null}}if(t==="web_fetch"&&typeof r=="object"&&r!==null){let o=r,s=o.url?[ot(o.url)]:[];return{summary:`${e.length}b`,hosts:s,resultCount:null,preview:o.title??null}}}catch{}let n=Array.from(e.matchAll(/https?:\/\/[^\s\])>"]+/g)).map(r=>r[0]);if(n.length>0){let r=Array.from(new Set(n.map(ot))).slice(0,3);return{summary:`${n.length} links`,hosts:r,resultCount:n.length,preview:null}}return{summary:`${e.length}b`,hosts:[],resultCount:null,preview:null}}function se(t,e,n){let r=t.agents.get(e);if(!r)return t;let o=new Map(t.agents);return o.set(e,n(r)),{...t,agents:o}}function Bn(t,e,n={}){if(t.agents.has(e))return t;let r={id:e,label:`A${t.nextLabelIdx}`,phase:"idle",tokenCount:0,toolCallCount:0,taskIndex:null,taskDescription:null,dependencyHint:null,currentThinkId:null,pendingToolCallId:null,contentBuffer:"",timeline:[],...n},o=new Map(t.agents);return o.set(e,r),{...t,agents:o,nextLabelIdx:t.nextLabelIdx+1}}function it(t,e){return{...t,timeline:[...t.timeline,e]}}function qn(t,e,n){return{...t,timeline:t.timeline.map(r=>r.id===e?n(r):r)}}function Dn(t,e){let n=t.nextTimelineId;return{...se(t,e,o=>it({...o,currentThinkId:n,phase:"thinking"},{kind:"think",id:n,title:"Thinking\u2026",body:"",live:!0,openedAt:Date.now(),closedAt:null})),nextTimelineId:t.nextTimelineId+1}}function st(t,e,n){let r=t.agents.get(e);if(!r||r.currentThinkId===null)return t;let o=r.currentThinkId,s=Eo(n);return se(t,e,a=>qn({...a,currentThinkId:null,phase:"content"},o,i=>i.kind==="think"?{...i,body:n,title:s,live:!1,closedAt:Date.now()}:i))}function Ot(t,e){switch(e.type){case"query":return{...rt,config:t.config,configOrigin:t.configOrigin,uiPhase:t.uiPhase,mode:t.mode,nextToastId:t.nextToastId,toast:t.toast,scrollback:t.scrollback,query:e.query,warm:e.warm,phase:"plan",startedAt:Date.now()};case"plan":return{...t,uiPhase:e.intent==="clarify"?"clarifying":t.uiPhase,phase:e.intent==="research"?"plan":"done",plan:{intent:e.intent,tasks:e.tasks,clarifyQuestions:e.clarifyQuestions,tokenCount:e.tokenCount,timeMs:e.timeMs},clarifyContext:e.intent==="clarify"?{originalQuery:t.query,questions:e.clarifyQuestions}:null};case"plan:task_updated":{if(!t.plan||e.index<0||e.index>=t.plan.tasks.length)return t;let n=t.plan.tasks.map((r,o)=>o===e.index?{...r,description:e.description}:r);return{...t,plan:{...t.plan,tasks:n}}}case"plan:task_added":{if(!t.plan)return t;let n=Math.max(0,Math.min(t.plan.tasks.length,e.afterIndex+1)),r=[...t.plan.tasks.slice(0,n),{description:""},...t.plan.tasks.slice(n)];return{...t,plan:{...t.plan,tasks:r}}}case"plan:task_deleted":{if(!t.plan||t.plan.tasks.length<=1||e.index<0||e.index>=t.plan.tasks.length)return t;let n=t.plan.tasks.filter((r,o)=>o!==e.index);return{...t,plan:{...t.plan,tasks:n}}}case"plan:task_moved":{if(!t.plan)return t;let n=t.plan.tasks.length;if(e.from===e.to||e.from<0||e.from>=n||e.to<0||e.to>=n)return t;let r=[...t.plan.tasks],[o]=r.splice(e.from,1);return r.splice(e.to,0,o),{...t,plan:{...t.plan,tasks:r}}}case"research:start":return{...t,uiPhase:"research",phase:"research",mode:e.mode==="flat"?"flat":"deep",pipelineResumedAt:Date.now()};case"research:done":return{...t,phase:"synth"};case"fanout:tasks":return t;case"spine:task":return{...t,pendingTaskIndex:e.taskIndex,pendingTaskDescription:e.description};case"spine:source":case"spine:task:done":return t;case"synthesize:start":return{...t,phase:"synth",synth:{open:!0,buffer:"",done:!1,stats:null}};case"synthesize:done":{let n=t.synth.buffer.trim(),r=n?[...t.scrollback,{key:`synth-${t.scrollback.length}-${Date.now()}`,kind:"synth",body:n}]:t.scrollback;return{...t,scrollback:r,synth:{...t.synth,open:!1,done:!0,stats:{tokens:e.tokenCount,toolCalls:e.toolCallCount,ppl:e.ppl,timeMs:e.timeMs}}}}case"answer":return{...t,answer:e.text};case"stats":return{...t,timings:e.timings,pressure:{pct:e.ctxPct,cellsUsed:e.ctxPos,nCtx:e.ctxTotal}};case"complete":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,phase:"done",uiPhase:"done",pipelineElapsedMs:n,pipelineResumedAt:null}}case"config:loaded":return{...t,config:e.config,configOrigin:e.origin};case"config:updated":{let n=t.nextToastId+1,r=e.skipped.length>0?`saved \u2192 ${_t(e.savedTo)} (skipped: ${e.skipped.join(", ")} \u2014 env active)`:e.gitignored?`saved \u2192 ${_t(e.savedTo)} (added to .gitignore)`:`saved \u2192 ${_t(e.savedTo)}`;return{...t,config:e.config,configOrigin:e.origin,toast:{id:n,message:r,tone:e.skipped.length>0?"warn":"success"},nextToastId:n}}case"plan:start":{let r=t.uiPhase==="composer"||t.uiPhase==="done"||t.uiPhase==="boot"?{pipelineElapsedMs:0,startedAt:Date.now()}:{};return{...t,...r,uiPhase:"planning",phase:"plan",plan:null,query:e.query,mode:e.mode==="flat"?"flat":"deep",pipelineResumedAt:Date.now()}}case"ui:composer":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,uiPhase:"composer",composerPrefill:e.prefill??"",clarifyContext:null,pipelineElapsedMs:n,pipelineResumedAt:null}}case"ui:plan_review":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,uiPhase:"plan_review",pipelineElapsedMs:n,pipelineResumedAt:null}}case"ui:error":{let n=t.nextToastId+1;return{...t,uiPhase:"composer",toast:{id:n,message:e.message,tone:"error"},nextToastId:n}}case"download:plan":return{...t,uiPhase:"downloading",downloads:e.entries.map(n=>({id:n.id,label:n.label,got:0,total:n.sizeBytes,done:!1,started:!1}))};case"download:start":return{...t,uiPhase:"downloading",downloads:t.downloads.map(n=>n.id===e.id?{...n,started:!0}:n)};case"download:progress":return{...t,downloads:t.downloads.map(n=>n.id===e.id?{...n,started:!0,got:e.got,total:e.total,url:e.url??n.url}:n)};case"download:complete":return{...t,downloads:t.downloads.map(n=>n.id===e.id?{...n,got:n.total||n.got,done:!0}:n)};case"weights:start":return{...t,uiPhase:"loading",loadingLabel:e.label};case"weights:label":return{...t,loadingLabel:e.label};case"weights:done":return{...t,loadingLabel:null};case"corpus:indexed":return{...t,corpusStatus:{fileCount:e.fileCount,chunkCount:e.chunkCount}};case"boot:error":return{...t,uiPhase:"boot_error",bootError:{kind:e.kind,message:e.message}};case"agent:spawn":{if(t.phase!=="research")return Bn(t,e.agentId,{phase:"idle",taskIndex:null});let n,r,o=t.pendingTaskIndex,s=t.pendingTaskDescription;t.mode==="deep"?(n=o??t.researchSpawnCount,r=s??t.plan?.tasks[n]?.description??null,o=null,s=null):(n=t.researchSpawnCount,r=t.plan?.tasks[n]?.description??null);let a=t.mode==="deep"&&n>0?`builds on Task ${n}`:null,i=Bn(t,e.agentId,{phase:"thinking",taskIndex:n,taskDescription:r,dependencyHint:a});return i={...i,researchAgentIds:[...i.researchAgentIds,e.agentId],researchSpawnCount:t.researchSpawnCount+1,pendingTaskIndex:o,pendingTaskDescription:s},Dn(i,e.agentId)}case"agent:produce":{if(t.phase==="synth"&&t.synth.open)return{...t,synth:{...t.synth,buffer:t.synth.buffer+e.text}};if(t.phase!=="research")return t;let n=t.agents.get(e.agentId);if(!n||n.taskIndex===null)return t;let r=t,o=n;if(o.phase==="content")return se(r,o.id,w=>({...w,tokenCount:e.tokenCount,contentBuffer:w.contentBuffer+e.text}));if(o.phase!=="thinking"||o.currentThinkId===null)if(o.phase==="tool"||o.phase==="idle")r=Dn(r,o.id),o=r.agents.get(o.id);else return se(r,o.id,w=>({...w,tokenCount:e.tokenCount}));let s=o.currentThinkId,a=o.timeline.find(w=>w.id===s);if(!a||a.kind!=="think")return r;let i=a.body+e.text,d=i.indexOf(On);if(d===-1)return se(r,o.id,w=>qn({...w,tokenCount:e.tokenCount},s,v=>v.kind==="think"?{...v,body:i}:v));let c=i.slice(0,d),u=i.slice(d+On.length),m=st(r,o.id,c);return se(m,o.id,w=>({...w,tokenCount:e.tokenCount,contentBuffer:u}))}case"agent:tool_call":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let a=n.timeline.find(d=>d.id===n.currentThinkId),i=a&&a.kind==="think"?a.body:"";r=st(r,e.agentId,i)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,a=>({...a,phase:"tool",toolCallCount:a.toolCallCount+1}));let o=r.nextTimelineId;return{...se(r,e.agentId,a=>it({...a,phase:"tool",toolCallCount:a.toolCallCount+1,pendingToolCallId:o,contentBuffer:""},{kind:"tool_call",id:o,tool:e.tool,argsSummary:Io(e.tool,e.args)})),nextTimelineId:r.nextTimelineId+1}}case"agent:tool_result":{let n=t.agents.get(e.agentId);if(!n)return t;if(n.taskIndex==null)return se(t,e.agentId,i=>({...i,phase:"idle"}));let r=Mo(e.tool,e.result),o=t.nextTimelineId,s=Array.from(new Set(r.hosts));return{...se(t,e.agentId,i=>it({...i,phase:"idle",pendingToolCallId:null},{kind:"tool_result",id:o,tool:e.tool,callId:n.pendingToolCallId,byteLength:e.result.length,preview:r.preview,hosts:s,resultCount:r.resultCount})),nextTimelineId:t.nextTimelineId+1,sourceCount:t.sourceCount+s.length}}case"agent:tool_progress":return t;case"agent:return":case"agent:recovered":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let u=n.timeline.find(w=>w.id===n.currentThinkId),m=u&&u.kind==="think"?u.body:"";r=st(r,e.agentId,m)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,u=>({...u,phase:"done",contentBuffer:""}));let o=r.nextTimelineId,s=se(r,e.agentId,u=>it({...u,phase:"done",contentBuffer:""},{kind:"report",id:o,body:e.result,tokenCount:u.tokenCount})),a=s.agents.get(e.agentId),i=s.researchAgentIds.includes(e.agentId),d=i&&a?[...s.scrollback,{key:`agent-${e.agentId}-${s.scrollback.length}`,kind:"agent",agent:a}]:s.scrollback,c=i?s.researchAgentIds.filter(u=>u!==e.agentId):s.researchAgentIds;return{...s,nextTimelineId:r.nextTimelineId+1,scrollback:d,researchAgentIds:c}}case"agent:done":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let o=n.timeline.find(a=>a.id===n.currentThinkId),s=o&&o.kind==="think"?o.body:"";r=st(r,e.agentId,s)}return se(r,e.agentId,o=>({...o,phase:"idle",contentBuffer:""}))}case"agent:tick":return{...t,pressure:{pct:e.nCtx>0?Math.round(100*e.cellsUsed/e.nCtx):0,cellsUsed:e.cellsUsed,nCtx:e.nCtx}};default:return t}}var On,Nn=q(()=>{"use strict";Mt();On="</think>"});import{useEffect as _o,useReducer as Oo}from"react";function Ln(t,e=[]){let[n,r]=Oo(Ot,e,o=>o.reduce(Ot,rt));return _o(()=>t.subscribe(r),[t]),n}var Fn=q(()=>{"use strict";Mt();Nn()});import{createContext as Bo,useContext as Do}from"react";function at(){return Do(Bt)}var qo,Bt,lt=q(()=>{"use strict";qo=()=>{},Bt=Bo(qo)});import{memo as No}from"react";import{Box as Lo,Text as Un}from"ink";import{jsx as $n,jsxs as Fo}from"react/jsx-runtime";var Wn,zn=q(()=>{"use strict";Wn=No(function({query:e,warm:n}){return e?Fo(Lo,{flexDirection:"column",marginBottom:1,children:[$n(Un,{bold:!0,children:e}),n?$n(Un,{dimColor:!0,children:"follow-up \xB7 warm session"}):null]}):null})});function ct(t){let e=Number.parseInt(t.slice(1),10);return!Number.isFinite(e)||e<0?Dt[0]:Dt[e%Dt.length]}var Dt,qt=q(()=>{"use strict";Dt=["cyan","yellow","green","magenta","red","blue"]});var de,ut=q(()=>{"use strict";de=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});import{memo as _e,useEffect as Uo,useState as $o}from"react";import{Box as W,Text as M}from"ink";import{jsx as R,jsxs as $}from"react/jsx-runtime";function zo(t){return Wo.includes(t.phase)}function Ho(t){let e=t.indexOf(`
|
|
4
|
+
`);if(e<=0)return"Thinking\u2026";let n=t.slice(0,e).trim();return n?n.length>72?n.slice(0,72).trimEnd()+"\u2026":n:"Thinking\u2026"}function Hn(t){let e=t.indexOf(`
|
|
5
|
+
`);return e<=0?"":t.slice(e+1).trimStart()}var Wo,Nt,Lt,Ft,Ut,Yo,jo,dt,$t=q(()=>{"use strict";qt();ut();Wo=["thinking","content","tool"];Nt=_e(function({item:e,color:n}){let r=e.live?e.body.includes(`
|
|
6
|
+
`)?Ho(e.body):"Thinking\u2026":e.title,o=e.live?Hn(e.body):Hn(e.body).trim();return $(W,{flexDirection:"column",marginBottom:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u2726 "}),R(M,{bold:!0,children:r})]}),o?R(W,{paddingLeft:2,children:$(M,{children:[o,e.live?"\u258E":""]})}):e.live?R(W,{paddingLeft:2,children:R(M,{dimColor:!0,children:"\u258E"})}):null]})});Lt=_e(function({item:e,pending:n=!1}){let[r,o]=$o(0);return Uo(()=>{if(!n)return;let s=setInterval(()=>o(a=>(a+1)%de.length),80);return()=>clearInterval(s)},[n]),$(W,{flexShrink:0,children:[n?$(M,{color:"cyan",children:[de[r]," "]}):R(M,{dimColor:!0,children:"\u203A "}),R(M,{color:"cyan",children:e.tool}),e.argsSummary?$(M,{dimColor:!0,children:[" ",e.argsSummary]}):null]})}),Ft=_e(function({item:e}){let n=e.hosts.length>0?e.hosts.join(" \xB7 "):null;return $(W,{flexDirection:"column",flexShrink:0,children:[$(W,{paddingLeft:2,children:[R(M,{color:"green",children:"\u2713 "}),R(M,{children:e.resultCount??e.byteLength+"b"}),typeof e.resultCount=="number"?R(M,{children:" results"}):null]}),n?R(W,{paddingLeft:4,children:R(M,{dimColor:!0,children:n})}):e.preview?R(W,{paddingLeft:4,children:R(M,{dimColor:!0,children:e.preview.length>60?e.preview.slice(0,60)+"\u2026":e.preview})}):null]})}),Ut=_e(function({item:e,color:n}){let r=e.body.trim();return $(W,{flexDirection:"column",marginTop:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u2713 "}),R(M,{bold:!0,children:"report"}),$(M,{dimColor:!0,children:[" \xB7 ",e.tokenCount," tok"]})]}),r?R(W,{paddingLeft:2,children:R(M,{children:r})}):null]})}),Yo=_e(function({buffer:e,color:n}){return $(W,{flexDirection:"column",marginTop:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u25B8 "}),R(M,{dimColor:!0,bold:!0,children:"streaming"})]}),R(W,{paddingLeft:2,children:$(M,{dimColor:!0,children:[e,"\u258E"]})})]})}),jo=3,dt=_e(function({agent:e,headerPrefix:n,bodyHeight:r,width:o}){let s=ct(e.label),a=zo(e),i=e.taskDescription??null,d=r+jo;return $(W,{flexDirection:"column",width:o,height:d,paddingX:1,marginRight:1,flexShrink:0,overflow:"hidden",children:[$(W,{flexShrink:0,children:[n?$(M,{dimColor:!0,children:[n," \xB7 "]}):null,R(M,{color:s,bold:!0,children:e.label}),R(W,{flexGrow:1}),R(M,{color:a?s:"green",children:a?"\u25CF":"\u2713"})]}),i?R(M,{dimColor:!0,children:i}):null,e.dependencyHint?$(M,{dimColor:!0,children:["\u2191 ",e.dependencyHint]}):null,$(W,{flexDirection:"column",flexGrow:1,justifyContent:"flex-end",overflow:"hidden",children:[e.timeline.map(c=>c.kind==="think"?R(Nt,{item:c,color:s},c.id):c.kind==="tool_call"?R(Lt,{item:c,pending:e.pendingToolCallId===c.id},c.id):c.kind==="tool_result"?R(Ft,{item:c},c.id):c.kind==="report"?R(Ut,{item:c,color:s},c.id):null),e.contentBuffer?R(Yo,{buffer:e.contentBuffer,color:s}):null]})]})})});import{Box as pt,Text as ht}from"ink";import{jsx as be,jsxs as Wt}from"react/jsx-runtime";function Yn({agent:t}){let e=ct(t.label),n=t.taskDescription?t.taskDescription.length>80?t.taskDescription.slice(0,80)+"\u2026":t.taskDescription:null;return Wt(pt,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,marginBottom:1,children:[Wt(pt,{flexShrink:0,children:[be(ht,{color:e,bold:!0,children:t.label}),be(pt,{flexGrow:1}),be(ht,{color:"green",children:"\u2713"})]}),n?be(ht,{dimColor:!0,children:n}):null,t.dependencyHint?Wt(ht,{dimColor:!0,children:["\u2191 ",t.dependencyHint]}):null,be(pt,{flexDirection:"column",children:t.timeline.map(r=>r.kind==="think"?be(Nt,{item:r,color:e},r.id):r.kind==="tool_call"?be(Lt,{item:r},r.id):r.kind==="tool_result"?be(Ft,{item:r},r.id):r.kind==="report"?be(Ut,{item:r,color:e},r.id):null)})]})}var jn=q(()=>{"use strict";qt();$t()});import{useEffect as Ko,useState as Go}from"react";import{useStdout as Qo}from"ink";function Kn(){let{stdout:t}=Qo(),[e,n]=Go(()=>[t?.columns??120,t?.rows??40]);return Ko(()=>{if(!t)return;let r=()=>{n([t.columns??120,t.rows??40])};return t.on("resize",r),()=>{t.off("resize",r)}},[t]),e}function Gn(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),r=e%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}var zt=q(()=>{"use strict"});import{Box as Ht}from"ink";import{jsx as Oe}from"react/jsx-runtime";function Vn({state:t}){let[e,n]=Kn(),r=t.researchAgentIds.map(a=>t.agents.get(a)).filter(a=>!!a);if(r.length===0)return null;let o=Math.max(Yt,n-Vo);if(t.mode==="flat"){let a=r.length,i=Math.max(Qn*a,e-4),d=Math.max(Qn,Math.floor(i/a)-1);return d*a+a<=e?Oe(Ht,{flexDirection:"row",marginBottom:1,children:r.map(u=>Oe(dt,{agent:u,headerPrefix:null,bodyHeight:o,width:d},u.id))}):Oe(Ht,{flexDirection:"column",marginBottom:1,children:r.map(u=>Oe(dt,{agent:u,headerPrefix:null,bodyHeight:Math.max(Yt,Math.floor(o/a))},u.id))})}let s=Math.max(Yt,Math.floor(o/Math.max(1,r.length)));return Oe(Ht,{flexDirection:"column",marginBottom:1,children:r.map(a=>Oe(dt,{agent:a,headerPrefix:`Task ${(a.taskIndex??0)+1}`,bodyHeight:s},a.id))})}var Vo,Qn,Yt,Xn=q(()=>{"use strict";$t();zt();Vo=18,Qn=26,Yt=10});import{Box as je,Text as ve}from"ink";import{jsx as Re,jsxs as Ke}from"react/jsx-runtime";function Jn({state:t}){let{synth:e}=t;if(!e.open&&!e.done)return null;let n=e.done?Ke(je,{children:[Re(ve,{bold:!0,children:"Synthesis "}),Re(ve,{color:"green",children:"\u2713"}),e.stats?Ke(ve,{dimColor:!0,children:[" ","\xB7 ",e.stats.tokens," tok \xB7 ",e.stats.toolCalls," tools \xB7"," ",Number.isFinite(e.stats.ppl)?`ppl ${e.stats.ppl.toFixed(2)} \xB7 `:"",Xo(e.stats.timeMs)]}):null]}):Ke(je,{children:[Re(ve,{bold:!0,children:"Synthesis"}),Re(ve,{color:"cyan",children:" \u25CF"})]}),r=e.buffer.trim();return Ke(je,{flexDirection:"column",marginBottom:1,children:[n,e.open&&r?Re(je,{paddingLeft:2,marginTop:0,children:Ke(ve,{children:[r,"\u258E"]})}):e.open?Re(je,{paddingLeft:2,children:Re(ve,{dimColor:!0,children:"\u258E"})}):null]})}var Xo,Zn=q(()=>{"use strict";Xo=t=>`${(t/1e3).toFixed(1)}s`});import{Box as er,Text as tr}from"ink";import{jsx as jt,jsxs as Jo}from"react/jsx-runtime";function nr({state:t}){return!t.answer||t.synth.done&&t.synth.buffer.trim().length>0?null:Jo(er,{flexDirection:"column",marginBottom:1,children:[jt(tr,{dimColor:!0,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"}),jt(er,{marginTop:1,paddingLeft:2,children:jt(tr,{children:t.answer.trim()})})]})}var rr=q(()=>{"use strict"});import{useEffect as Zo,useState as es}from"react";import{Box as or,Text as ae}from"ink";import{Fragment as ss,jsx as pe,jsxs as Ge}from"react/jsx-runtime";function ts(t,e=12){let n=Math.min(e,Math.max(0,Math.round(t/100*e)));return"\u2588".repeat(n)+"\u2591".repeat(e-n)}function ns(t){return t>=90?"red":t>=70?"yellow":"green"}function rs(t){let e=0;for(let n of t.agents.values())n.phase!=="done"&&n.phase!=="idle"&&e++;return e}function os(t){let e=t.pipelineResumedAt,[,n]=es(0);return Zo(()=>{if(e===null)return;let r=setInterval(()=>n(o=>o+1),250);return()=>clearInterval(r)},[e]),e===null?t.pipelineElapsedMs:t.pipelineElapsedMs+(Date.now()-e)}function sr({state:t}){let e=os(t),n=t.pressure?.pct??0,r=rs(t),o=ns(n);return pe(or,{borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,paddingTop:0,children:Ge(or,{flexDirection:"row",children:[pe(ae,{dimColor:!0,children:"KV "}),pe(ae,{color:o,children:ts(n)}),Ge(ae,{children:[" ",String(n).padStart(2," "),"%"]}),pe(ae,{dimColor:!0,children:" \xB7 "}),pe(ae,{children:t.phase}),pe(ae,{dimColor:!0,children:" \xB7 \u23F1 "}),pe(ae,{children:Gn(e)}),pe(ae,{dimColor:!0,children:" \xB7 "}),Ge(ae,{children:[r," active"]}),t.sourceCount>0?Ge(ss,{children:[pe(ae,{dimColor:!0,children:" \xB7 "}),pe(ae,{dimColor:!0,children:"\u2315 "}),Ge(ae,{children:[t.sourceCount," sources"]})]}):null]})})}var ir=q(()=>{"use strict";zt()});import{useState as is}from"react";import{Text as Be,useInput as as}from"ink";import{jsx as mt,jsxs as lr}from"react/jsx-runtime";function xe({value:t,onChange:e,onSubmit:n,onCancel:r,placeholder:o="",focused:s=!0,mask:a=!1,color:i}){let[d,c]=is(t.length),u=Math.min(d,t.length);as((p,g)=>{if(g.return){n?.(t);return}if(g.escape){r?.();return}if(g.leftArrow){g.meta||g.ctrl?c(ar(t,u)):c(Math.max(0,u-1));return}if(g.rightArrow){g.meta||g.ctrl?c(ls(t,u)):c(Math.min(t.length,u+1));return}if(p==="\x1B[H"||p==="\x1BOH"){c(0);return}if(p==="\x1B[F"||p==="\x1BOF"){c(t.length);return}if(g.backspace||g.delete){if(u===0)return;if(g.meta||g.ctrl){let A=ar(t,u);e(t.slice(0,A)+t.slice(u)),c(A);return}let C=t.slice(0,u-1)+t.slice(u);c(u-1),e(C);return}if(g.ctrl&&p==="a"){c(0);return}if(g.ctrl&&p==="e"){c(t.length);return}if(g.ctrl&&p==="u"){e(t.slice(u)),c(0);return}if(g.ctrl&&p==="k"){e(t.slice(0,u));return}if(g.ctrl&&p==="w"){let C=t.slice(0,u),A=/\S+\s*$/.exec(C),T=A?A.index:0;e(t.slice(0,T)+t.slice(u)),c(T);return}if(!(g.ctrl||g.meta||g.tab||g.upArrow||g.downArrow)&&p.length>0){let C=t.slice(0,u)+p+t.slice(u);c(u+p.length),e(C)}},{isActive:s});let m=a?"*".repeat(t.length):t;if(t.length===0)return lr(Be,{children:[mt(Be,{color:i,children:s?"\u258E":""}),mt(Be,{dimColor:!0,children:o})]});if(!s)return mt(Be,{color:i,children:m});let v=m.slice(0,u),L=m.slice(u,u+1),P=m.slice(u+1);return lr(Be,{color:i,children:[v,mt(Be,{inverse:!0,children:L||" "}),P]})}function ar(t,e){if(e<=0)return 0;let n=e;for(;n>0&&/\s/.test(t[n-1]);)n--;for(;n>0&&!/\s/.test(t[n-1]);)n--;return n}function ls(t,e){let n=t.length;if(e>=n)return n;let r=e;for(;r<n&&/\s/.test(t[r]);)r++;for(;r<n&&!/\s/.test(t[r]);)r++;return r}var Kt=q(()=>{"use strict"});import{memo as qe,useEffect as Gt,useState as De}from"react";import{Box as ee,Text as O,useInput as cs}from"ink";import{jsx as k,jsxs as re}from"react/jsx-runtime";function cr(t){if(!t.startsWith("/"))return null;let e=t.slice(1).trimStart();if(!e)return{name:"",value:""};let n=e.search(/\s/),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1).trim();return{name:r,value:o}}function us(t){if(!t)return[];if(!t.name)return ft;let e=t.name.toLowerCase();return ft.filter(n=>n.name.startsWith(e))}var ft,pr,ur,Qt,ds,ps,dr,hr=q(()=>{"use strict";lt();Kt();ft=[{name:"scan",desc:"Set local file source (path or glob)",kind:"value"},{name:"web",desc:"Set web search key",kind:"value"},{name:"model",desc:"Set local LLM .gguf path",kind:"value"},{name:"reranker",desc:"Set local reranker .gguf path",kind:"value"},{name:"output",desc:"Set output directory",kind:"value"},{name:"deep",desc:"Use deep (chain) reasoning",kind:"instant"},{name:"flat",desc:"Use flat (parallel) reasoning",kind:"instant"},{name:"help",desc:"Show this list",kind:"instant"},{name:"quit",desc:"Quit",kind:"instant"}];pr=qe(function({state:e}){let n=at(),r=e.config?.defaults.reasoningMode??"flat",[o,s]=De(r),[a,i]=De("query"),[d,c]=De(""),[u,m]=De(""),[w,v]=De(!1),L=e.scrollback.length>0,[P,p]=De(L?"start":"plan");Gt(()=>{L&&p("start")},[L]),Gt(()=>{e.composerPrefill&&e.composerPrefill!==d&&c(e.composerPrefill)},[e.composerPrefill]),Gt(()=>{s(r)},[r]);let g=e.configOrigin?.tavilyKey??"unset",C=e.configOrigin?.corpusPath??"unset",A=e.configOrigin?.outputDir??"default",T=g!=="unset",F=T||C!=="unset",J=g==="env",K=e.clarifyContext!==null,B=cr(d),D=B!==null,U=us(B);cs((x,h)=>{if(h.ctrl&&x==="c"){n({type:"quit"});return}if(h.tab&&h.shift){!D&&!K&&p(l=>l==="plan"?"start":"plan");return}if(h.tab){if(D&&B&&B.name&&U.length===1){let l=U[0];c("/"+l.name+(l.kind==="value"?" ":""));return}return}if(h.escape){if(K){n({type:"cancel_plan"}),c("");return}c(""),v(!1);return}},{isActive:a==="query"});let Se=x=>{let h=x.trim();if(h){if(!K){let l=cr(h);if(l){Ee(l);return}}if(K){n({type:"submit_clarification",answer:h}),c("");return}F&&(n({type:"submit_query",query:h,mode:o,skipPlanner:P==="start"}),c(""))}},Ee=({name:x,value:h})=>{if(!x)return;let l=ft.find(f=>f.name===x);if(l){if(c(""),v(!1),l.kind==="instant"){x==="deep"?s("deep"):x==="flat"?s("flat"):x==="quit"?n({type:"quit"}):x==="help"&&v(!0);return}if(h){x==="web"?n({type:"set_tavily_key",key:h}):x==="scan"?n({type:"set_corpus_path",path:h}):x==="output"?n({type:"set_output_dir",path:h}):x==="model"?n({type:"set_model_path",path:h}):x==="reranker"&&n({type:"set_reranker_path",path:h});return}if(x==="web"){if(J)return;m(e.config?.sources.tavilyKey??""),i("web")}else x==="scan"?(m(e.config?.sources.corpusPath??""),i("scan")):x==="output"?(m(e.config?.sources.outputDir??""),i("output")):x==="model"?(m(e.config?.model.path??""),i("model")):x==="reranker"&&(m(e.config?.model.reranker??""),i("reranker"))}};return re(ee,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[a==="query"?re(ee,{children:[k(O,{children:"\u203A "}),k(xe,{value:d,onChange:c,onSubmit:Se,focused:!0,placeholder:K?"Answer the questions above, or Esc to cancel\u2026":F?"Ask a research question, or / for commands\u2026":"Type / for commands (e.g. /web, /scan) to add a source"})]}):a==="web"?re(ee,{children:[k(O,{color:"yellow",children:"Web search key \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_tavily_key",key:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,mask:!0,placeholder:"tvly-..."})]}):a==="scan"?re(ee,{children:[k(O,{color:"yellow",children:"Scan path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_corpus_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/docs or /path/**/*.md"})]}):a==="output"?re(ee,{children:[k(O,{color:"yellow",children:"Output dir \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_output_dir",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:`${process.cwd()} (default)`})]}):a==="model"?re(ee,{children:[k(O,{color:"yellow",children:"Model path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_model_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/qwen3.5-4b.gguf"})]}):re(ee,{children:[k(O,{color:"yellow",children:"Reranker path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_reranker_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/qwen3-reranker.gguf"})]}),a==="query"&&!K&&D?k(ee,{flexDirection:"column",marginTop:0,children:U.length===0?k(O,{color:"red",children:"no matching command"}):U.map(x=>k(ur,{cmd:x},x.name))}):null,a==="query"&&!D&&w?k(ee,{flexDirection:"column",marginTop:0,children:ft.map(x=>k(ur,{cmd:x},x.name))}):null,re(ee,{marginTop:0,children:[k(Qt,{label:"Web",origin:g,value:T?"set":null,disabled:J}),k(O,{children:" "}),k(Qt,{label:"Scan",origin:C,value:e.config?.sources.corpusPath?e.corpusStatus?`${e.corpusStatus.fileCount} files`:e.config.sources.corpusPath:null}),k(O,{children:" "}),k(Qt,{label:"Output",origin:A,value:e.config?.sources.outputDir??null}),k(ee,{flexGrow:1}),a==="query"&&!K&&!D?k(ps,{submitMode:P}):null]}),k(ee,{marginTop:0,children:k(ds,{field:a,hasSource:F,inSlash:D,clarifying:K})}),e.toast?k(ee,{marginTop:0,children:k(O,{color:e.toast.tone==="error"?"red":e.toast.tone==="warn"?"yellow":"green",children:e.toast.message})}):null]})}),ur=qe(function({cmd:e}){return re(ee,{children:[re(O,{color:"cyan",children:["/",e.name]}),re(O,{dimColor:!0,children:[" \xB7 ",e.desc]}),e.kind==="value"?k(O,{dimColor:!0,children:" <value>"}):null]})}),Qt=qe(function({label:e,origin:n,value:r,disabled:o=!1}){let s=n!=="unset";return re(O,{children:[re(O,{color:s?"green":"gray",dimColor:o,children:[e," ",s?e==="Scan"&&r?r:"\u2713":"\u2014"]}),k(O,{dimColor:!0,children:n==="env"?" (env)":n==="cli"?" (cli)":""})]})}),ds=qe(function({field:e,hasSource:n,inSlash:r,clarifying:o}){return e==="web"||e==="scan"||e==="output"||e==="model"||e==="reranker"?k(O,{dimColor:!0,children:"\u23CE save (empty to clear) \xB7 Ctrl+U clear \xB7 Esc cancel"}):o?k(O,{color:"yellow",children:"\u23CE submit answer \xB7 Esc cancel"}):r?k(O,{dimColor:!0,children:"Tab complete \xB7 \u23CE run \xB7 Esc clear"}):n?k(O,{dimColor:!0,children:"\u21E7Tab Plan/Start \xB7 / commands"}):k(O,{color:"yellow",children:"\u26A0 Add a source via /web or /scan"})}),ps=qe(function({submitMode:e}){return re(ee,{children:[k(dr,{label:"PLAN",focused:e==="plan",hue:"cyan"}),k(O,{children:" "}),k(dr,{label:"START",focused:e==="start",hue:"green"})]})}),dr=qe(function({label:e,focused:n,hue:r}){let s=` ${n?"\u25C9":"\u25CB"} ${e} `;return n?k(O,{backgroundColor:r,color:"black",bold:!0,children:s}):k(O,{dimColor:!0,children:s})})});import{memo as Vt,useEffect as mr,useRef as hs,useState as gt}from"react";import{Box as Y,Text as _,useInput as ms}from"ink";import{jsx as E,jsxs as Q}from"react/jsx-runtime";var fr,fs,gs,gr=q(()=>{"use strict";lt();Kt();fr=Vt(function({state:e}){let n=at(),r=e.plan,[o,s]=gt(e.mode??"flat"),[a,i]=gt(()=>r?.tasks.length??0),[d,c]=gt(null),[u,m]=gt("");mr(()=>{e.mode&&e.mode!==o&&s(e.mode),c(null),i(r?.tasks.length??0)},[e.mode]),mr(()=>{r&&a>r.tasks.length&&i(r.tasks.length)},[r?.tasks.length]);let w=hs({focusedIndex:a,editingIndex:d,mode:o,plan:r,query:e.query});if(w.current={focusedIndex:a,editingIndex:d,mode:o,plan:r,query:e.query},ms((P,p)=>{let g=w.current,C=g.plan,A=g.editingIndex,T=g.focusedIndex,le=g.mode;if(!C||A!==null)return;if(C.intent!=="research"){if(p.return){C.intent==="clarify"&&n({type:"edit_plan",query:g.query});return}p.escape&&n({type:"cancel_plan"}),p.ctrl&&P==="c"&&n({type:"quit"});return}if(p.ctrl&&P==="c"){n({type:"quit"});return}if(p.escape){n({type:"cancel_plan"});return}let F=T>=C.tasks.length;if(p.shift&&p.upArrow){!F&&T>0&&(n({type:"move_task",from:T,to:T-1}),i(T-1));return}if(p.shift&&p.downArrow){!F&&T<C.tasks.length-1&&(n({type:"move_task",from:T,to:T+1}),i(T+1));return}if(p.upArrow){i(Math.max(0,T-1));return}if(p.downArrow){i(Math.min(C.tasks.length,T+1));return}if(p.return){F?n({type:"accept_plan"}):(m(C.tasks[T]?.description??""),c(T));return}if(P==="a"||P==="A"||P==="+"){let J=F?C.tasks.length-1:T,K=J+1;n({type:"add_task",afterIndex:J}),i(K),m(""),c(K);return}if(P==="d"||P==="D"||p.delete){!F&&C.tasks.length>1&&n({type:"delete_task",index:T});return}if(P==="t"||P==="T"){let J=le==="deep"?"flat":"deep";s(J),n({type:"change_mode",mode:J});return}}),!r)return null;if(r.intent==="clarify")return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(Y,{marginBottom:1,children:E(_,{bold:!0,children:e.query})}),E(_,{dimColor:!0,children:"A few questions to narrow this down."}),E(Y,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.clarifyQuestions.map((P,p)=>Q(_,{children:[Q(_,{dimColor:!0,children:["(",p+1,")"]})," ",P]},p))}),E(Y,{marginTop:1,children:E(_,{dimColor:!0,children:"\u23CE answer \xB7 Esc cancel"})})]});if(r.intent==="passthrough")return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(_,{bold:!0,children:e.query}),E(_,{dimColor:!0,children:"Answering directly \u2014 no research needed."})]});let v=o==="flat"?"parallel":"chained",L=d!==null;return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(Y,{marginBottom:1,children:E(_,{bold:!0,children:e.query})}),Q(Y,{marginBottom:1,children:[E(_,{dimColor:!0,children:"Research plan"}),Q(_,{dimColor:!0,children:[" \xB7 ",r.tasks.length," ",v," tasks"]}),L?Q(_,{color:"yellow",children:[" \xB7 editing row ",d+1]}):null]}),Q(Y,{flexDirection:"column",children:[r.tasks.map((P,p)=>E(gs,{index:p,description:P.description,focused:p===a,editing:p===d,draft:u,onDraftChange:m,onSubmit:g=>{n({type:"update_task_description",index:p,description:g.trim()}),c(null)},onCancel:()=>c(null)},p)),E(fs,{focused:a>=r.tasks.length&&!L})]}),Q(Y,{marginTop:1,children:[Q(_,{color:o==="deep"?"cyan":void 0,bold:o==="deep",children:[o==="deep"?"\u25C6":"\u25CB"," Deep"]}),E(_,{children:" "}),Q(_,{color:o==="flat"?"cyan":void 0,bold:o==="flat",children:[o==="flat"?"\u25C6":"\u25CB"," Flat"]}),E(_,{dimColor:!0,children:" T toggle mode (re-plans, discards edits)"})]}),E(Y,{marginTop:1,children:L?E(_,{dimColor:!0,children:"\u23CE save \xB7 Esc revert"}):Q(_,{dimColor:!0,children:["\u2191\u2193 select \xB7 \u23CE ",a>=r.tasks.length?"start research":"edit"," \xB7 A add \xB7 D delete \xB7 \u21E7\u2191\u2193 reorder \xB7 Esc cancel"]})})]})}),fs=Vt(function({focused:e}){return e?E(Y,{paddingLeft:2,marginTop:1,children:E(_,{backgroundColor:"green",color:"black",bold:!0,children:" \u25B6 START research "})}):E(Y,{paddingLeft:2,marginTop:1,children:E(_,{dimColor:!0,children:" \u25B6 START research"})})}),gs=Vt(function({index:e,description:n,focused:r,editing:o,draft:s,onDraftChange:a,onSubmit:i,onCancel:d}){return o?Q(Y,{paddingLeft:2,children:[E(_,{color:"yellow",bold:!0,children:`\u25B6 ${e+1}. `}),E(Y,{flexGrow:1,children:E(xe,{value:s,onChange:a,onSubmit:i,onCancel:d,focused:!0,placeholder:"(empty \u2014 type a task description)"})})]}):r?Q(Y,{paddingLeft:2,children:[E(_,{color:"cyan",bold:!0,children:`\u203A ${e+1}. `}),E(_,{bold:!0,children:n||E(_,{dimColor:!0,children:"(empty)"})})]}):Q(Y,{paddingLeft:2,children:[E(_,{dimColor:!0,children:` ${e+1}. `}),E(_,{dimColor:!0,children:n||"(empty)"})]})})});import{memo as ys,useEffect as bs,useState as xs}from"react";import{Box as yr,Text as Xt}from"ink";import{jsx as br,jsxs as Jt}from"react/jsx-runtime";var xr,kr=q(()=>{"use strict";ut();xr=ys(function({state:e}){let[n,r]=xs(0);return bs(()=>{let o=setInterval(()=>r(s=>(s+1)%de.length),80);return()=>clearInterval(o)},[]),Jt(yr,{flexDirection:"column",marginBottom:1,children:[br(Xt,{bold:!0,children:e.query}),Jt(yr,{marginTop:1,children:[Jt(Xt,{color:"cyan",children:[de[n]," "]}),br(Xt,{dimColor:!0,children:"Planning\u2026"})]})]})})});import{memo as ks}from"react";import{Box as wr,Text as yt}from"ink";import{jsx as Zt,jsxs as en}from"react/jsx-runtime";var Tr,Sr=q(()=>{"use strict";Tr=ks(function({state:e}){if(!e.clarifyContext)return null;let{originalQuery:n,questions:r}=e.clarifyContext;return en(wr,{flexDirection:"column",marginBottom:1,children:[Zt(yt,{bold:!0,children:n}),Zt(yt,{dimColor:!0,children:"A few questions to narrow this down."}),Zt(wr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.map((o,s)=>en(yt,{children:[en(yt,{dimColor:!0,children:["(",s+1,")"]})," ",o]},s))})]})})});import{memo as Cr,useEffect as ws,useState as Ts}from"react";import{Box as Pe,Text as N}from"ink";import{Fragment as vs,jsx as oe,jsxs as V}from"react/jsx-runtime";function Cs(t){try{return new URL(t).host}catch{return null}}function bt(t){return t>=1e9?(t/1e9).toFixed(1)+" GB":t>=1e6?(t/1e6).toFixed(0)+" MB":t>=1e3?(t/1e3).toFixed(0)+" KB":`${t} B`}var vr,Ss,Rr=q(()=>{"use strict";ut();vr=Cr(function({state:e}){let[n,r]=Ts(0);if(ws(()=>{let o=setInterval(()=>r(s=>(s+1)%de.length),80);return()=>clearInterval(o)},[]),e.uiPhase==="boot_error"){let o=e.bootError,s=o?.kind??"llm",a=s==="llm"?"LLM":"reranker",i=s==="llm"?"/model":"/reranker",d=s==="llm"?"/reranker":"/model";return V(Pe,{flexDirection:"column",marginBottom:1,children:[V(N,{color:"red",bold:!0,children:["\u2717 Boot failed (",a,")"]}),oe(Pe,{paddingLeft:2,children:oe(N,{children:o?.message??"Unknown error"})}),oe(Pe,{paddingLeft:2,marginTop:1,children:V(N,{dimColor:!0,children:["Type ",V(N,{color:"cyan",children:[i," "]}),oe(N,{dimColor:!0,children:"<path-to-gguf>"}),V(N,{dimColor:!0,children:[" to use a local ",a,", or "]}),oe(N,{color:"cyan",children:d}),oe(N,{dimColor:!0,children:" for the other, or "}),oe(N,{color:"cyan",children:"/quit"}),oe(N,{dimColor:!0,children:" to exit."})]})})]})}return e.uiPhase==="downloading"?V(Pe,{flexDirection:"column",marginBottom:1,children:[V(Pe,{children:[V(N,{color:"cyan",children:[de[n]," "]}),oe(N,{bold:!0,children:"Downloading models"})]}),e.downloads.map(o=>oe(Ss,{item:o},o.id))]}):V(Pe,{marginBottom:1,children:[V(N,{color:"cyan",children:[de[n]," "]}),oe(N,{bold:!0,children:e.loadingLabel??"Loading\u2026"})]})}),Ss=Cr(function({item:e}){let n=e.total>0?Math.min(100,Math.floor(e.got/e.total*100)):0,r=16,o=Math.floor(n/100*r),s="\u2588".repeat(o)+"\u2591".repeat(r-o),a=e.url?Cs(e.url):null,i=e.started&&a!==null,d=e.done?"\u2713 ":i?"\u25CF ":"\u25CB ",c=e.done?"green":i?"cyan":void 0,u=!i&&!e.done;return V(Pe,{paddingLeft:2,children:[oe(N,{color:c,dimColor:u,children:d}),V(N,{dimColor:u,children:[e.label.padEnd(28)," "]}),e.done?oe(N,{dimColor:!0,children:bt(e.got)}):i?V(vs,{children:[oe(N,{color:"cyan",children:s}),V(N,{children:[" ",String(n).padStart(2),"% \xB7 ",bt(e.got)," / ",bt(e.total)]}),V(N,{dimColor:!0,children:[" \xB7 ",a]})]}):V(N,{dimColor:!0,children:["queued \xB7 ",bt(e.total)]})]})})});import{Box as xt,Static as Rs,Text as Pr}from"ink";import{jsx as X,jsxs as tn}from"react/jsx-runtime";function Ar({bus:t,dispatch:e,bootstrap:n}){let r=Ln(t,n),o=r.uiPhase!=="composer"&&r.uiPhase!=="boot"&&r.uiPhase!=="downloading"&&r.uiPhase!=="loading"&&r.uiPhase!=="planning"&&r.uiPhase!=="plan_review"&&r.uiPhase!=="clarifying",s=r.uiPhase==="research"||r.uiPhase==="done",a=r.uiPhase==="composer"||r.uiPhase==="done"||r.uiPhase==="clarifying"||r.uiPhase==="boot_error";return tn(Bt.Provider,{value:e,children:[X(Rs,{items:r.scrollback,children:i=>i.kind==="agent"?X(xt,{paddingX:2,children:X(Yn,{agent:i.agent})},i.key):tn(xt,{flexDirection:"column",paddingX:2,marginBottom:1,children:[X(Pr,{dimColor:!0,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"}),X(xt,{paddingLeft:2,marginTop:1,children:X(Pr,{children:i.body})})]},i.key)}),tn(xt,{flexDirection:"column",paddingX:2,paddingY:1,children:[o&&X(Wn,{query:r.query,warm:r.warm}),(r.uiPhase==="downloading"||r.uiPhase==="loading"||r.uiPhase==="boot_error")&&X(vr,{state:r}),r.uiPhase==="planning"&&X(xr,{state:r}),r.uiPhase==="plan_review"&&X(fr,{state:r}),r.uiPhase==="clarifying"&&X(Tr,{state:r}),s&&X(Vn,{state:r}),s&&X(Jn,{state:r}),r.uiPhase==="done"&&X(nr,{state:r}),a&&X(pr,{state:r}),X(sr,{state:r})]})]})}var Er=q(()=>{"use strict";Fn();lt();zn();jn();Xn();Zn();rr();ir();hr();gr();kr();Sr();Rr()});var Ir={};Wr(Ir,{render:()=>Es});import Ps from"react";import{render as As}from"ink";function Es(t,e,n=[]){return As(Ps.createElement(Ar,{bus:t,dispatch:e,bootstrap:n}),{incrementalRendering:!0})}var Mr=q(()=>{"use strict";Er()});import*as H from"node:fs";import*as ge from"node:path";import{parseArgs as Is}from"node:util";import{main as Ms,ensure as kt,createSignal as _s,spawn as _r,each as Ae,call as Fe}from"effection";import{createContext as Os}from"@lloyal-labs/lloyal.node";import{initAgents as Bs,JsonlTraceWriter as Ds}from"@lloyal-labs/lloyal-agents";var wt=!1,zr=!1;function un(t){wt=t}function dn(t){zr=t}var Tt=!!process.stdout.isTTY,St=Tt?{bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m",green:"\x1B[32m",cyan:"\x1B[36m",yellow:"\x1B[33m",red:"\x1B[31m"}:{bold:"",dim:"",reset:"",green:"",cyan:"",yellow:"",red:""},cn="";function Hr(){cn&&(cn="",process.stdout.write("\r\x1B[K"))}var Je=(...t)=>{wt||(Hr(),console.log(...t))};function pn(t,e){wt&&console.log(JSON.stringify({event:t,...e}))}import*as ne from"node:fs";import*as Z from"node:path";import*as Ct from"node:os";import*as Ze from"node:path";function ke(t){if(!t)return"";let e=t==="~"?Ct.homedir():t.startsWith("~/")?Ze.join(Ct.homedir(),t.slice(2)):t;return Ze.resolve(e)}function vt(){return{version:1,sources:{},defaults:{reasoningMode:"flat",maxTurns:10},model:{}}}function mn(t){try{let e=ne.readFileSync(t,"utf8"),n=JSON.parse(e);if(n.version!==1)return null;let r=vt();return{version:1,sources:{...r.sources,...n.sources??{}},defaults:{...r.defaults,...n.defaults??{}},model:{...r.model,...n.model??{}}}}catch{return null}}function Ce(t,e,n=process.env){let r=Z.resolve(t),o=mn(r),s=o??vt(),a=n.TAVILY_API_KEY?.trim()||void 0,i=n.LLAMA_CTX_SIZE?.trim(),d=i&&/^\d+$/.test(i)?parseInt(i,10):void 0,c=e.tavilyKey??a??s.sources.tavilyKey,u=e.corpusPath??s.sources.corpusPath,m=u?ke(u):void 0,w=e.outputDir??s.sources.outputDir,v=w?ke(w):void 0,L=e.reasoningMode??s.defaults.reasoningMode??"flat",P=e.modelPath??s.model.path,p=P?ke(P):void 0,g=e.reranker??s.model.reranker,C=e.nCtx??d??s.model.nCtx,A={version:1,sources:{tavilyKey:c,corpusPath:m,outputDir:v},defaults:{reasoningMode:L,maxTurns:s.defaults.maxTurns},model:{path:p,reranker:g,nCtx:C}},T={tavilyKey:e.tavilyKey?"cli":a?"env":s.sources.tavilyKey?"file":"unset",corpusPath:e.corpusPath?"cli":s.sources.corpusPath?"file":"unset",reasoningMode:e.reasoningMode?"cli":o?.defaults.reasoningMode?"file":"default",modelPath:e.modelPath?"cli":o?.model.path?"file":"default",reranker:e.reranker?"cli":o?.model.reranker?"file":"default",nCtx:e.nCtx!==void 0?"cli":d!==void 0?"env":o?.model.nCtx!==void 0?"file":"default",outputDir:e.outputDir?"cli":o?.sources.outputDir?"file":"default"};return{config:A,origin:T,path:r,loadedFromFile:!!o}}function we(t,e,n=process.env){let r=Z.resolve(e),o=mn(r)??vt(),s=[],a={...o.sources,...t.sources??{}};t.sources?.tavilyKey===""&&delete a.tavilyKey,t.sources?.corpusPath===""&&delete a.corpusPath,t.sources?.outputDir===""&&delete a.outputDir,n.TAVILY_API_KEY&&t.sources&&"tavilyKey"in t.sources&&(delete a.tavilyKey,s.push("sources.tavilyKey"));let i={version:1,sources:a,defaults:{...o.defaults,...t.defaults??{}},model:{...o.model,...t.model??{}}},d=Z.dirname(r);ne.mkdirSync(d,{recursive:!0});let c=r+".tmp-"+process.pid;ne.writeFileSync(c,JSON.stringify(i,null,2)+`
|
|
7
|
+
`,"utf8"),ne.renameSync(c,r);let u=Yr(r);return{path:r,gitignored:u,skipped:s}}function Yr(t){try{let e=jr(Z.dirname(t));if(!e)return!1;let n=Z.join(e,".gitignore"),r=Z.relative(e,t).replace(/\\/g,"/"),o=ne.existsSync(n)?ne.readFileSync(n,"utf8"):"",s=Z.basename(t);if(new RegExp(`(^|\\n)\\s*(${hn(r)}|${hn(s)})\\s*(\\n|$)`).test(o))return!1;let i=o.length===0||o.endsWith(`
|
|
8
8
|
`)?"":`
|
|
9
9
|
`;return ne.appendFileSync(n,i+r+`
|
|
10
|
-
`),!0}catch{return!1}}function hn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function
|
|
10
|
+
`),!0}catch{return!1}}function hn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jr(t){let e=Z.resolve(t);for(;;){if(ne.existsSync(Z.join(e,".git")))return e;let n=Z.dirname(e);if(n===e)return null;e=n}}function fn(){let t=[],e=new Set;return{send(n){if(t!==null){t.push(n);return}for(let r of e)r(n)},subscribe(n){if(e.add(n),t!==null){let r=t;t=null;for(let o of r)n(o)}return()=>{e.delete(n)}}}}import{TavilyProvider as qs}from"@lloyal-labs/rig";import{createReranker as Ns,WebSource as Ls,CorpusSource as Fs,chunkResources as Us,resolveCorpusInput as $s}from"@lloyal-labs/rig/node";import Ws from"ignore";import{call as Rt}from"effection";import{Ctx as At,Events as et,agentPool as no,useAgent as ro,chain as oo,parallel as so,renderTemplate as $e,withSpine as io,DefaultAgentPolicy as An}from"@lloyal-labs/lloyal-agents";import{reportTool as ao,PlanTool as lo}from"@lloyal-labs/rig";import{taskToContent as vn}from"@lloyal-labs/rig";var gn=`You're a research planner. You analyze a user query and pick ONE of three dispositions, producing a JSON plan. Output JSON only.
|
|
11
11
|
---
|
|
12
12
|
The query: "<%= it.query %>"
|
|
13
13
|
|
|
@@ -601,15 +601,15 @@ ASSISTANT calls: report({"summary": "(no findings \u2014 no corpus inspection pe
|
|
|
601
601
|
<% } -%>
|
|
602
602
|
`;function Ie(t){let e=t.trim(),n=e.indexOf(`
|
|
603
603
|
---
|
|
604
|
-
`);return n===-1?{system:e,user:""}:{system:e.slice(0,n).trim(),user:e.slice(n+5).trim()}}var
|
|
604
|
+
`);return n===-1?{system:e,user:""}:{system:e.slice(0,n).trim(),user:e.slice(n+5).trim()}}var co=Ie(gn),uo=Ie(yn),po=Ie(bn),ho=Ie(xn),mo=Ie(kn),fo=Ie(wn),go=Tn,yo=Sn,bo=Cn;function xo(){return new An({budget:{context:{softLimit:2048,hardLimit:1024},time:{softLimit:24e4,hardLimit:36e4}},recovery:{prompt:ho},terminalToolName:"report"})}var Pt=class extends An{onProduced(...e){let[,n]=e;return!n.toolCalls[0]&&n.content?{type:"free_text_return",content:n.content}:super.onProduced(...e)}};function Rn(t,e){return t.promptData?$e(go,{...t.promptData(),...e}):t.name==="web"?$e(yo,e):po.system}function En(){return new Date().toISOString().slice(0,10)}function Pn(){let t=performance.now();return()=>performance.now()-t}function Et(t){return{intent:"research",tasks:[{description:t}],clarifyQuestions:[],tokenCount:0,timeMs:0}}function*ko(t,e){let n=e.trunk;if(!n)throw new Error("runPassthrough: session has no trunk");let r=yield*At.expect(),o=r.getTurnSeparator(),{prompt:s}=r.formatChatSync(JSON.stringify([{role:"user",content:t}]),{addGenerationPrompt:!0,enableThinking:!1}),a=[...o,...r.tokenizeSync(s,!1)];yield*Rt(()=>n.prefill(a));let i=performance.now(),d=0,c=[];for(;;){let{token:u,text:m,isStop:w}=n.produceSync();if(w)break;yield*Rt(()=>n.commit(u)),d++,c.push(m)}return{answer:c.join(""),tokenCount:d,timeMs:performance.now()-i}}function*wo(t,e,n){let r=yield*et.expect(),o=u=>r.send(u);yield*o({type:"query",query:t,warm:!!e.trunk});let s=En(),a=n.reasoningMode==="flat"?uo:co,i=new lo({prompt:a,session:e,maxQuestions:10}),d=n.context?`Today's date: ${s}
|
|
605
605
|
|
|
606
|
-
${n.context}`:`Today's date: ${s}`,c=yield*i.execute({query:t,context:d});return yield*o({type:"plan",intent:c.intent,tasks:c.tasks,clarifyQuestions:c.clarifyQuestions,tokenCount:c.tokenCount,timeMs:c.timeMs}),c}function*Me(t,e,n,r,o){let s=yield*et.expect(),a=d=>s.send(d);yield*a({type:"plan:start",query:t,mode:o.reasoningMode});let i=yield*
|
|
606
|
+
${n.context}`:`Today's date: ${s}`,c=yield*i.execute({query:t,context:d});return yield*o({type:"plan",intent:c.intent,tasks:c.tasks,clarifyQuestions:c.clarifyQuestions,tokenCount:c.tokenCount,timeMs:c.timeMs}),c}function*Me(t,e,n,r,o){let s=yield*et.expect(),a=d=>s.send(d);yield*a({type:"plan:start",query:t,mode:o.reasoningMode});let i=yield*wo(t,e,{reasoningMode:o.reasoningMode,context:o.context});if(i.intent==="clarify")return{type:"clarify",plan:i};if(i.intent==="passthrough"){if(!e.trunk){let c=Et(t);return o.onStart?.(),yield*We(t,c,e,n,r,{...o}),{type:"done"}}o.onStart?.();let d=yield*ko(t,e);return yield*a({type:"answer",text:d.answer}),yield*To(i,d,o.wallStartMs),{type:"done"}}return{type:"research_plan",plan:i}}function*We(t,e,n,r,o,s){if(e.intent!=="research")throw new Error(`runResearchPlan: expected plan.intent=research, got ${e.intent}`);let a=yield*et.expect(),i=B=>a.send(B),d=e.tasks,c=En();yield*i({type:"research:start",agentCount:d.length,mode:s.reasoningMode});let u=Pn();for(let B of r)yield*B.bind({reranker:o});let m=new Map(r.map(B=>[B,B.createScorer(t)])),w=r.flatMap(B=>B.tools),v=r[0],L=m.get(v),P=r.some(B=>B.name==="web"),p=r.some(B=>typeof B.promptData=="function"),g=$e(bo,{hasWeb:P,hasCorpus:p}),C=[...w,ao],A=0,T=0,{answer:le,totalTokens:F,totalToolCalls:J,synthTokens:K}=yield*io({parent:n.trunk??void 0,systemPrompt:g,tools:C},function*(B){s.reasoningMode==="flat"&&(yield*i({type:"fanout:tasks",tasks:d}));let D=yield*no({tools:C,parent:B,terminalToolName:"report",maxTurns:s.maxTurns,pruneOnReturn:!0,policy:xo(),scorer:L,enableThinking:!0,orchestrate:s.reasoningMode==="flat"?so(d.map((z,b)=>({content:vn(z),systemPrompt:Rn(v,{maxTurns:s.maxTurns,agentCount:d.length,siblingTasks:d.filter((G,x)=>x!==b).map(G=>G.description),date:c,taskIndex:0}),seed:1e3+b}))):oo(d,(z,b)=>({task:{content:vn(z),systemPrompt:Rn(v,{maxTurns:s.maxTurns,agentCount:1,siblingTasks:[],date:c,taskIndex:b})},userContent:`Research task: ${z.description}`,beforeSpawn:function*(){yield*i({type:"spine:task",taskIndex:b,taskCount:d.length,description:z.description}),yield*i({type:"spine:source",taskIndex:b,source:v.name})},afterExtend:function*(G,x){yield*i({type:"spine:task:done",taskIndex:b,stageFindings:G,accumulated:x})}}))});if(T=u(),yield*i({type:"research:done",totalTokens:D.totalTokens,totalToolCalls:D.totalToolCalls,timeMs:T}),d.length===1)return{answer:D.agents[0]?.result?.trim()??"",totalTokens:D.totalTokens,totalToolCalls:D.totalToolCalls,synthTokens:0};yield*i({type:"synthesize:start"});let U=Pn(),Se=s.reasoningMode==="flat"?fo:mo,Ee=s.reasoningMode==="flat"?D.agents.map((z,b)=>{let G=d[b]?.description??`task ${b+1}`,x=z.result?.trim()||"(no findings)";return`### Agent ${b+1}: ${G}
|
|
607
607
|
|
|
608
608
|
${x}`}).join(`
|
|
609
609
|
|
|
610
|
-
`):void 0,Ue={query:t,findings:Ee,agentCount:d.length},ce=yield*
|
|
610
|
+
`):void 0,Ue={query:t,findings:Ee,agentCount:d.length},ce=yield*ro({systemPrompt:$e(Se.system,Ue),task:$e(Se.user,Ue),parent:B,policy:new Pt,maxTurns:s.maxTurns});return A=U(),yield*i({type:"synthesize:done",agentId:ce.id,ppl:ce.branch.disposed?0:ce.branch.perplexity,tokenCount:ce.tokenCount,toolCallCount:ce.toolCallCount,timeMs:A}),{answer:ce.result||"",totalTokens:D.totalTokens,totalToolCalls:D.totalToolCalls,synthTokens:ce.tokenCount}});yield*i({type:"answer",text:le}),le&&(yield*Rt(()=>n.commitTurn(t,le))),yield*So({plan:e,researchTokens:F,researchToolCalls:J,researchTimeMs:T,synthTokens:K,synthTimeMs:A,wallStartMs:s.wallStartMs,send:i})}function*To(t,e,n){let r=yield*et.expect(),o=c=>r.send(c),a=(yield*At.expect())._storeKvPressure(),i=a.nCtx||1,d=[{label:"Plan",tokens:t.tokenCount,detail:t.intent,timeMs:t.timeMs},{label:"Passthrough",tokens:e.tokenCount,detail:"trunk stream",timeMs:e.timeMs}];yield*o({type:"stats",timings:d,ctxPct:Math.round(100*a.cellsUsed/i),ctxPos:a.cellsUsed,ctxTotal:i}),yield*o({type:"complete",data:{intent:t.intent,planTokens:t.tokenCount,passthroughTokens:e.tokenCount,wallTimeMs:Math.round(performance.now()-n),planMs:Math.round(t.timeMs),passthroughMs:Math.round(e.timeMs)}})}function*So(t){let n=(yield*At.expect())._storeKvPressure(),r=n.nCtx||1,o=[{label:"Plan",tokens:t.plan.tokenCount,detail:t.plan.intent,timeMs:t.plan.timeMs},{label:"Research",tokens:t.researchTokens,detail:`${t.researchToolCalls} tools`,timeMs:t.researchTimeMs},{label:"Synthesize",tokens:t.synthTokens,detail:t.synthTokens>0?"spine fork":"skipped (single task)",timeMs:t.synthTimeMs}];yield*t.send({type:"stats",timings:o,ctxPct:Math.round(100*n.cellsUsed/r),ctxPos:n.cellsUsed,ctxTotal:r}),yield*t.send({type:"complete",data:{intent:t.plan.intent,planTokens:t.plan.tokenCount,agentTokens:t.researchTokens,synthTokens:t.synthTokens,totalToolCalls:t.researchToolCalls,agentCount:t.plan.tasks.length,wallTimeMs:Math.round(performance.now()-t.wallStartMs),planMs:Math.round(t.plan.timeMs),researchMs:Math.round(t.researchTimeMs),synthMs:Math.round(t.synthTimeMs)}})}import*as ue from"node:fs";import*as Mn from"node:os";import*as Te from"node:path";var In={name:"reasoning.run",version:"0.2.2",description:"A private reasoner for your terminal. Direct conversation or grounded multi-agent research, GPU-native and fully local. No API keys, no inference servers.",bin:{"reasoning.run":"bin/run.js"},files:["bin","dist","LICENSE","README.md"],scripts:{build:"esbuild src/main.ts --bundle --platform=node --target=node22 --format=esm --packages=external --loader:.eta=text --outfile=dist/bundle.mjs --minify --legal-comments=none","build:watch":"esbuild src/main.ts --bundle --platform=node --target=node22 --format=esm --packages=external --loader:.eta=text --outfile=dist/bundle.mjs --watch",start:"npm run build && node bin/run.js",smoke:"tsx src/tui-ink/__bus-smoke.ts && tsx src/tui-ink/__reducer-smoke.ts && tsx src/tui-ink/__config-smoke.ts && tsx src/__download-smoke.ts && tsx src/__rundir-smoke.ts","smoke:visual":"tsx src/tui-ink/__visual-smoke.tsx",prepublishOnly:"npm run build"},dependencies:{"@inkjs/ui":"^2.0.0","@lloyal-labs/lloyal-agents":"^2.1.0","@lloyal-labs/lloyal.node":"^2.1.0","@lloyal-labs/rig":"^2.1.0","@lloyal-labs/sdk":"^2.1.0",effection:"^4.0.2",eta:"^4.5.1",ignore:"^7.0.5",ink:"^7.0.1",react:"^19.2.5"},devDependencies:{"@types/node":"^25.3.0","@types/react":"^19.2.14",esbuild:"^0.28.0",tsx:"^4.21.0",typescript:"^5.9.3"},engines:{node:">=22"},keywords:["reasoning","private-reasoner","deep-research","grounded-reasoning","multi-agent","agents","rag","local-llm","offline","on-device","gpu","llama.cpp","cli","tui"],repository:{type:"git",url:"git+https://github.com/lloyal-ai/reasoning-run.git"},license:"SEE LICENSE IN LICENSE"};var vo=`reasoning.run/${In.version}`,It=[{id:"qwen3.5-4b-q4",label:"Qwen3.5-4B Q4_K_M",kind:"llm",urls:["https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/resolve/main/Qwen3.5-4B-Q4_K_M.gguf","https://models.lloyal.ai/Qwen3.5-4B-Q4_K_M.gguf"],filename:"Qwen3.5-4B-Q4_K_M.gguf",sizeBytes:26e8,recommendedNCtx:32768},{id:"qwen3-reranker-0.6b-q8",label:"Qwen3-Reranker 0.6B Q8_0",kind:"reranker",urls:["https://huggingface.co/ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/resolve/main/qwen3-reranker-0.6b-q8_0.gguf","https://models.lloyal.ai/qwen3-reranker-0.6b-q8_0.gguf"],filename:"qwen3-reranker-0.6b-q8_0.gguf",sizeBytes:63e7}],Ro=It.find(t=>t.kind==="llm"),Po=It.find(t=>t.kind==="reranker");function tt(){let t=process.env.XDG_CACHE_HOME||Te.join(Mn.homedir(),".cache");return Te.join(t,"lloyal","models")}function ye(t,e){if(!t){let r=e==="llm"?Ro:Po;return{path:Te.join(tt(),r.filename),entry:r}}let n=It.find(r=>r.id===t);return n?{path:Te.join(tt(),n.filename),entry:n}:{path:Te.resolve(t),entry:null}}async function _n(t,e={}){let n=Te.join(tt(),t.filename);if(ue.existsSync(n))return n;ue.mkdirSync(tt(),{recursive:!0});let r=n+".partial";try{ue.unlinkSync(r)}catch{}let o=[];for(let s of t.urls)try{return await Ao(s,r,n,t.sizeBytes,e)}catch(a){o.push(` ${s}: ${a.message}`);try{ue.unlinkSync(r)}catch{}}throw new Error(`Failed to download ${t.label} from any source:
|
|
611
611
|
${o.join(`
|
|
612
|
-
`)}`)}async function
|
|
612
|
+
`)}`)}async function Ao(t,e,n,r,o){let s=await fetch(t,{redirect:"follow",headers:{"User-Agent":vo}});if(!s.ok||!s.body)throw new Error(`HTTP ${s.status} ${s.statusText}`);let a=Number(s.headers.get("content-length")??r),i=ue.createWriteStream(e),d=0,c=0,u=(m=!1)=>{if(!o.onProgress)return;let w=Date.now();!m&&w-c<200||(c=w,o.onProgress(d,a,t))};try{for await(let m of s.body)i.write(m),d+=m.byteLength,u()}catch(m){throw i.destroy(),m}return await new Promise((m,w)=>{i.end(v=>v?w(v):m())}),ue.renameSync(e,n),u(!0),n}import*as ze from"node:fs";import*as He from"node:path";var nt=class{currentDir=null;inResearch=!1;spawnOrdinal=0;agentToOrdinal=new Map;taskByOrdinal=new Map;lastAnswer=null;query=null;mode=null;startedAt=null;synthStats=null;start(e){let n=new Date().toISOString().replace(/[:.]/g,"-").replace("Z","");return this.currentDir=He.resolve(e.outputDir,n),ze.mkdirSync(this.currentDir,{recursive:!0}),this.inResearch=!1,this.spawnOrdinal=0,this.agentToOrdinal.clear(),this.taskByOrdinal.clear(),this.lastAnswer=null,this.query=e.query,this.mode=e.mode,this.startedAt=Date.now(),this.synthStats=null,this.currentDir}handle(e){if(this.currentDir)switch(e.type){case"research:start":this.inResearch=!0;break;case"research:done":this.inResearch=!1;break;case"fanout:tasks":e.tasks.forEach((n,r)=>this.taskByOrdinal.set(r+1,n.description));break;case"spine:task":this.taskByOrdinal.set(e.taskIndex+1,e.description);break;case"agent:spawn":this.inResearch&&!this.agentToOrdinal.has(e.agentId)&&(this.spawnOrdinal+=1,this.agentToOrdinal.set(e.agentId,this.spawnOrdinal));break;case"agent:return":case"agent:recovered":{let n=this.agentToOrdinal.get(e.agentId);n!==void 0&&this.writeAnnexure(n,e.result);break}case"answer":this.lastAnswer=e.text;break;case"synthesize:done":this.synthStats={tokens:e.tokenCount,ppl:e.ppl,timeMs:e.timeMs};break;case"complete":this.finish();break;case"ui:error":this.reset();break}}writeAnnexure(e,n){if(!this.currentDir)return;let r=this.taskByOrdinal.get(e)??"",o=`# Annexure ${e}
|
|
613
613
|
|
|
614
614
|
${r?`**Task:** ${r}
|
|
615
615
|
|
|
@@ -628,15 +628,15 @@ ${r}
|
|
|
628
628
|
${s}
|
|
629
629
|
|
|
630
630
|
${this.lastAnswer.trim()}
|
|
631
|
-
${a}`;ze.writeFileSync(He.join(this.currentDir,"report.md"),i,"utf8")}this.reset()}reset(){this.currentDir=null,this.inResearch=!1,this.spawnOrdinal=0,this.agentToOrdinal.clear(),this.taskByOrdinal.clear(),this.lastAnswer=null,this.query=null,this.mode=null,this.startedAt=null,this.synthStats=null}};var
|
|
632
|
-
`),process.exit(1));var
|
|
633
|
-
`),process.exit(1));var on=Qe!==void 0?parseInt(Qe,10):void 0,ln=Ce(ie,{modelPath:
|
|
634
|
-
`)}var rn=t=>t instanceof Error?t.message:String(t),
|
|
631
|
+
${a}`;ze.writeFileSync(He.join(this.currentDir,"report.md"),i,"utf8")}this.reset()}reset(){this.currentDir=null,this.inResearch=!1,this.spawnOrdinal=0,this.agentToOrdinal.clear(),this.taskByOrdinal.clear(),this.lastAnswer=null,this.query=null,this.mode=null,this.startedAt=null,this.synthStats=null}};var zs=ge.join(process.cwd(),"harness.json"),{values:j,positionals:Hs}=Is({args:process.argv.slice(2),options:{query:{type:"string"},reranker:{type:"string"},corpus:{type:"string"},config:{type:"string"},"findings-budget":{type:"string"},"reasoning-mode":{type:"string"},"n-ctx":{type:"string"},"output-dir":{type:"string"},jsonl:{type:"boolean",default:!1},verbose:{type:"boolean",default:!1}},allowPositionals:!0}),fe=j["reasoning-mode"];fe!==void 0&&fe!=="flat"&&fe!=="deep"&&(process.stderr.write(`Invalid --reasoning-mode: ${fe}. Expected "flat" or "deep".
|
|
632
|
+
`),process.exit(1));var Br=Hs[0]||void 0,an=j.jsonl,Dr=j.verbose,Le=j["output-dir"],he=j.query,ie=j.config??zs,Qe=j["n-ctx"];Qe!==void 0&&!/^\d+$/.test(Qe)&&(process.stderr.write(`Invalid --n-ctx: ${Qe}. Expected a positive integer.
|
|
633
|
+
`),process.exit(1));var on=Qe!==void 0?parseInt(Qe,10):void 0,ln=Ce(ie,{modelPath:Br,reranker:j.reranker,corpusPath:j.corpus,reasoningMode:fe,nCtx:on,outputDir:Le}),S=ln.config,me=ln.origin,Ys=j["findings-budget"]?parseInt(j["findings-budget"],10):void 0,qr=ye(S.model.path,"llm"),Nr=ye(S.model.reranker,"reranker"),Nl=qr.path,Ll=Nr.path,Fl=S.model.nCtx??32768;an&&un(!0);Dr&&dn(!0);var js=!Dr&&!an;if(js)try{H.closeSync(2),H.openSync(process.platform==="win32"?"\\\\.\\NUL":"/dev/null","w")}catch{}var Ks=10,sn=new Map;function*Or(t,e){let n=sn.get(t);if(n)return n;let{cwd:r,pattern:o}=$s(t),s=o??"**/*.{md,mdx}",a=ge.join(r,".gitignore"),i=H.existsSync(a)?Ws().add(H.readFileSync(a,"utf8")):null,d=H.globSync(s,{cwd:r}),c=(i?d.filter(v=>!i.ignores(v)):d).sort();if(c.length===0)throw new Error(`No .md(x) files at ${r}${o?` matching ${o}`:""}`);e.send({type:"weights:label",label:`Indexing corpus (${c.length} files)\u2026`});let u=[];for(let v=0;v<c.length;v++){let L=c[v];e.send({type:"weights:label",label:`Indexing: ${L} (${v+1}/${c.length})`}),yield*Fe(()=>new Promise(P=>{setImmediate(()=>{try{u.push({name:L,content:H.readFileSync(ge.join(r,L),"utf8")})}catch{}P()})}))}e.send({type:"weights:label",label:"Chunking corpus\u2026"}),yield*Fe(()=>new Promise(v=>setImmediate(v)));let m=Us(u),w={resources:u,chunks:m};return sn.set(t,w),w}function Ne(t){let e=[];if(t.sources.corpusPath){let n=sn.get(t.sources.corpusPath);n&&e.push(new Fs(n.resources,n.chunks,{grep:{maxResults:50,lineMaxChars:200},readFile:{defaultMaxLines:100}}))}return t.sources.tavilyKey&&e.push(new Ls(new qs(t.sources.tavilyKey),{topN:5,fetch:{maxChars:3e3,topK:5,timeout:1e4,tokenBudget:1200}})),e}function nn(t){if(t.length===0)return"";let e=["Available research sources:"],n=!1;for(let r of t){let o=r;if(typeof o.promptData=="function"){let s=o.promptData();e.push("","## Local corpus"),e.push("Files and top-level topics (full-text searchable via grep/read/search tools):"),s.toc&&e.push(s.toc)}else r.name==="web"&&(n=!0)}return n&&(e.push("","## Web search"),e.push("web search is available for live web queries (web_search + fetch_page tools).")),e.join(`
|
|
634
|
+
`)}var rn=t=>t instanceof Error?t.message:String(t),Gs=t=>t instanceof Error?t.stack??t.message:String(t);Ms(function*(){let t=Tt&&!an;t||(Je(),Je(`${St.bold} Deep Research${St.reset}`),Je());let e=fn(),n=_s(),r=Br,o=j.reranker,s=[qr,Nr].filter(p=>p.entry!==null&&!H.existsSync(p.path)).map(p=>({id:p.entry.id,label:p.entry.label,sizeBytes:p.entry.sizeBytes})),a=null;if(t){let p=yield*Fe(()=>Promise.resolve().then(()=>(Mr(),Ir))),g=[{type:"config:loaded",config:S,origin:me,path:ln.path}];s.length>0&&g.push({type:"download:plan",entries:s}),a=p.render(e,C=>n.send(C),g),yield*kt(()=>{a?.unmount()})}else e.subscribe(p=>{pn(p.type,p)});let i=ke(S.sources.outputDir||process.cwd());H.mkdirSync(i,{recursive:!0});let d=new Date().toISOString().replace(/[:.]/g,"-").replace("Z",""),c=ge.join(i,`trace-${d}.jsonl`),u=H.openSync(c,"w"),m=new Ds(u);yield*kt(()=>{m.flush();try{H.closeSync(u)}catch{}});function*w(p){if(H.existsSync(p.path))return p.path;if(!p.entry)throw new Error(`Model not found: ${p.path}. Pass --model <path> or use /model <path> to set a local .gguf file.`);let g=p.entry;return e.send({type:"download:start",id:g.id,label:g.label,sizeBytes:g.sizeBytes}),yield*Fe(()=>_n(g,{onProgress:(C,A,T)=>{e.send({type:"download:progress",id:g.id,got:C,total:A,url:T})}})),e.send({type:"download:complete",id:g.id}),p.path}function v(p){let g=p.filter(C=>C.entry!==null&&!H.existsSync(C.path)).map(C=>({id:C.entry.id,label:C.entry.label,sizeBytes:C.entry.sizeBytes}));g.length>0&&e.send({type:"download:plan",entries:g})}function*L(){for(let p of yield*Ae(n)){if(p.type==="quit"||p.type==="set_model_path"||p.type==="set_reranker_path")return yield*Ae.next(),p;yield*Ae.next()}return{type:"quit"}}let P=0;for(;;){if(P>0){let A=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le,nCtx:on});S=A.config,me=A.origin,e.send({type:"config:loaded",config:S,origin:me,path:A.path});let T=ye(S.model.path,"llm"),le=ye(S.model.reranker,"reranker");v([T,le])}let p=P;if((yield*yield*_r(function*(){let A=ye(S.model.path,"llm"),T=A.path,le=A.entry?.label??ge.basename(T).replace(/-Q\w+\.gguf$/,""),F=ye(S.model.reranker,"reranker"),J=F.path,K=F.entry?.label??ge.basename(J).replace(/-q\w+\.gguf$/i,""),B=S.model.nCtx??32768,D=null,U=null,Se=p===0;for(;D===null||U===null;){let l="llm";try{Se||v([A,F]),Se=!1,l="llm",yield*w(A),l="reranker",yield*w(F),l="llm",e.send({type:"weights:start",label:`Loading ${le}\u2026`}),D=yield*Fe(()=>Os({modelPath:T,nCtx:B,nSeqMax:64,typeK:"q4_0",typeV:"q4_0"})),l="reranker",e.send({type:"weights:label",label:`Loading ${K}\u2026`}),U=yield*Fe(()=>Ns(J,{nSeqMax:8,nCtx:16384}))}catch(f){if(D){try{D.dispose?.()}catch{}D=null}U=null,e.send({type:"boot:error",kind:l,message:rn(f)});let y=yield*L();if(y.type==="quit")return"quit";y.type==="set_model_path"?(we({model:{path:y.path}},ie),r=void 0,A=ye(y.path,"llm"),T=A.path,le=A.entry?.label??ge.basename(T)):(we({model:{reranker:y.path}},ie),o=void 0,F=ye(y.path,"reranker"),J=F.path,K=F.entry?.label??ge.basename(J));let I=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le,nCtx:on});S=I.config,me=I.origin}}let Ee=D,Ue=U;yield*kt(()=>{Ue.dispose()}),yield*kt(()=>{try{Ee.dispose?.()}catch{}}),e.send({type:"weights:done"});let ce=new nt,{session:z,events:b}=yield*Bs(Ee,{traceWriter:m});if(yield*_r(function*(){for(let l of yield*Ae(b))ce.handle(l),e.send(l),yield*Ae.next()}),S.sources.corpusPath)try{let l=yield*Or(S.sources.corpusPath,e);e.send({type:"corpus:indexed",corpusPath:S.sources.corpusPath,fileCount:l.resources.length,chunkCount:l.chunks.length})}catch(l){e.send({type:"ui:error",message:`Corpus disabled: ${l.message}. Use /scan to fix.`})}e.send({type:"ui:composer"});let G={maxTurns:Ks,findingsMaxChars:Ys,reasoningMode:S.defaults.reasoningMode};function x(l,f){let y=S.sources.outputDir??process.cwd();ce.start({outputDir:y,query:l,mode:f})}if(!t){he||(process.stderr.write(`Non-TTY mode requires --query.
|
|
635
635
|
`),process.exit(2));let l=Ne(S);l.length===0&&(process.stderr.write(`No source configured. Set TAVILY_API_KEY, pass --corpus <dir>, or store one in harness.json.
|
|
636
636
|
`),process.exit(2));let f=performance.now(),y=yield*Me(he,z,l,U,{...G,wallStartMs:f,onStart:()=>x(he,S.defaults.reasoningMode)});return y.type==="clarify"&&(process.stderr.write(`Planner asked clarifying questions; non-TTY mode can't answer. Aborting.
|
|
637
|
-
`),process.exit(2)),y.type==="research_plan"&&(x(he,S.defaults.reasoningMode),yield*We(he,y.plan,z,l,U,{...G,wallStartMs:f})),"quit"}let h=null;if(p===0&&he){let l=S.defaults.reasoningMode,f=performance.now(),y=Ne(S),I=yield*Me(he,z,y,U,{...G,reasoningMode:l,wallStartMs:f,onStart:()=>x(he,l)});I.type==="research_plan"?(h={plan:I.plan,query:he,mode:l,wallStartMs:f},yield*b.send({type:"ui:plan_review"})):I.type==="clarify"?h={plan:I.plan,query:he,mode:l,wallStartMs:f}:yield*b.send({type:"ui:composer"})}for(let l of yield*Ae(n))try{if(l.type==="quit")return"quit";if(l.type==="set_model_path")return we({model:{path:l.path}},ie),r=void 0,"restart";if(l.type==="set_reranker_path")return we({model:{reranker:l.path}},ie),o=void 0,"restart";if(l.type==="set_tavily_key"){S={...S,sources:{...S.sources,tavilyKey:l.key}};let f=we({sources:{tavilyKey:l.key}},ie),y=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le});S=y.config,me=y.origin,yield*b.send({type:"config:updated",config:S,origin:me,savedTo:f.path,gitignored:f.gitignored,skipped:f.skipped})}else if(l.type==="set_output_dir"){let f=l.path?ke(l.path):"",y=we({sources:{outputDir:f}},ie),I=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le});S=I.config,me=I.origin,yield*b.send({type:"config:updated",config:S,origin:me,savedTo:y.path,gitignored:y.gitignored,skipped:y.skipped})}else if(l.type==="set_corpus_path"){let f=l.path?ke(l.path):"";if(f){e.send({type:"weights:start",label:"Indexing corpus\u2026"});let te;try{te=yield*
|
|
638
|
-
`),Xe=yield*Me(f,z,Ve,U,{...G,reasoningMode:I,context:[nn(Ve),
|
|
637
|
+
`),process.exit(2)),y.type==="research_plan"&&(x(he,S.defaults.reasoningMode),yield*We(he,y.plan,z,l,U,{...G,wallStartMs:f})),"quit"}let h=null;if(p===0&&he){let l=S.defaults.reasoningMode,f=performance.now(),y=Ne(S),I=yield*Me(he,z,y,U,{...G,reasoningMode:l,wallStartMs:f,onStart:()=>x(he,l)});I.type==="research_plan"?(h={plan:I.plan,query:he,mode:l,wallStartMs:f},yield*b.send({type:"ui:plan_review"})):I.type==="clarify"?h={plan:I.plan,query:he,mode:l,wallStartMs:f}:yield*b.send({type:"ui:composer"})}for(let l of yield*Ae(n))try{if(l.type==="quit")return"quit";if(l.type==="set_model_path")return we({model:{path:l.path}},ie),r=void 0,"restart";if(l.type==="set_reranker_path")return we({model:{reranker:l.path}},ie),o=void 0,"restart";if(l.type==="set_tavily_key"){S={...S,sources:{...S.sources,tavilyKey:l.key}};let f=we({sources:{tavilyKey:l.key}},ie),y=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le});S=y.config,me=y.origin,yield*b.send({type:"config:updated",config:S,origin:me,savedTo:f.path,gitignored:f.gitignored,skipped:f.skipped})}else if(l.type==="set_output_dir"){let f=l.path?ke(l.path):"",y=we({sources:{outputDir:f}},ie),I=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le});S=I.config,me=I.origin,yield*b.send({type:"config:updated",config:S,origin:me,savedTo:y.path,gitignored:y.gitignored,skipped:y.skipped})}else if(l.type==="set_corpus_path"){let f=l.path?ke(l.path):"";if(f){e.send({type:"weights:start",label:"Indexing corpus\u2026"});let te;try{te=yield*Or(f,e)}catch(Ve){e.send({type:"weights:done"}),yield*b.send({type:"ui:error",message:`Cannot use ${f}: ${Ve.message}`});continue}e.send({type:"corpus:indexed",corpusPath:f,fileCount:te.resources.length,chunkCount:te.chunks.length}),e.send({type:"weights:done"})}let y=we({sources:{corpusPath:f}},ie),I=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le});S=I.config,me=I.origin,yield*b.send({type:"config:updated",config:S,origin:me,savedTo:y.path,gitignored:y.gitignored,skipped:y.skipped}),f&&(yield*b.send({type:"ui:composer"}))}else if(l.type==="submit_query"){let f=Ne(S);if(f.length===0){yield*b.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."});continue}let y=performance.now();if(l.skipPlanner){let te=Et(l.query);yield*b.send({type:"plan:start",query:l.query,mode:l.mode}),yield*b.send({type:"query",query:l.query,warm:!!z.trunk}),yield*b.send({type:"plan",intent:te.intent,tasks:te.tasks,clarifyQuestions:te.clarifyQuestions,tokenCount:te.tokenCount,timeMs:te.timeMs}),x(l.query,l.mode),yield*We(l.query,te,z,f,U,{...G,reasoningMode:l.mode,wallStartMs:y}),yield*b.send({type:"ui:composer"});continue}let I=yield*Me(l.query,z,f,U,{...G,reasoningMode:l.mode,context:nn(f),wallStartMs:y,onStart:()=>x(l.query,l.mode)});I.type==="research_plan"?(h={plan:I.plan,query:l.query,mode:l.mode,wallStartMs:y},yield*b.send({type:"ui:plan_review"})):I.type==="clarify"?h={plan:I.plan,query:l.query,mode:l.mode,wallStartMs:y}:yield*b.send({type:"ui:composer"})}else if(l.type==="submit_clarification"&&h){let{query:f,plan:y,mode:I,wallStartMs:te}=h,Ve=Ne(S),Lr=["Prior clarification exchange:",...y.clarifyQuestions.map((Fr,Ur)=>`(${Ur+1}) ${Fr}`),"",`User response: ${l.answer}`,"","Use this exchange to proceed with research if possible."].join(`
|
|
638
|
+
`),Xe=yield*Me(f,z,Ve,U,{...G,reasoningMode:I,context:[nn(Ve),Lr].filter(Boolean).join(`
|
|
639
639
|
|
|
640
640
|
`),wallStartMs:te,onStart:()=>x(f,I)});Xe.type==="research_plan"?(h={plan:Xe.plan,query:f,mode:I,wallStartMs:te},yield*b.send({type:"ui:plan_review"})):Xe.type==="clarify"?h={plan:Xe.plan,query:f,mode:I,wallStartMs:te}:(h=null,yield*b.send({type:"ui:composer"}))}else if(l.type==="change_mode"&&h){let f=Ne(S),y=yield*Me(h.query,z,f,U,{...G,reasoningMode:l.mode,context:nn(f),wallStartMs:h.wallStartMs,onStart:()=>x(h.query,l.mode)});y.type==="research_plan"?(h={...h,plan:y.plan,mode:l.mode},yield*b.send({type:"ui:plan_review"})):y.type==="clarify"?h={...h,plan:y.plan,mode:l.mode}:(h=null,yield*b.send({type:"ui:composer"}))}else if(l.type==="accept_plan"&&h){if(h.plan.intent==="clarify"){h=null,yield*b.send({type:"ui:composer"});continue}let f=Ne(S);if(f.length===0){yield*b.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."}),h=null;continue}x(h.query,h.mode),yield*We(h.query,h.plan,z,f,U,{...G,reasoningMode:h.mode,wallStartMs:h.wallStartMs}),h=null,yield*b.send({type:"ui:composer"})}else if(l.type==="cancel_plan")h=null,yield*b.send({type:"ui:composer"});else if(l.type==="edit_plan")h=null,yield*b.send({type:"ui:composer",prefill:l.query});else if(l.type==="update_task_description"&&h)h.plan.tasks=h.plan.tasks.map((f,y)=>y===l.index?{...f,description:l.description}:f),yield*b.send({type:"plan:task_updated",index:l.index,description:l.description});else if(l.type==="add_task"&&h){let f=Math.max(0,Math.min(h.plan.tasks.length,l.afterIndex+1));h.plan.tasks=[...h.plan.tasks.slice(0,f),{description:""},...h.plan.tasks.slice(f)],yield*b.send({type:"plan:task_added",afterIndex:l.afterIndex})}else if(l.type==="delete_task"&&h)h.plan.tasks.length>1&&(h.plan.tasks=h.plan.tasks.filter((f,y)=>y!==l.index),yield*b.send({type:"plan:task_deleted",index:l.index}));else if(l.type==="move_task"&&h){let f=h.plan.tasks.length;if(l.from!==l.to&&l.from>=0&&l.from<f&&l.to>=0&&l.to<f){let y=[...h.plan.tasks],[I]=y.splice(l.from,1);y.splice(l.to,0,I),h.plan.tasks=y,yield*b.send({type:"plan:task_moved",from:l.from,to:l.to})}}}catch(f){h=null,yield*b.send({type:"ui:error",message:rn(f)})}finally{yield*Ae.next()}return"quit"}))==="quit")return;P++}}).catch(t=>{process.stderr.write(`Error: ${rn(t)}
|
|
641
|
-
${
|
|
641
|
+
${Gs(t)}
|
|
642
642
|
`),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "reasoning.run",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "A private reasoner for your terminal. Direct conversation or grounded multi-agent research, GPU-native and fully local. No API keys, no inference servers.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"reasoning.run": "bin/run.js"
|
|
@@ -21,10 +21,10 @@
|
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@inkjs/ui": "^2.0.0",
|
|
24
|
-
"@lloyal-labs/lloyal-agents": "^2.
|
|
24
|
+
"@lloyal-labs/lloyal-agents": "^2.1.0",
|
|
25
25
|
"@lloyal-labs/lloyal.node": "^2.1.0",
|
|
26
|
-
"@lloyal-labs/rig": "^2.0
|
|
27
|
-
"@lloyal-labs/sdk": "^2.
|
|
26
|
+
"@lloyal-labs/rig": "^2.1.0",
|
|
27
|
+
"@lloyal-labs/sdk": "^2.1.0",
|
|
28
28
|
"effection": "^4.0.2",
|
|
29
29
|
"eta": "^4.5.1",
|
|
30
30
|
"ignore": "^7.0.5",
|