reasoning.run 0.1.0 → 0.1.1
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/README.md +45 -13
- package/dist/bundle.mjs +35 -57
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -8,6 +8,8 @@ npx reasoning.run
|
|
|
8
8
|
|
|
9
9
|
Then type a research question.
|
|
10
10
|
|
|
11
|
+
> Built with **[HDK](https://hdk.lloyal.ai/)** — Lloyal's Harness Development Kit. The agentic envelope for local-first apps: models, tools, retrieval, and multi-agent orchestration in one import, no API keys, no inference servers.
|
|
12
|
+
|
|
11
13
|
## What it does
|
|
12
14
|
|
|
13
15
|
- Downloads a Qwen3.5-4B LLM and Qwen3 reranker on first run (~3 GB, cached in `~/.cache/lloyal/models/`).
|
|
@@ -36,17 +38,23 @@ State lives in `./harness.json` (auto-created, auto-gitignored on first save):
|
|
|
36
38
|
}
|
|
37
39
|
```
|
|
38
40
|
|
|
39
|
-
###
|
|
40
|
-
|
|
41
|
-
Press `Esc` to open the menu mode:
|
|
41
|
+
### Slash commands
|
|
42
42
|
|
|
43
|
-
|
|
44
|
-
- `C` → set corpus path (or clear with empty)
|
|
45
|
-
- `O` → set output dir (or clear to fall back to cwd)
|
|
46
|
-
- `T` → toggle Deep / Fast reasoning
|
|
47
|
-
- `Esc` → back to the query input
|
|
43
|
+
Type `/` in the composer to open the command palette. Tab autocompletes; Enter runs.
|
|
48
44
|
|
|
49
|
-
|
|
45
|
+
| Command | Effect |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `/web <key>` | Set Tavily API key. Empty value clears. |
|
|
48
|
+
| `/scan <path>` | Set local file/glob source. Empty value clears. |
|
|
49
|
+
| `/output <dir>` | Set the run-artifact output directory. Empty value resets to cwd. |
|
|
50
|
+
| `/model <path>` | Use a local LLM `.gguf` instead of the catalog default. |
|
|
51
|
+
| `/reranker <path>` | Use a local reranker `.gguf` instead of the catalog default. |
|
|
52
|
+
| `/deep` | Switch to deep (chain) reasoning mode. |
|
|
53
|
+
| `/flat` | Switch to flat (parallel) reasoning mode. |
|
|
54
|
+
| `/help` | Show the command list inline. |
|
|
55
|
+
| `/quit` | Exit. |
|
|
56
|
+
|
|
57
|
+
Settings persist to `harness.json` the moment you submit. `/model` and `/reranker` also work as a recovery path: if the boot-time download fails (HF outage, no internet, etc.), the BootStatus prompt accepts these commands so you can drop in a pre-downloaded `.gguf` and continue without restarting.
|
|
50
58
|
|
|
51
59
|
## Run artifacts
|
|
52
60
|
|
|
@@ -72,6 +80,22 @@ Every query writes a self-contained bundle under `<output-dir>/<ISO-timestamp>/`
|
|
|
72
80
|
- `TAVILY_API_KEY` — wins over the stored key; never persists to disk while set.
|
|
73
81
|
- `LLAMA_CTX_SIZE` — context window fallback.
|
|
74
82
|
|
|
83
|
+
## CLI flags
|
|
84
|
+
|
|
85
|
+
All optional. Anything you can set in `harness.json` you can also set on the command line; CLI > env > file > defaults.
|
|
86
|
+
|
|
87
|
+
| Flag | Effect |
|
|
88
|
+
|---|---|
|
|
89
|
+
| `--query <q>` | Run one query non-interactively, then exit. Implied non-TTY mode. |
|
|
90
|
+
| `--reasoning-mode <flat\|deep>` | Override the default reasoning mode. |
|
|
91
|
+
| `--n-ctx <int>` | LLM context window in tokens. |
|
|
92
|
+
| `--corpus <path>` | Local file/glob source (same as `/scan`). |
|
|
93
|
+
| `--output-dir <dir>` | Where run artifacts are written (same as `/output`). |
|
|
94
|
+
| `--reranker <path>` | Local reranker `.gguf` (same as `/reranker`). |
|
|
95
|
+
| `--config <path>` | Use a non-default `harness.json`. |
|
|
96
|
+
| `--jsonl` | Stream events as JSONL to stdout (good for piping). |
|
|
97
|
+
| `--verbose` | Verbose logs. |
|
|
98
|
+
|
|
75
99
|
## Keyboard shortcuts
|
|
76
100
|
|
|
77
101
|
Standard readline chords (work in every terminal):
|
|
@@ -88,11 +112,19 @@ Standard readline chords (work in every terminal):
|
|
|
88
112
|
|
|
89
113
|
For Cmd+Backspace / Cmd+arrow to work, turn on "Natural Text Editing" in iTerm2, or use Ghostty.
|
|
90
114
|
|
|
91
|
-
##
|
|
115
|
+
## Built with HDK
|
|
116
|
+
|
|
117
|
+
reasoning.run is a working example of [Lloyal's **Harness Development Kit**](https://hdk.lloyal.ai/) — the same primitives ship intelligence directly into desktop and mobile apps, no cloud round-trip required. Specifically:
|
|
118
|
+
|
|
119
|
+
- **`useAgent`** — single agents with tools and a terminal report tool. Powers the planner, the bridge, and synth.
|
|
120
|
+
- **`agentPool` + `parallel`/`chain`** — multi-agent orchestration. Drives the research phase: parallel fan-out for `Fast` mode, chained tasks for `Deep` mode.
|
|
121
|
+
- **Continuous Context Spine** — agents share GPU KV state instead of re-tokenizing strings, so a 32K-context pipeline runs on a consumer laptop. Why subsequent queries in the same session are warm and instant.
|
|
122
|
+
- **Retrieval-Interleaved Generation (RIG)** — `WebSource` (Tavily) and `CorpusSource` (local markdown) plug in via the `Source` contract, with reranker-scored chunks fed inline during generation.
|
|
123
|
+
- **`@lloyal-labs/lloyal.node`** — llama.cpp Node binding for in-process inference.
|
|
124
|
+
|
|
125
|
+
If you like what reasoning.run does and want to build something similar — a local research tool, a domain-specific agent, an in-app assistant — read the [HDK docs](https://hdk.lloyal.ai/) and start with `useAgent`.
|
|
92
126
|
|
|
93
|
-
|
|
94
|
-
- Local inference via `@lloyal-labs/lloyal.node` (llama.cpp Node binding).
|
|
95
|
-
- UI via Ink (React for terminals).
|
|
127
|
+
UI is [Ink](https://github.com/vadimdemedes/ink) (React for terminals).
|
|
96
128
|
|
|
97
129
|
## License
|
|
98
130
|
|
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 dt(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Go(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 Qo(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(i=>i.url?dt(i.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?[dt(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?[dt(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(dt))).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 J(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 Qn(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 ht(t,e){return{...t,timeline:[...t.timeline,e]}}function Jn(t,e,n){return{...t,timeline:t.timeline.map(r=>r.id===e?n(r):r)}}function Vn(t,e){let n=t.nextTimelineId;return{...J(t,e,o=>ht({...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 pt(t,e,n){let r=t.agents.get(e);if(!r||r.currentThinkId===null)return t;let o=r.currentThinkId,s=Ko(n);return J(t,e,i=>Jn({...i,currentThinkId:null,phase:"content"},o,a=>a.kind==="think"?{...a,body:n,title:s,live:!1,closedAt:Date.now()}:a))}function Ft(t,e){switch(e.type){case"query":return{...ut,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"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"verify:start":return{...t,phase:"verify",verify:{active:!0,count:e.count,done:!1,timeMs:null}};case"verify:done":return{...t,verify:{active:!1,count:e.count,done:!0,timeMs:e.timeMs}};case"eval:done":return{...t,phase:"eval",evalState:{done:!0,converged:e.converged,sampleCount:e.sampleCount,tokenCount:e.tokenCount,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 ${Lt(e.savedTo)} (skipped: ${e.skipped.join(", ")} \u2014 env active)`:e.gitignored?`saved \u2192 ${Lt(e.savedTo)} (added to .gitignore)`:`saved \u2192 ${Lt(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 Qn(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 i=t.mode==="deep"&&n>0?`builds on Task ${n}`:null,a=Qn(t,e.agentId,{phase:"thinking",taskIndex:n,taskDescription:r,dependencyHint:i});return a={...a,researchAgentIds:[...a.researchAgentIds,e.agentId],researchSpawnCount:t.researchSpawnCount+1,pendingTaskIndex:o,pendingTaskDescription:s},Vn(a,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==="verify"||t.phase==="eval"||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 J(r,o.id,x=>({...x,tokenCount:e.tokenCount,contentBuffer:x.contentBuffer+e.text}));if(o.phase!=="thinking"||o.currentThinkId===null)if(o.phase==="tool"||o.phase==="idle")r=Vn(r,o.id),o=r.agents.get(o.id);else return J(r,o.id,x=>({...x,tokenCount:e.tokenCount}));let s=o.currentThinkId,i=o.timeline.find(x=>x.id===s);if(!i||i.kind!=="think")return r;let a=i.body+e.text,p=a.indexOf(Gn);if(p===-1)return J(r,o.id,x=>Jn({...x,tokenCount:e.tokenCount},s,k=>k.kind==="think"?{...k,body:a}:k));let l=a.slice(0,p),u=a.slice(p+Gn.length),h=pt(r,o.id,l);return J(h,o.id,x=>({...x,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 i=n.timeline.find(p=>p.id===n.currentThinkId),a=i&&i.kind==="think"?i.body:"";r=pt(r,e.agentId,a)}if(r.agents.get(e.agentId)?.taskIndex==null)return J(r,e.agentId,i=>({...i,phase:"tool",toolCallCount:i.toolCallCount+1}));let o=r.nextTimelineId;return{...J(r,e.agentId,i=>ht({...i,phase:"tool",toolCallCount:i.toolCallCount+1,pendingToolCallId:o,contentBuffer:""},{kind:"tool_call",id:o,tool:e.tool,argsSummary:Go(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 J(t,e.agentId,a=>({...a,phase:"idle"}));let r=Qo(e.tool,e.result),o=t.nextTimelineId,s=Array.from(new Set(r.hosts));return{...J(t,e.agentId,a=>ht({...a,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(x=>x.id===n.currentThinkId),h=u&&u.kind==="think"?u.body:"";r=pt(r,e.agentId,h)}if(r.agents.get(e.agentId)?.taskIndex==null)return J(r,e.agentId,u=>({...u,phase:"done",contentBuffer:""}));let o=r.nextTimelineId,s=J(r,e.agentId,u=>ht({...u,phase:"done",contentBuffer:""},{kind:"report",id:o,body:e.result,tokenCount:u.tokenCount})),i=s.agents.get(e.agentId),a=s.researchAgentIds.includes(e.agentId),p=a&&i?[...s.scrollback,{key:`agent-${e.agentId}-${s.scrollback.length}`,kind:"agent",agent:i}]:s.scrollback,l=a?s.researchAgentIds.filter(u=>u!==e.agentId):s.researchAgentIds;return{...s,nextTimelineId:r.nextTimelineId+1,scrollback:p,researchAgentIds:l}}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(i=>i.id===n.currentThinkId),s=o&&o.kind==="think"?o.body:"";r=pt(r,e.agentId,s)}return J(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 Gn,Xn=E(()=>{"use strict";Nt();Gn="</think>"});import{useEffect as Vo,useReducer as Jo}from"react";function Zn(t,e=[]){let[n,r]=Jo(Ft,e,o=>o.reduce(Ft,ut));return Vo(()=>t.subscribe(r),[t]),n}var er=E(()=>{"use strict";Nt();Xn()});import{createContext as Xo,useContext as Zo}from"react";function mt(){return Zo(Ut)}var es,Ut,ft=E(()=>{"use strict";es=()=>{},Ut=Xo(es)});import{memo as ts}from"react";import{Box as ns,Text as tr}from"ink";import{jsx as nr,jsxs as rs}from"react/jsx-runtime";var rr,or=E(()=>{"use strict";rr=ts(function({query:e,warm:n}){return e?rs(ns,{flexDirection:"column",marginBottom:1,children:[nr(tr,{bold:!0,children:e}),n?nr(tr,{dimColor:!0,children:"follow-up \xB7 warm session"}):null]}):null})});function gt(t){let e=Number.parseInt(t.slice(1),10);return!Number.isFinite(e)||e<0?$t[0]:$t[e%$t.length]}var $t,Wt=E(()=>{"use strict";$t=["cyan","yellow","green","magenta","red","blue"]});import{memo as Oe}from"react";import{Box as _,Text as A}from"ink";import{jsx as T,jsxs as D}from"react/jsx-runtime";function ss(t){return os.includes(t.phase)}function is(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
|
-
`)?is(e.body):"Thinking\u2026":e.title,o=e.live?sr(e.body):sr(e.body).trim();return D(_,{flexDirection:"column",marginBottom:1,flexShrink:0,children:[D(_,{children:[T(A,{color:n,children:"\u2726 "}),T(A,{bold:!0,children:r})]}),o?T(_,{paddingLeft:2,children:D(A,{children:[o,e.live?"\u258E":""]})}):e.live?T(_,{paddingLeft:2,children:T(A,{dimColor:!0,children:"\u258E"})}):null]})});Ht=Oe(function({item:e}){return D(_,{flexShrink:0,children:[T(A,{dimColor:!0,children:"\u203A "}),T(A,{color:"cyan",children:e.tool}),e.argsSummary?D(A,{dimColor:!0,children:[" ",e.argsSummary]}):null]})}),Yt=Oe(function({item:e}){let n=e.hosts.length>0?e.hosts.join(" \xB7 "):null;return D(_,{flexDirection:"column",flexShrink:0,children:[D(_,{paddingLeft:2,children:[T(A,{color:"green",children:"\u2713 "}),T(A,{children:e.resultCount??e.byteLength+"b"}),typeof e.resultCount=="number"?T(A,{children:" results"}):null]}),n?T(_,{paddingLeft:4,children:T(A,{dimColor:!0,children:n})}):e.preview?T(_,{paddingLeft:4,children:T(A,{dimColor:!0,children:e.preview.length>60?e.preview.slice(0,60)+"\u2026":e.preview})}):null]})}),jt=Oe(function({item:e,color:n}){let r=e.body.trim();return D(_,{flexDirection:"column",marginTop:1,flexShrink:0,children:[D(_,{children:[T(A,{color:n,children:"\u2713 "}),T(A,{bold:!0,children:"report"}),D(A,{dimColor:!0,children:[" \xB7 ",e.tokenCount," tok"]})]}),r?T(_,{paddingLeft:2,children:T(A,{children:r})}):null]})}),as=Oe(function({buffer:e,color:n}){return D(_,{flexDirection:"column",marginTop:1,flexShrink:0,children:[D(_,{children:[T(A,{color:n,children:"\u25B8 "}),T(A,{dimColor:!0,bold:!0,children:"streaming"})]}),T(_,{paddingLeft:2,children:D(A,{dimColor:!0,children:[e,"\u258E"]})})]})}),ls=3,yt=Oe(function({agent:e,headerPrefix:n,bodyHeight:r,width:o}){let s=gt(e.label),i=ss(e),a=e.taskDescription?e.taskDescription.length>80?e.taskDescription.slice(0,80)+"\u2026":e.taskDescription:null,p=r+ls+2;return D(_,{flexDirection:"column",width:o,height:p,borderStyle:"round",borderColor:i?s:"gray",paddingX:1,marginRight:1,flexShrink:0,overflow:"hidden",children:[D(_,{flexShrink:0,children:[n?D(A,{dimColor:!0,children:[n," \xB7 "]}):null,T(A,{color:s,bold:!0,children:e.label}),T(_,{flexGrow:1}),T(A,{color:i?s:"green",children:i?"\u25CF":"\u2713"})]}),a?T(A,{dimColor:!0,children:a}):null,e.dependencyHint?D(A,{dimColor:!0,children:["\u2191 ",e.dependencyHint]}):null,D(_,{flexDirection:"column",flexGrow:1,justifyContent:"flex-end",overflow:"hidden",children:[e.timeline.map(l=>l.kind==="think"?T(zt,{item:l,color:s},l.id):l.kind==="tool_call"?T(Ht,{item:l},l.id):l.kind==="tool_result"?T(Yt,{item:l},l.id):l.kind==="report"?T(jt,{item:l,color:s},l.id):null),e.contentBuffer?T(as,{buffer:e.contentBuffer,color:s}):null]})]})})});import{Box as bt,Text as xt}from"ink";import{jsx as pe,jsxs as Gt}from"react/jsx-runtime";function ir({agent:t}){let e=gt(t.label),n=t.taskDescription?t.taskDescription.length>80?t.taskDescription.slice(0,80)+"\u2026":t.taskDescription:null;return Gt(bt,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,marginBottom:1,children:[Gt(bt,{flexShrink:0,children:[pe(xt,{color:e,bold:!0,children:t.label}),pe(bt,{flexGrow:1}),pe(xt,{color:"green",children:"\u2713"})]}),n?pe(xt,{dimColor:!0,children:n}):null,t.dependencyHint?Gt(xt,{dimColor:!0,children:["\u2191 ",t.dependencyHint]}):null,pe(bt,{flexDirection:"column",children:t.timeline.map(r=>r.kind==="think"?pe(zt,{item:r,color:e},r.id):r.kind==="tool_call"?pe(Ht,{item:r},r.id):r.kind==="tool_result"?pe(Yt,{item:r},r.id):r.kind==="report"?pe(jt,{item:r,color:e},r.id):null)})]})}var ar=E(()=>{"use strict";Wt();Kt()});import{useEffect as cs,useState as us}from"react";import{useStdout as ds}from"ink";function lr(){let{stdout:t}=ds(),[e,n]=us(()=>[t?.columns??120,t?.rows??40]);return cs(()=>{if(!t)return;let r=()=>{n([t.columns??120,t.rows??40])};return t.on("resize",r),()=>{t.off("resize",r)}},[t]),e}function cr(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 Qt=E(()=>{"use strict"});import{Box as Vt}from"ink";import{jsx as Be}from"react/jsx-runtime";function dr({state:t}){let[e,n]=lr(),r=t.researchAgentIds.map(i=>t.agents.get(i)).filter(i=>!!i);if(r.length===0)return null;let o=Math.max(Jt,n-ps);if(t.mode==="flat"){let i=r.length,a=Math.max(ur*i,e-4),p=Math.max(ur,Math.floor(a/i)-1);return p*i+i<=e?Be(Vt,{flexDirection:"row",marginBottom:1,children:r.map(u=>Be(yt,{agent:u,headerPrefix:null,bodyHeight:o,width:p},u.id))}):Be(Vt,{flexDirection:"column",marginBottom:1,children:r.map(u=>Be(yt,{agent:u,headerPrefix:null,bodyHeight:Math.max(Jt,Math.floor(o/i))},u.id))})}let s=Math.max(Jt,Math.floor(o/Math.max(1,r.length)));return Be(Vt,{flexDirection:"column",marginBottom:1,children:r.map(i=>Be(yt,{agent:i,headerPrefix:`Task ${(i.taskIndex??0)+1}`,bodyHeight:s},i.id))})}var ps,ur,Jt,pr=E(()=>{"use strict";Kt();Qt();ps=18,ur=26,Jt=10});import{Box as Ye,Text as ve}from"ink";import{jsx as Ce,jsxs as je}from"react/jsx-runtime";function hr({state:t}){let{synth:e}=t;if(!e.open&&!e.done)return null;let n=e.done?je(Ye,{children:[Ce(ve,{bold:!0,children:"Synthesis "}),Ce(ve,{color:"green",children:"\u2713"}),e.stats?je(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 `:"",hs(e.stats.timeMs)]}):null]}):je(Ye,{children:[Ce(ve,{bold:!0,children:"Synthesis"}),Ce(ve,{color:"cyan",children:" \u25CF"})]}),r=e.buffer.trim();return je(Ye,{flexDirection:"column",marginBottom:1,children:[n,e.open&&r?Ce(Ye,{paddingLeft:2,marginTop:0,children:je(ve,{children:[r,"\u258E"]})}):e.open?Ce(Ye,{paddingLeft:2,children:Ce(ve,{dimColor:!0,children:"\u258E"})}):null]})}var hs,mr=E(()=>{"use strict";hs=t=>`${(t/1e3).toFixed(1)}s`});var ae,kt=E(()=>{"use strict";ae=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});import{useEffect as ms,useState as fs}from"react";import{Box as fr,Text as De}from"ink";import{jsx as Xt,jsxs as Ke}from"react/jsx-runtime";function gr({state:t}){let{verify:e}=t,[n,r]=fs(0);return ms(()=>{if(!e.active)return;let o=setInterval(()=>r(s=>(s+1)%ae.length),80);return()=>clearInterval(o)},[e.active]),!e.active&&!e.done?null:e.active?Ke(fr,{marginBottom:1,children:[Ke(De,{color:"cyan",children:[ae[n]," "]}),Xt(De,{dimColor:!0,children:"Verifying "}),Ke(De,{children:[e.count," samples\u2026"]})]}):Ke(fr,{marginBottom:1,children:[Xt(De,{bold:!0,children:"Verify "}),Xt(De,{color:"green",children:"\u2713"}),Ke(De,{dimColor:!0,children:[" ","\xB7 ",e.count," samples",e.timeMs!=null?` \xB7 ${gs(e.timeMs)}`:""]})]})}var gs,yr=E(()=>{"use strict";kt();gs=t=>`${(t/1e3).toFixed(1)}s`});import{Box as ys,Text as qe}from"ink";import{jsx as Qe,jsxs as br}from"react/jsx-runtime";function xr({state:t}){let e=t.evalState;if(!e||!e.done)return null;let n=e.converged===!0?Qe(qe,{color:"green",children:"yes"}):e.converged===!1?Qe(qe,{color:"red",children:"no"}):Qe(qe,{color:"yellow",children:"unknown"});return br(ys,{marginBottom:1,children:[Qe(qe,{bold:!0,children:"Eval "}),Qe(qe,{children:"Converged: "}),n,br(qe,{dimColor:!0,children:[" ","\xB7 ",e.sampleCount," samples \xB7 ",e.tokenCount," tok \xB7 ",bs(e.timeMs)]})]})}var bs,kr=E(()=>{"use strict";bs=t=>`${(t/1e3).toFixed(1)}s`});import{Box as wr,Text as Tr}from"ink";import{jsx as Zt,jsxs as xs}from"react/jsx-runtime";function vr({state:t}){return!t.answer||t.synth.done&&t.synth.buffer.trim().length>0?null:xs(wr,{flexDirection:"column",marginBottom:1,children:[Zt(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"}),Zt(wr,{marginTop:1,paddingLeft:2,children:Zt(Tr,{children:t.answer.trim()})})]})}var Cr=E(()=>{"use strict"});import{useEffect as ks,useState as ws}from"react";import{Box as Sr,Text as ee}from"ink";import{Fragment as Rs,jsx as le,jsxs as Ve}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 vs(t){return t>=90?"red":t>=70?"yellow":"green"}function Cs(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]=ws(0);return ks(()=>{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 Rr({state:t}){let e=Ss(t),n=t.pressure?.pct??0,r=Cs(t),o=vs(n);return le(Sr,{borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,paddingTop:0,children:Ve(Sr,{flexDirection:"row",children:[le(ee,{dimColor:!0,children:"KV "}),le(ee,{color:o,children:Ts(n)}),Ve(ee,{children:[" ",String(n).padStart(2," "),"%"]}),le(ee,{dimColor:!0,children:" \xB7 "}),le(ee,{children:t.phase}),le(ee,{dimColor:!0,children:" \xB7 \u23F1 "}),le(ee,{children:cr(e)}),le(ee,{dimColor:!0,children:" \xB7 "}),Ve(ee,{children:[r," active"]}),t.sourceCount>0?Ve(Rs,{children:[le(ee,{dimColor:!0,children:" \xB7 "}),le(ee,{dimColor:!0,children:"\u2315 "}),Ve(ee,{children:[t.sourceCount," sources"]})]}):null]})})}var Er=E(()=>{"use strict";Qt()});import{useState as Es}from"react";import{Text as Ne,useInput as As}from"ink";import{jsx as wt,jsxs as Pr}from"react/jsx-runtime";function Se({value:t,onChange:e,onSubmit:n,onCancel:r,placeholder:o="",focused:s=!0,mask:i=!1,color:a}){let[p,l]=Es(t.length),u=Math.min(p,t.length);As((R,g)=>{if(g.return){n?.(t);return}if(g.escape){r?.();return}if(g.leftArrow){g.meta||g.ctrl?l(Ar(t,u)):l(Math.max(0,u-1));return}if(g.rightArrow){g.meta||g.ctrl?l(Ps(t,u)):l(Math.min(t.length,u+1));return}if(R==="\x1B[H"||R==="\x1BOH"){l(0);return}if(R==="\x1B[F"||R==="\x1BOF"){l(t.length);return}if(g.backspace||g.delete){if(u===0)return;if(g.meta||g.ctrl){let L=Ar(t,u);e(t.slice(0,L)+t.slice(u)),l(L);return}let Q=t.slice(0,u-1)+t.slice(u);l(u-1),e(Q);return}if(g.ctrl&&R==="a"){l(0);return}if(g.ctrl&&R==="e"){l(t.length);return}if(g.ctrl&&R==="u"){e(t.slice(u)),l(0);return}if(g.ctrl&&R==="k"){e(t.slice(0,u));return}if(g.ctrl&&R==="w"){let Q=t.slice(0,u),L=/\S+\s*$/.exec(Q),Y=L?L.index:0;e(t.slice(0,Y)+t.slice(u)),l(Y);return}if(!(g.ctrl||g.meta||g.tab||g.upArrow||g.downArrow)&&R.length>0){let Q=t.slice(0,u)+R+t.slice(u);l(u+R.length),e(Q)}},{isActive:s});let h=i?"*".repeat(t.length):t;if(t.length===0)return Pr(Ne,{children:[wt(Ne,{color:a,children:s?"\u258E":""}),wt(Ne,{dimColor:!0,children:o})]});if(!s)return wt(Ne,{color:a,children:h});let k=h.slice(0,u),M=h.slice(u,u+1),H=h.slice(u+1);return Pr(Ne,{color:a,children:[k,wt(Ne,{inverse:!0,children:M||" "}),H]})}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 Ps(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 Ir=E(()=>{"use strict"});import{memo as Xe,useEffect as Mr,useState as Je}from"react";import{Box as X,Text as S,useInput as Is}from"ink";import{jsx as y,jsxs as F}from"react/jsx-runtime";function _r(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 Ms(t){if(!t)return[];if(!t.name)return Tt;let e=t.name.toLowerCase();return Tt.filter(n=>n.name.startsWith(e))}var Tt,Br,Or,_s,en,Os,Dr=E(()=>{"use strict";ft();Ir();Tt=[{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:"fast",desc:"Use fast (parallel) reasoning",kind:"instant"},{name:"help",desc:"Show this list",kind:"instant"},{name:"quit",desc:"Quit",kind:"instant"}];Br=Xe(function({state:e}){let n=mt(),r=e.config?.defaults.reasoningMode??"deep",[o,s]=Je(r),[i,a]=Je("query"),[p,l]=Je(""),[u,h]=Je(""),[x,k]=Je(!1);Mr(()=>{e.composerPrefill&&e.composerPrefill!==p&&l(e.composerPrefill)},[e.composerPrefill]),Mr(()=>{s(r)},[r]);let M=e.configOrigin?.tavilyKey??"unset",H=e.configOrigin?.corpusPath??"unset",R=e.configOrigin?.outputDir??"default",g=M!=="unset",L=g||H!=="unset",Y=M==="env",V=e.clarifyContext!==null,Z=_r(p),te=Z!==null,ie=Ms(Z);Is((d,f)=>{if(f.ctrl&&d==="c"){n({type:"quit"});return}if(f.tab){if(te&&Z&&Z.name&&ie.length===1){let w=ie[0];l("/"+w.name+(w.kind==="value"?" ":""));return}te||s(w=>w==="deep"?"flat":"deep");return}if(f.escape){if(V){n({type:"cancel_plan"}),l("");return}l(""),k(!1);return}},{isActive:i==="query"});let W=d=>{let f=d.trim();if(f){if(!V){let w=_r(f);if(w){C(w);return}}if(V){n({type:"submit_clarification",answer:f}),l("");return}L&&(n({type:"submit_query",query:f,mode:o}),l(""))}},C=({name:d,value:f})=>{if(!d)return;let w=Tt.find(rt=>rt.name===d);if(w){if(l(""),k(!1),w.kind==="instant"){d==="deep"?s("deep"):d==="fast"?s("flat"):d==="quit"?n({type:"quit"}):d==="help"&&k(!0);return}if(f){d==="web"?n({type:"set_tavily_key",key:f}):d==="scan"?n({type:"set_corpus_path",path:f}):d==="output"?n({type:"set_output_dir",path:f}):d==="model"?n({type:"set_model_path",path:f}):d==="reranker"&&n({type:"set_reranker_path",path:f});return}if(d==="web"){if(Y)return;h(e.config?.sources.tavilyKey??""),a("web")}else d==="scan"?(h(e.config?.sources.corpusPath??""),a("scan")):d==="output"?(h(e.config?.sources.outputDir??""),a("output")):d==="model"?(h(e.config?.model.path??""),a("model")):d==="reranker"&&(h(e.config?.model.reranker??""),a("reranker"))}};return F(X,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[i==="query"?F(X,{children:[y(S,{children:"\u203A "}),y(Se,{value:p,onChange:l,onSubmit:W,focused:!0,placeholder:V?"Answer the questions above, or Esc to cancel\u2026":L?"Ask a research question, or / for commands\u2026":"Type / for commands (e.g. /web, /scan) to add a source"})]}):i==="web"?F(X,{children:[y(S,{color:"yellow",children:"Web search key \u203A "}),y(Se,{value:u,onChange:h,onSubmit:()=>{n({type:"set_tavily_key",key:u.trim()}),a("query"),h("")},onCancel:()=>{a("query"),h("")},focused:!0,mask:!0,placeholder:"tvly-..."})]}):i==="scan"?F(X,{children:[y(S,{color:"yellow",children:"Scan path \u203A "}),y(Se,{value:u,onChange:h,onSubmit:()=>{n({type:"set_corpus_path",path:u.trim()}),a("query"),h("")},onCancel:()=>{a("query"),h("")},focused:!0,placeholder:"/path/to/docs or /path/**/*.md"})]}):i==="output"?F(X,{children:[y(S,{color:"yellow",children:"Output dir \u203A "}),y(Se,{value:u,onChange:h,onSubmit:()=>{n({type:"set_output_dir",path:u.trim()}),a("query"),h("")},onCancel:()=>{a("query"),h("")},focused:!0,placeholder:`${process.cwd()} (default)`})]}):i==="model"?F(X,{children:[y(S,{color:"yellow",children:"Model path \u203A "}),y(Se,{value:u,onChange:h,onSubmit:()=>{n({type:"set_model_path",path:u.trim()}),a("query"),h("")},onCancel:()=>{a("query"),h("")},focused:!0,placeholder:"/path/to/qwen3.5-4b.gguf"})]}):F(X,{children:[y(S,{color:"yellow",children:"Reranker path \u203A "}),y(Se,{value:u,onChange:h,onSubmit:()=>{n({type:"set_reranker_path",path:u.trim()}),a("query"),h("")},onCancel:()=>{a("query"),h("")},focused:!0,placeholder:"/path/to/qwen3-reranker.gguf"})]}),i==="query"&&!V&&te?y(X,{flexDirection:"column",marginTop:0,children:ie.length===0?y(S,{color:"red",children:"no matching command"}):ie.map(d=>y(Or,{cmd:d},d.name))}):null,i==="query"&&!te&&x?y(X,{flexDirection:"column",marginTop:0,children:Tt.map(d=>y(Or,{cmd:d},d.name))}):null,F(X,{marginTop:0,children:[y(_s,{mode:o}),y(S,{children:" "}),y(en,{label:"Web",origin:M,value:g?"set":null,disabled:Y}),y(S,{children:" "}),y(en,{label:"Scan",origin:H,value:e.config?.sources.corpusPath?e.corpusStatus?`${e.corpusStatus.fileCount} files`:e.config.sources.corpusPath:null}),y(S,{children:" "}),y(en,{label:"Output",origin:R,value:e.config?.sources.outputDir??null}),y(X,{flexGrow:1}),y(Os,{field:i,hasSource:L,inSlash:te,clarifying:V})]}),e.toast?y(X,{marginTop:0,children:y(S,{color:e.toast.tone==="error"?"red":e.toast.tone==="warn"?"yellow":"green",children:e.toast.message})}):null]})}),Or=Xe(function({cmd:e}){return F(X,{children:[F(S,{color:"cyan",children:["/",e.name]}),F(S,{dimColor:!0,children:[" \xB7 ",e.desc]}),e.kind==="value"?y(S,{dimColor:!0,children:" <value>"}):null]})}),_s=Xe(function({mode:e}){return F(S,{children:[F(S,{color:e==="deep"?"cyan":void 0,bold:e==="deep",children:[e==="deep"?"\u25C6":"\u25CB"," Deep"]}),y(S,{dimColor:!0,children:" "}),F(S,{color:e==="flat"?"cyan":void 0,bold:e==="flat",children:[e==="flat"?"\u25C6":"\u25CB"," Fast"]})]})}),en=Xe(function({label:e,origin:n,value:r,disabled:o=!1}){let s=n!=="unset";return F(S,{children:[F(S,{color:s?"green":"gray",dimColor:o,children:[e," ",s?e==="Scan"&&r?r:"\u2713":"\u2014"]}),y(S,{dimColor:!0,children:n==="env"?" (env)":n==="cli"?" (cli)":""})]})}),Os=Xe(function({field:e,hasSource:n,inSlash:r,clarifying:o}){return e==="web"||e==="scan"||e==="output"||e==="model"||e==="reranker"?y(S,{dimColor:!0,children:"\u23CE save (empty to clear) \xB7 Ctrl+U clear \xB7 Esc cancel"}):o?y(S,{color:"yellow",children:"\u23CE submit answer \xB7 Esc cancel"}):r?y(S,{dimColor:!0,children:"Tab complete \xB7 \u23CE run \xB7 Esc clear"}):n?y(S,{dimColor:!0,children:"Tab toggle mode \xB7 / commands \xB7 \u23CE submit"}):y(S,{color:"yellow",children:"\u26A0 Add a source via /web or /scan"})})});import{memo as Bs,useEffect as Ds,useState as qs}from"react";import{Box as se,Text as O,useInput as Ns}from"ink";import{jsx as U,jsxs as K}from"react/jsx-runtime";var qr,Nr=E(()=>{"use strict";ft();qr=Bs(function({state:e}){let n=mt(),r=e.plan,[o,s]=qs(e.mode??"deep");if(Ds(()=>{e.mode&&e.mode!==o&&s(e.mode)},[e.mode]),Ns((a,p)=>{if(r){if(p.return){if(r.intent==="clarify"){n({type:"edit_plan",query:e.query});return}n({type:"accept_plan"});return}if(p.escape){n({type:"cancel_plan"});return}if(a==="e"||a==="E"){n({type:"edit_plan",query:e.query});return}if(a==="t"||a==="T"){let l=o==="deep"?"flat":"deep";s(l),n({type:"change_mode",mode:l});return}p.ctrl&&a==="c"&&n({type:"quit"})}}),!r)return null;if(r.intent==="clarify")return K(se,{flexDirection:"column",marginBottom:1,children:[U(se,{marginBottom:1,children:U(O,{bold:!0,children:e.query})}),U(O,{dimColor:!0,children:"A few questions to narrow this down."}),U(se,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.clarifyQuestions.map((a,p)=>K(O,{children:[K(O,{dimColor:!0,children:["(",p+1,")"]})," ",a]},p))}),U(se,{marginTop:1,children:U(O,{dimColor:!0,children:"\u23CE answer \xB7 Esc cancel"})})]});if(r.intent==="passthrough")return K(se,{flexDirection:"column",marginBottom:1,children:[U(O,{bold:!0,children:e.query}),U(O,{dimColor:!0,children:"Answering directly \u2014 no research needed."})]});let i=o==="flat"?`${r.tasks.length} parallel tasks`:`${r.tasks.length} chained tasks`;return K(se,{flexDirection:"column",marginBottom:1,children:[U(se,{marginBottom:1,children:U(O,{bold:!0,children:e.query})}),U(O,{dimColor:!0,children:"Here's my plan."}),K(se,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,marginTop:1,children:[K(se,{children:[U(O,{bold:!0,children:"Research"}),K(O,{dimColor:!0,children:[" \xB7 ",i]})]}),r.tasks.map((a,p)=>K(O,{children:[K(O,{dimColor:!0,children:[" (",p+1,")"]})," ",a.description]},p))]}),K(se,{marginTop:1,children:[K(O,{color:o==="deep"?"cyan":void 0,bold:o==="deep",children:[o==="deep"?"\u25C6":"\u25CB"," Deep"]}),U(O,{children:" "}),K(O,{color:o==="flat"?"cyan":void 0,bold:o==="flat",children:[o==="flat"?"\u25C6":"\u25CB"," Fast"]}),U(O,{dimColor:!0,children:" (T to toggle \u2014 re-plans)"})]}),K(se,{marginTop:1,children:[U(O,{dimColor:!0,children:"[E] Edit plan \xB7 [Esc] Cancel \xB7 "}),U(O,{color:"cyan",bold:!0,children:"[\u23CE] Start research"})]})]})})});import{memo as Ls,useEffect as Fs,useState as Us}from"react";import{Box as Lr,Text as tn}from"ink";import{jsx as Fr,jsxs as nn}from"react/jsx-runtime";var Ur,$r=E(()=>{"use strict";kt();Ur=Ls(function({state:e}){let[n,r]=Us(0);return Fs(()=>{let o=setInterval(()=>r(s=>(s+1)%ae.length),80);return()=>clearInterval(o)},[]),nn(Lr,{flexDirection:"column",marginBottom:1,children:[Fr(tn,{bold:!0,children:e.query}),nn(Lr,{marginTop:1,children:[nn(tn,{color:"cyan",children:[ae[n]," "]}),Fr(tn,{dimColor:!0,children:"Planning\u2026"})]})]})})});import{memo as $s}from"react";import{Box as Wr,Text as vt}from"ink";import{jsx as rn,jsxs as on}from"react/jsx-runtime";var zr,Hr=E(()=>{"use strict";zr=$s(function({state:e}){if(!e.clarifyContext)return null;let{originalQuery:n,questions:r}=e.clarifyContext;return on(Wr,{flexDirection:"column",marginBottom:1,children:[rn(vt,{bold:!0,children:n}),rn(vt,{dimColor:!0,children:"A few questions to narrow this down."}),rn(Wr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.map((o,s)=>on(vt,{children:[on(vt,{dimColor:!0,children:["(",s+1,")"]})," ",o]},s))})]})})});import{memo as Yr,useEffect as Ws,useState as zs}from"react";import{Box as Re,Text as I}from"ink";import{Fragment as js,jsx as G,jsxs as $}from"react/jsx-runtime";function Ys(t){try{return new URL(t).host}catch{return null}}function Ct(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 jr,Hs,Kr=E(()=>{"use strict";kt();jr=Yr(function({state:e}){let[n,r]=zs(0);if(Ws(()=>{let o=setInterval(()=>r(s=>(s+1)%ae.length),80);return()=>clearInterval(o)},[]),e.uiPhase==="boot_error"){let o=e.bootError,s=o?.kind??"llm",i=s==="llm"?"LLM":"reranker",a=s==="llm"?"/model":"/reranker",p=s==="llm"?"/reranker":"/model";return $(Re,{flexDirection:"column",marginBottom:1,children:[$(I,{color:"red",bold:!0,children:["\u2717 Boot failed (",i,")"]}),G(Re,{paddingLeft:2,children:G(I,{children:o?.message??"Unknown error"})}),G(Re,{paddingLeft:2,marginTop:1,children:$(I,{dimColor:!0,children:["Type ",$(I,{color:"cyan",children:[a," "]}),G(I,{dimColor:!0,children:"<path-to-gguf>"}),$(I,{dimColor:!0,children:[" to use a local ",i,", or "]}),G(I,{color:"cyan",children:p}),G(I,{dimColor:!0,children:" for the other, or "}),G(I,{color:"cyan",children:"/quit"}),G(I,{dimColor:!0,children:" to exit."})]})})]})}return e.uiPhase==="downloading"?$(Re,{flexDirection:"column",marginBottom:1,children:[$(Re,{children:[$(I,{color:"cyan",children:[ae[n]," "]}),G(I,{bold:!0,children:"Downloading models"})]}),e.downloads.map(o=>G(Hs,{item:o},o.id))]}):$(Re,{marginBottom:1,children:[$(I,{color:"cyan",children:[ae[n]," "]}),G(I,{bold:!0,children:e.loadingLabel??"Loading\u2026"})]})}),Hs=Yr(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),i=e.url?Ys(e.url):null,a=e.started&&i!==null,p=e.done?"\u2713 ":a?"\u25CF ":"\u25CB ",l=e.done?"green":a?"cyan":void 0,u=!a&&!e.done;return $(Re,{paddingLeft:2,children:[G(I,{color:l,dimColor:u,children:p}),$(I,{dimColor:u,children:[e.label.padEnd(28)," "]}),e.done?G(I,{dimColor:!0,children:Ct(e.got)}):a?$(js,{children:[G(I,{color:"cyan",children:s}),$(I,{children:[" ",String(n).padStart(2),"% \xB7 ",Ct(e.got)," / ",Ct(e.total)]}),$(I,{dimColor:!0,children:[" \xB7 ",i]})]}):$(I,{dimColor:!0,children:["queued \xB7 ",Ct(e.total)]})]})})});import{Box as St,Static as Ks,Text as Gr}from"ink";import{jsx as q,jsxs as sn}from"react/jsx-runtime";function Qr({bus:t,dispatch:e,bootstrap:n}){let r=Zn(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",i=r.uiPhase==="composer"||r.uiPhase==="done"||r.uiPhase==="clarifying"||r.uiPhase==="boot_error";return sn(Ut.Provider,{value:e,children:[q(Ks,{items:r.scrollback,children:a=>a.kind==="agent"?q(St,{paddingX:2,children:q(ir,{agent:a.agent})},a.key):sn(St,{flexDirection:"column",paddingX:2,marginBottom:1,children:[q(Gr,{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"}),q(St,{paddingLeft:2,marginTop:1,children:q(Gr,{children:a.body})})]},a.key)}),sn(St,{flexDirection:"column",paddingX:2,paddingY:1,children:[o&&q(rr,{query:r.query,warm:r.warm}),(r.uiPhase==="downloading"||r.uiPhase==="loading"||r.uiPhase==="boot_error")&&q(jr,{state:r}),r.uiPhase==="planning"&&q(Ur,{state:r}),r.uiPhase==="plan_review"&&q(qr,{state:r}),r.uiPhase==="clarifying"&&q(zr,{state:r}),s&&q(dr,{state:r}),s&&q(hr,{state:r}),r.uiPhase==="done"&&q(gr,{state:r}),r.uiPhase==="done"&&q(xr,{state:r}),r.uiPhase==="done"&&q(vr,{state:r}),i&&q(Br,{state:r}),q(Rr,{state:r})]})]})}var Vr=E(()=>{"use strict";er();ft();or();ar();pr();mr();yr();kr();Cr();Er();Dr();Nr();$r();Hr();Kr()});var Jr={};lo(Jr,{render:()=>Vs});import Gs from"react";import{render as Qs}from"ink";function Vs(t,e,n=[]){return Qs(Gs.createElement(Qr,{bus:t,dispatch:e,bootstrap:n}),{incrementalRendering:!0})}var Xr=E(()=>{"use strict";Vr()});import*as N from"node:fs";import*as ue from"node:path";import{parseArgs as Js}from"node:util";import{main as Xs,ensure as an,createSignal as Zs,spawn as ei,each as Ee,call as Le}from"effection";import{createContext as ti}from"@lloyal-labs/lloyal.node";import{initAgents as ni,JsonlTraceWriter as ri}from"@lloyal-labs/lloyal-agents";var Rt=!1,co=!1;function bn(t){Rt=t}function xn(t){co=t}var Et=!!process.stdout.isTTY,At=Et?{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:""},yn="";function uo(){yn&&(yn="",process.stdout.write("\r\x1B[K"))}var st=(...t)=>{Rt||(uo(),console.log(...t))};function kn(t,e){Rt&&console.log(JSON.stringify({event:t,...e}))}import*as j from"node:fs";import*as z from"node:path";import*as Pt from"node:os";import*as it from"node:path";function fe(t){if(!t)return"";let e=t==="~"?Pt.homedir():t.startsWith("~/")?it.join(Pt.homedir(),t.slice(2)):t;return it.resolve(e)}function It(){return{version:1,sources:{},defaults:{reasoningMode:"deep",verifyCount:3,maxTurns:10},model:{}}}function Tn(t){try{let e=j.readFileSync(t,"utf8"),n=JSON.parse(e);if(n.version!==1)return null;let r=It();return{version:1,sources:{...r.sources,...n.sources??{}},defaults:{...r.defaults,...n.defaults??{}},model:{...r.model,...n.model??{}}}}catch{return null}}function Pe(t,e,n=process.env){let r=z.resolve(t),o=Tn(r),s=o??It(),i=n.TAVILY_API_KEY?.trim()||void 0,a=n.LLAMA_CTX_SIZE?.trim(),p=a&&/^\d+$/.test(a)?parseInt(a,10):void 0,l=e.tavilyKey??i??s.sources.tavilyKey,u=e.corpusPath??s.sources.corpusPath,h=u?fe(u):void 0,x=e.outputDir??s.sources.outputDir,k=x?fe(x):void 0,M=e.reasoningMode??s.defaults.reasoningMode??"deep",H=e.modelPath??s.model.path,R=H?fe(H):void 0,g=e.reranker??s.model.reranker,Q=e.nCtx??p??s.model.nCtx,L={version:1,sources:{tavilyKey:l,corpusPath:h,outputDir:k},defaults:{reasoningMode:M,verifyCount:s.defaults.verifyCount,maxTurns:s.defaults.maxTurns},model:{path:R,reranker:g,nCtx:Q}},Y={tavilyKey:e.tavilyKey?"cli":i?"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":p!==void 0?"env":o?.model.nCtx!==void 0?"file":"default",outputDir:e.outputDir?"cli":o?.sources.outputDir?"file":"default"};return{config:L,origin:Y,path:r,loadedFromFile:!!o}}function Ie(t,e,n=process.env){let r=z.resolve(e),o=Tn(r)??It(),s=[],i={...o.sources,...t.sources??{}};t.sources?.tavilyKey===""&&delete i.tavilyKey,t.sources?.corpusPath===""&&delete i.corpusPath,t.sources?.outputDir===""&&delete i.outputDir,n.TAVILY_API_KEY&&t.sources&&"tavilyKey"in t.sources&&(delete i.tavilyKey,s.push("sources.tavilyKey"));let a={version:1,sources:i,defaults:{...o.defaults,...t.defaults??{}},model:{...o.model,...t.model??{}}},p=z.dirname(r);j.mkdirSync(p,{recursive:!0});let l=r+".tmp-"+process.pid;j.writeFileSync(l,JSON.stringify(a,null,2)+`
|
|
7
|
-
`,"utf8"),
|
|
2
|
+
var qr=Object.defineProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var Nr=(t,e)=>{for(var n in e)qr(t,n,{get:e[n],enumerable:!0})};var Je,Rt=D(()=>{"use strict";Je={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 At(t){let e=process.env.HOME;return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Co(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 Ze(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function vo(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 Ro(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(l=>l.url?Ze(l.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?[Ze(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?[Ze(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(Ze))).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 Mn(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 tt(t,e){return{...t,timeline:[...t.timeline,e]}}function Bn(t,e,n){return{...t,timeline:t.timeline.map(r=>r.id===e?n(r):r)}}function On(t,e){let n=t.nextTimelineId;return{...se(t,e,o=>tt({...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 et(t,e,n){let r=t.agents.get(e);if(!r||r.currentThinkId===null)return t;let o=r.currentThinkId,s=Co(n);return se(t,e,l=>Bn({...l,currentThinkId:null,phase:"content"},o,a=>a.kind==="think"?{...a,body:n,title:s,live:!1,closedAt:Date.now()}:a))}function Pt(t,e){switch(e.type){case"query":return{...Je,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 ${At(e.savedTo)} (skipped: ${e.skipped.join(", ")} \u2014 env active)`:e.gitignored?`saved \u2192 ${At(e.savedTo)} (added to .gitignore)`:`saved \u2192 ${At(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 Mn(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 l=t.mode==="deep"&&n>0?`builds on Task ${n}`:null,a=Mn(t,e.agentId,{phase:"thinking",taskIndex:n,taskDescription:r,dependencyHint:l});return a={...a,researchAgentIds:[...a.researchAgentIds,e.agentId],researchSpawnCount:t.researchSpawnCount+1,pendingTaskIndex:o,pendingTaskDescription:s},On(a,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=On(r,o.id),o=r.agents.get(o.id);else return se(r,o.id,w=>({...w,tokenCount:e.tokenCount}));let s=o.currentThinkId,l=o.timeline.find(w=>w.id===s);if(!l||l.kind!=="think")return r;let a=l.body+e.text,d=a.indexOf(_n);if(d===-1)return se(r,o.id,w=>Bn({...w,tokenCount:e.tokenCount},s,S=>S.kind==="think"?{...S,body:a}:S));let c=a.slice(0,d),u=a.slice(d+_n.length),m=et(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 l=n.timeline.find(d=>d.id===n.currentThinkId),a=l&&l.kind==="think"?l.body:"";r=et(r,e.agentId,a)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,l=>({...l,phase:"tool",toolCallCount:l.toolCallCount+1}));let o=r.nextTimelineId;return{...se(r,e.agentId,l=>tt({...l,phase:"tool",toolCallCount:l.toolCallCount+1,pendingToolCallId:o,contentBuffer:""},{kind:"tool_call",id:o,tool:e.tool,argsSummary:vo(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,a=>({...a,phase:"idle"}));let r=Ro(e.tool,e.result),o=t.nextTimelineId,s=Array.from(new Set(r.hosts));return{...se(t,e.agentId,a=>tt({...a,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=et(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=>tt({...u,phase:"done",contentBuffer:""},{kind:"report",id:o,body:e.result,tokenCount:u.tokenCount})),l=s.agents.get(e.agentId),a=s.researchAgentIds.includes(e.agentId),d=a&&l?[...s.scrollback,{key:`agent-${e.agentId}-${s.scrollback.length}`,kind:"agent",agent:l}]:s.scrollback,c=a?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(l=>l.id===n.currentThinkId),s=o&&o.kind==="think"?o.body:"";r=et(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 _n,Dn=D(()=>{"use strict";Rt();_n="</think>"});import{useEffect as Ao,useReducer as Po}from"react";function qn(t,e=[]){let[n,r]=Po(Pt,e,o=>o.reduce(Pt,Je));return Ao(()=>t.subscribe(r),[t]),n}var Nn=D(()=>{"use strict";Rt();Dn()});import{createContext as Eo,useContext as Io}from"react";function nt(){return Io(Et)}var _o,Et,rt=D(()=>{"use strict";_o=()=>{},Et=Eo(_o)});import{memo as Mo}from"react";import{Box as Oo,Text as Ln}from"ink";import{jsx as Un,jsxs as Bo}from"react/jsx-runtime";var Fn,$n=D(()=>{"use strict";Fn=Mo(function({query:e,warm:n}){return e?Bo(Oo,{flexDirection:"column",marginBottom:1,children:[Un(Ln,{bold:!0,children:e}),n?Un(Ln,{dimColor:!0,children:"follow-up \xB7 warm session"}):null]}):null})});function ot(t){let e=Number.parseInt(t.slice(1),10);return!Number.isFinite(e)||e<0?It[0]:It[e%It.length]}var It,_t=D(()=>{"use strict";It=["cyan","yellow","green","magenta","red","blue"]});var le,st=D(()=>{"use strict";le=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});import{memo as Pe,useEffect as Do,useState as qo}from"react";import{Box as F,Text as _}from"ink";import{jsx as v,jsxs as U}from"react/jsx-runtime";function Lo(t){return No.includes(t.phase)}function Uo(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 Wn(t){let e=t.indexOf(`
|
|
5
|
+
`);return e<=0?"":t.slice(e+1).trimStart()}var No,Mt,Ot,Bt,Dt,Fo,$o,it,qt=D(()=>{"use strict";_t();st();No=["thinking","content","tool"];Mt=Pe(function({item:e,color:n}){let r=e.live?e.body.includes(`
|
|
6
|
+
`)?Uo(e.body):"Thinking\u2026":e.title,o=e.live?Wn(e.body):Wn(e.body).trim();return U(F,{flexDirection:"column",marginBottom:1,flexShrink:0,children:[U(F,{children:[v(_,{color:n,children:"\u2726 "}),v(_,{bold:!0,children:r})]}),o?v(F,{paddingLeft:2,children:U(_,{children:[o,e.live?"\u258E":""]})}):e.live?v(F,{paddingLeft:2,children:v(_,{dimColor:!0,children:"\u258E"})}):null]})});Ot=Pe(function({item:e,pending:n=!1}){let[r,o]=qo(0);return Do(()=>{if(!n)return;let s=setInterval(()=>o(l=>(l+1)%le.length),80);return()=>clearInterval(s)},[n]),U(F,{flexShrink:0,children:[n?U(_,{color:"cyan",children:[le[r]," "]}):v(_,{dimColor:!0,children:"\u203A "}),v(_,{color:"cyan",children:e.tool}),e.argsSummary?U(_,{dimColor:!0,children:[" ",e.argsSummary]}):null]})}),Bt=Pe(function({item:e}){let n=e.hosts.length>0?e.hosts.join(" \xB7 "):null;return U(F,{flexDirection:"column",flexShrink:0,children:[U(F,{paddingLeft:2,children:[v(_,{color:"green",children:"\u2713 "}),v(_,{children:e.resultCount??e.byteLength+"b"}),typeof e.resultCount=="number"?v(_,{children:" results"}):null]}),n?v(F,{paddingLeft:4,children:v(_,{dimColor:!0,children:n})}):e.preview?v(F,{paddingLeft:4,children:v(_,{dimColor:!0,children:e.preview.length>60?e.preview.slice(0,60)+"\u2026":e.preview})}):null]})}),Dt=Pe(function({item:e,color:n}){let r=e.body.trim();return U(F,{flexDirection:"column",marginTop:1,flexShrink:0,children:[U(F,{children:[v(_,{color:n,children:"\u2713 "}),v(_,{bold:!0,children:"report"}),U(_,{dimColor:!0,children:[" \xB7 ",e.tokenCount," tok"]})]}),r?v(F,{paddingLeft:2,children:v(_,{children:r})}):null]})}),Fo=Pe(function({buffer:e,color:n}){return U(F,{flexDirection:"column",marginTop:1,flexShrink:0,children:[U(F,{children:[v(_,{color:n,children:"\u25B8 "}),v(_,{dimColor:!0,bold:!0,children:"streaming"})]}),v(F,{paddingLeft:2,children:U(_,{dimColor:!0,children:[e,"\u258E"]})})]})}),$o=3,it=Pe(function({agent:e,headerPrefix:n,bodyHeight:r,width:o}){let s=ot(e.label),l=Lo(e),a=e.taskDescription??null,d=r+$o;return U(F,{flexDirection:"column",width:o,height:d,paddingX:1,marginRight:1,flexShrink:0,overflow:"hidden",children:[U(F,{flexShrink:0,children:[n?U(_,{dimColor:!0,children:[n," \xB7 "]}):null,v(_,{color:s,bold:!0,children:e.label}),v(F,{flexGrow:1}),v(_,{color:l?s:"green",children:l?"\u25CF":"\u2713"})]}),a?v(_,{dimColor:!0,children:a}):null,e.dependencyHint?U(_,{dimColor:!0,children:["\u2191 ",e.dependencyHint]}):null,U(F,{flexDirection:"column",flexGrow:1,justifyContent:"flex-end",overflow:"hidden",children:[e.timeline.map(c=>c.kind==="think"?v(Mt,{item:c,color:s},c.id):c.kind==="tool_call"?v(Ot,{item:c,pending:e.pendingToolCallId===c.id},c.id):c.kind==="tool_result"?v(Bt,{item:c},c.id):c.kind==="report"?v(Dt,{item:c,color:s},c.id):null),e.contentBuffer?v(Fo,{buffer:e.contentBuffer,color:s}):null]})]})})});import{Box as at,Text as lt}from"ink";import{jsx as he,jsxs as Nt}from"react/jsx-runtime";function zn({agent:t}){let e=ot(t.label),n=t.taskDescription?t.taskDescription.length>80?t.taskDescription.slice(0,80)+"\u2026":t.taskDescription:null;return Nt(at,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,marginBottom:1,children:[Nt(at,{flexShrink:0,children:[he(lt,{color:e,bold:!0,children:t.label}),he(at,{flexGrow:1}),he(lt,{color:"green",children:"\u2713"})]}),n?he(lt,{dimColor:!0,children:n}):null,t.dependencyHint?Nt(lt,{dimColor:!0,children:["\u2191 ",t.dependencyHint]}):null,he(at,{flexDirection:"column",children:t.timeline.map(r=>r.kind==="think"?he(Mt,{item:r,color:e},r.id):r.kind==="tool_call"?he(Ot,{item:r},r.id):r.kind==="tool_result"?he(Bt,{item:r},r.id):r.kind==="report"?he(Dt,{item:r,color:e},r.id):null)})]})}var Hn=D(()=>{"use strict";_t();qt()});import{useEffect as Wo,useState as zo}from"react";import{useStdout as Ho}from"ink";function Yn(){let{stdout:t}=Ho(),[e,n]=zo(()=>[t?.columns??120,t?.rows??40]);return Wo(()=>{if(!t)return;let r=()=>{n([t.columns??120,t.rows??40])};return t.on("resize",r),()=>{t.off("resize",r)}},[t]),e}function jn(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 Lt=D(()=>{"use strict"});import{Box as Ut}from"ink";import{jsx as Ee}from"react/jsx-runtime";function Gn({state:t}){let[e,n]=Yn(),r=t.researchAgentIds.map(l=>t.agents.get(l)).filter(l=>!!l);if(r.length===0)return null;let o=Math.max(Ft,n-Yo);if(t.mode==="flat"){let l=r.length,a=Math.max(Kn*l,e-4),d=Math.max(Kn,Math.floor(a/l)-1);return d*l+l<=e?Ee(Ut,{flexDirection:"row",marginBottom:1,children:r.map(u=>Ee(it,{agent:u,headerPrefix:null,bodyHeight:o,width:d},u.id))}):Ee(Ut,{flexDirection:"column",marginBottom:1,children:r.map(u=>Ee(it,{agent:u,headerPrefix:null,bodyHeight:Math.max(Ft,Math.floor(o/l))},u.id))})}let s=Math.max(Ft,Math.floor(o/Math.max(1,r.length)));return Ee(Ut,{flexDirection:"column",marginBottom:1,children:r.map(l=>Ee(it,{agent:l,headerPrefix:`Task ${(l.taskIndex??0)+1}`,bodyHeight:s},l.id))})}var Yo,Kn,Ft,Qn=D(()=>{"use strict";qt();Lt();Yo=18,Kn=26,Ft=10});import{Box as $e,Text as ke}from"ink";import{jsx as we,jsxs as We}from"react/jsx-runtime";function Vn({state:t}){let{synth:e}=t;if(!e.open&&!e.done)return null;let n=e.done?We($e,{children:[we(ke,{bold:!0,children:"Synthesis "}),we(ke,{color:"green",children:"\u2713"}),e.stats?We(ke,{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]}):We($e,{children:[we(ke,{bold:!0,children:"Synthesis"}),we(ke,{color:"cyan",children:" \u25CF"})]}),r=e.buffer.trim();return We($e,{flexDirection:"column",marginBottom:1,children:[n,e.open&&r?we($e,{paddingLeft:2,marginTop:0,children:We(ke,{children:[r,"\u258E"]})}):e.open?we($e,{paddingLeft:2,children:we(ke,{dimColor:!0,children:"\u258E"})}):null]})}var jo,Xn=D(()=>{"use strict";jo=t=>`${(t/1e3).toFixed(1)}s`});import{Box as Jn,Text as Zn}from"ink";import{jsx as $t,jsxs as Ko}from"react/jsx-runtime";function er({state:t}){return!t.answer||t.synth.done&&t.synth.buffer.trim().length>0?null:Ko(Jn,{flexDirection:"column",marginBottom:1,children:[$t(Zn,{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"}),$t(Jn,{marginTop:1,paddingLeft:2,children:$t(Zn,{children:t.answer.trim()})})]})}var tr=D(()=>{"use strict"});import{useEffect as Go,useState as Qo}from"react";import{Box as nr,Text as ie}from"ink";import{Fragment as es,jsx as ce,jsxs as ze}from"react/jsx-runtime";function Vo(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 Xo(t){return t>=90?"red":t>=70?"yellow":"green"}function Jo(t){let e=0;for(let n of t.agents.values())n.phase!=="done"&&n.phase!=="idle"&&e++;return e}function Zo(t){let e=t.pipelineResumedAt,[,n]=Qo(0);return Go(()=>{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 rr({state:t}){let e=Zo(t),n=t.pressure?.pct??0,r=Jo(t),o=Xo(n);return ce(nr,{borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,paddingTop:0,children:ze(nr,{flexDirection:"row",children:[ce(ie,{dimColor:!0,children:"KV "}),ce(ie,{color:o,children:Vo(n)}),ze(ie,{children:[" ",String(n).padStart(2," "),"%"]}),ce(ie,{dimColor:!0,children:" \xB7 "}),ce(ie,{children:t.phase}),ce(ie,{dimColor:!0,children:" \xB7 \u23F1 "}),ce(ie,{children:jn(e)}),ce(ie,{dimColor:!0,children:" \xB7 "}),ze(ie,{children:[r," active"]}),t.sourceCount>0?ze(es,{children:[ce(ie,{dimColor:!0,children:" \xB7 "}),ce(ie,{dimColor:!0,children:"\u2315 "}),ze(ie,{children:[t.sourceCount," sources"]})]}):null]})})}var or=D(()=>{"use strict";Lt()});import{useState as ts}from"react";import{Text as Ie,useInput as ns}from"ink";import{jsx as ct,jsxs as ir}from"react/jsx-runtime";function me({value:t,onChange:e,onSubmit:n,onCancel:r,placeholder:o="",focused:s=!0,mask:l=!1,color:a}){let[d,c]=ts(t.length),u=Math.min(d,t.length);ns((y,g)=>{if(g.return){n?.(t);return}if(g.escape){r?.();return}if(g.leftArrow){g.meta||g.ctrl?c(sr(t,u)):c(Math.max(0,u-1));return}if(g.rightArrow){g.meta||g.ctrl?c(rs(t,u)):c(Math.min(t.length,u+1));return}if(y==="\x1B[H"||y==="\x1BOH"){c(0);return}if(y==="\x1B[F"||y==="\x1BOF"){c(t.length);return}if(g.backspace||g.delete){if(u===0)return;if(g.meta||g.ctrl){let W=sr(t,u);e(t.slice(0,W)+t.slice(u)),c(W);return}let I=t.slice(0,u-1)+t.slice(u);c(u-1),e(I);return}if(g.ctrl&&y==="a"){c(0);return}if(g.ctrl&&y==="e"){c(t.length);return}if(g.ctrl&&y==="u"){e(t.slice(u)),c(0);return}if(g.ctrl&&y==="k"){e(t.slice(0,u));return}if(g.ctrl&&y==="w"){let I=t.slice(0,u),W=/\S+\s*$/.exec(I),R=W?W.index:0;e(t.slice(0,R)+t.slice(u)),c(R);return}if(!(g.ctrl||g.meta||g.tab||g.upArrow||g.downArrow)&&y.length>0){let I=t.slice(0,u)+y+t.slice(u);c(u+y.length),e(I)}},{isActive:s});let m=l?"*".repeat(t.length):t;if(t.length===0)return ir(Ie,{children:[ct(Ie,{color:a,children:s?"\u258E":""}),ct(Ie,{dimColor:!0,children:o})]});if(!s)return ct(Ie,{color:a,children:m});let S=m.slice(0,u),q=m.slice(u,u+1),E=m.slice(u+1);return ir(Ie,{color:a,children:[S,ct(Ie,{inverse:!0,children:q||" "}),E]})}function sr(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 rs(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 Wt=D(()=>{"use strict"});import{memo as Me,useEffect as zt,useState as _e}from"react";import{Box as J,Text as B,useInput as os}from"ink";import{jsx as k,jsxs as te}from"react/jsx-runtime";function ar(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 ss(t){if(!t)return[];if(!t.name)return ut;let e=t.name.toLowerCase();return ut.filter(n=>n.name.startsWith(e))}var ut,ur,lr,Ht,is,as,cr,dr=D(()=>{"use strict";rt();Wt();ut=[{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"}];ur=Me(function({state:e}){let n=nt(),r=e.config?.defaults.reasoningMode??"flat",[o,s]=_e(r),[l,a]=_e("query"),[d,c]=_e(""),[u,m]=_e(""),[w,S]=_e(!1),q=e.scrollback.length>0,[E,y]=_e(q?"start":"plan");zt(()=>{q&&y("start")},[q]),zt(()=>{e.composerPrefill&&e.composerPrefill!==d&&c(e.composerPrefill)},[e.composerPrefill]),zt(()=>{s(r)},[r]);let g=e.configOrigin?.tavilyKey??"unset",I=e.configOrigin?.corpusPath??"unset",W=e.configOrigin?.outputDir??"default",R=g!=="unset",Z=R||I!=="unset",re=g==="env",Y=e.clarifyContext!==null,C=ar(d),b=C!==null,Q=ss(C);os((T,L)=>{if(L.ctrl&&T==="c"){n({type:"quit"});return}if(L.tab&&L.shift){!b&&!Y&&y(V=>V==="plan"?"start":"plan");return}if(L.tab){if(b&&C&&C.name&&Q.length===1){let V=Q[0];c("/"+V.name+(V.kind==="value"?" ":""));return}return}if(L.escape){if(Y){n({type:"cancel_plan"}),c("");return}c(""),S(!1);return}},{isActive:l==="query"});let oe=T=>{let L=T.trim();if(L){if(!Y){let V=ar(L);if(V){f(V);return}}if(Y){n({type:"submit_clarification",answer:L}),c("");return}Z&&(n({type:"submit_query",query:L,mode:o,skipPlanner:E==="start"}),c(""))}},f=({name:T,value:L})=>{if(!T)return;let V=ut.find(ft=>ft.name===T);if(V){if(c(""),S(!1),V.kind==="instant"){T==="deep"?s("deep"):T==="flat"?s("flat"):T==="quit"?n({type:"quit"}):T==="help"&&S(!0);return}if(L){T==="web"?n({type:"set_tavily_key",key:L}):T==="scan"?n({type:"set_corpus_path",path:L}):T==="output"?n({type:"set_output_dir",path:L}):T==="model"?n({type:"set_model_path",path:L}):T==="reranker"&&n({type:"set_reranker_path",path:L});return}if(T==="web"){if(re)return;m(e.config?.sources.tavilyKey??""),a("web")}else T==="scan"?(m(e.config?.sources.corpusPath??""),a("scan")):T==="output"?(m(e.config?.sources.outputDir??""),a("output")):T==="model"?(m(e.config?.model.path??""),a("model")):T==="reranker"&&(m(e.config?.model.reranker??""),a("reranker"))}};return te(J,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[l==="query"?te(J,{children:[k(B,{children:"\u203A "}),k(me,{value:d,onChange:c,onSubmit:oe,focused:!0,placeholder:Y?"Answer the questions above, or Esc to cancel\u2026":Z?"Ask a research question, or / for commands\u2026":"Type / for commands (e.g. /web, /scan) to add a source"})]}):l==="web"?te(J,{children:[k(B,{color:"yellow",children:"Web search key \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_tavily_key",key:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,mask:!0,placeholder:"tvly-..."})]}):l==="scan"?te(J,{children:[k(B,{color:"yellow",children:"Scan path \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_corpus_path",path:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,placeholder:"/path/to/docs or /path/**/*.md"})]}):l==="output"?te(J,{children:[k(B,{color:"yellow",children:"Output dir \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_output_dir",path:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,placeholder:`${process.cwd()} (default)`})]}):l==="model"?te(J,{children:[k(B,{color:"yellow",children:"Model path \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_model_path",path:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,placeholder:"/path/to/qwen3.5-4b.gguf"})]}):te(J,{children:[k(B,{color:"yellow",children:"Reranker path \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_reranker_path",path:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,placeholder:"/path/to/qwen3-reranker.gguf"})]}),l==="query"&&!Y&&b?k(J,{flexDirection:"column",marginTop:0,children:Q.length===0?k(B,{color:"red",children:"no matching command"}):Q.map(T=>k(lr,{cmd:T},T.name))}):null,l==="query"&&!b&&w?k(J,{flexDirection:"column",marginTop:0,children:ut.map(T=>k(lr,{cmd:T},T.name))}):null,te(J,{marginTop:0,children:[k(Ht,{label:"Web",origin:g,value:R?"set":null,disabled:re}),k(B,{children:" "}),k(Ht,{label:"Scan",origin:I,value:e.config?.sources.corpusPath?e.corpusStatus?`${e.corpusStatus.fileCount} files`:e.config.sources.corpusPath:null}),k(B,{children:" "}),k(Ht,{label:"Output",origin:W,value:e.config?.sources.outputDir??null}),k(J,{flexGrow:1}),l==="query"&&!Y&&!b?k(as,{submitMode:E}):null]}),k(J,{marginTop:0,children:k(is,{field:l,hasSource:Z,inSlash:b,clarifying:Y})}),e.toast?k(J,{marginTop:0,children:k(B,{color:e.toast.tone==="error"?"red":e.toast.tone==="warn"?"yellow":"green",children:e.toast.message})}):null]})}),lr=Me(function({cmd:e}){return te(J,{children:[te(B,{color:"cyan",children:["/",e.name]}),te(B,{dimColor:!0,children:[" \xB7 ",e.desc]}),e.kind==="value"?k(B,{dimColor:!0,children:" <value>"}):null]})}),Ht=Me(function({label:e,origin:n,value:r,disabled:o=!1}){let s=n!=="unset";return te(B,{children:[te(B,{color:s?"green":"gray",dimColor:o,children:[e," ",s?e==="Scan"&&r?r:"\u2713":"\u2014"]}),k(B,{dimColor:!0,children:n==="env"?" (env)":n==="cli"?" (cli)":""})]})}),is=Me(function({field:e,hasSource:n,inSlash:r,clarifying:o}){return e==="web"||e==="scan"||e==="output"||e==="model"||e==="reranker"?k(B,{dimColor:!0,children:"\u23CE save (empty to clear) \xB7 Ctrl+U clear \xB7 Esc cancel"}):o?k(B,{color:"yellow",children:"\u23CE submit answer \xB7 Esc cancel"}):r?k(B,{dimColor:!0,children:"Tab complete \xB7 \u23CE run \xB7 Esc clear"}):n?k(B,{dimColor:!0,children:"\u21E7Tab Plan/Start \xB7 / commands"}):k(B,{color:"yellow",children:"\u26A0 Add a source via /web or /scan"})}),as=Me(function({submitMode:e}){return te(J,{children:[k(cr,{label:"PLAN",focused:e==="plan",hue:"cyan"}),k(B,{children:" "}),k(cr,{label:"START",focused:e==="start",hue:"green"})]})}),cr=Me(function({label:e,focused:n,hue:r}){let s=` ${n?"\u25C9":"\u25CB"} ${e} `;return n?k(B,{backgroundColor:r,color:"black",bold:!0,children:s}):k(B,{dimColor:!0,children:s})})});import{memo as Yt,useEffect as pr,useRef as ls,useState as dt}from"react";import{Box as H,Text as M,useInput as cs}from"ink";import{jsx as A,jsxs as j}from"react/jsx-runtime";var hr,us,ds,mr=D(()=>{"use strict";rt();Wt();hr=Yt(function({state:e}){let n=nt(),r=e.plan,[o,s]=dt(e.mode??"flat"),[l,a]=dt(()=>r?.tasks.length??0),[d,c]=dt(null),[u,m]=dt("");pr(()=>{e.mode&&e.mode!==o&&s(e.mode),c(null),a(r?.tasks.length??0)},[e.mode]),pr(()=>{r&&l>r.tasks.length&&a(r.tasks.length)},[r?.tasks.length]);let w=ls({focusedIndex:l,editingIndex:d,mode:o,plan:r,query:e.query});if(w.current={focusedIndex:l,editingIndex:d,mode:o,plan:r,query:e.query},cs((E,y)=>{let g=w.current,I=g.plan,W=g.editingIndex,R=g.focusedIndex,ge=g.mode;if(!I||W!==null)return;if(I.intent!=="research"){if(y.return){I.intent==="clarify"&&n({type:"edit_plan",query:g.query});return}y.escape&&n({type:"cancel_plan"}),y.ctrl&&E==="c"&&n({type:"quit"});return}if(y.ctrl&&E==="c"){n({type:"quit"});return}if(y.escape){n({type:"cancel_plan"});return}let Z=R>=I.tasks.length;if(y.shift&&y.upArrow){!Z&&R>0&&(n({type:"move_task",from:R,to:R-1}),a(R-1));return}if(y.shift&&y.downArrow){!Z&&R<I.tasks.length-1&&(n({type:"move_task",from:R,to:R+1}),a(R+1));return}if(y.upArrow){a(Math.max(0,R-1));return}if(y.downArrow){a(Math.min(I.tasks.length,R+1));return}if(y.return){Z?n({type:"accept_plan"}):(m(I.tasks[R]?.description??""),c(R));return}if(E==="a"||E==="A"||E==="+"){let re=Z?I.tasks.length-1:R,Y=re+1;n({type:"add_task",afterIndex:re}),a(Y),m(""),c(Y);return}if(E==="d"||E==="D"||y.delete){!Z&&I.tasks.length>1&&n({type:"delete_task",index:R});return}if(E==="t"||E==="T"){let re=ge==="deep"?"flat":"deep";s(re),n({type:"change_mode",mode:re});return}}),!r)return null;if(r.intent==="clarify")return j(H,{flexDirection:"column",marginBottom:1,children:[A(H,{marginBottom:1,children:A(M,{bold:!0,children:e.query})}),A(M,{dimColor:!0,children:"A few questions to narrow this down."}),A(H,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.clarifyQuestions.map((E,y)=>j(M,{children:[j(M,{dimColor:!0,children:["(",y+1,")"]})," ",E]},y))}),A(H,{marginTop:1,children:A(M,{dimColor:!0,children:"\u23CE answer \xB7 Esc cancel"})})]});if(r.intent==="passthrough")return j(H,{flexDirection:"column",marginBottom:1,children:[A(M,{bold:!0,children:e.query}),A(M,{dimColor:!0,children:"Answering directly \u2014 no research needed."})]});let S=o==="flat"?"parallel":"chained",q=d!==null;return j(H,{flexDirection:"column",marginBottom:1,children:[A(H,{marginBottom:1,children:A(M,{bold:!0,children:e.query})}),j(H,{marginBottom:1,children:[A(M,{dimColor:!0,children:"Research plan"}),j(M,{dimColor:!0,children:[" \xB7 ",r.tasks.length," ",S," tasks"]}),q?j(M,{color:"yellow",children:[" \xB7 editing row ",d+1]}):null]}),j(H,{flexDirection:"column",children:[r.tasks.map((E,y)=>A(ds,{index:y,description:E.description,focused:y===l,editing:y===d,draft:u,onDraftChange:m,onSubmit:g=>{n({type:"update_task_description",index:y,description:g.trim()}),c(null)},onCancel:()=>c(null)},y)),A(us,{focused:l>=r.tasks.length&&!q})]}),j(H,{marginTop:1,children:[j(M,{color:o==="deep"?"cyan":void 0,bold:o==="deep",children:[o==="deep"?"\u25C6":"\u25CB"," Deep"]}),A(M,{children:" "}),j(M,{color:o==="flat"?"cyan":void 0,bold:o==="flat",children:[o==="flat"?"\u25C6":"\u25CB"," Flat"]}),A(M,{dimColor:!0,children:" T toggle mode (re-plans, discards edits)"})]}),A(H,{marginTop:1,children:q?A(M,{dimColor:!0,children:"\u23CE save \xB7 Esc revert"}):j(M,{dimColor:!0,children:["\u2191\u2193 select \xB7 \u23CE ",l>=r.tasks.length?"start research":"edit"," \xB7 A add \xB7 D delete \xB7 \u21E7\u2191\u2193 reorder \xB7 Esc cancel"]})})]})}),us=Yt(function({focused:e}){return e?A(H,{paddingLeft:2,marginTop:1,children:A(M,{backgroundColor:"green",color:"black",bold:!0,children:" \u25B6 START research "})}):A(H,{paddingLeft:2,marginTop:1,children:A(M,{dimColor:!0,children:" \u25B6 START research"})})}),ds=Yt(function({index:e,description:n,focused:r,editing:o,draft:s,onDraftChange:l,onSubmit:a,onCancel:d}){return o?j(H,{paddingLeft:2,children:[A(M,{color:"yellow",bold:!0,children:`\u25B6 ${e+1}. `}),A(H,{flexGrow:1,children:A(me,{value:s,onChange:l,onSubmit:a,onCancel:d,focused:!0,placeholder:"(empty \u2014 type a task description)"})})]}):r?j(H,{paddingLeft:2,children:[A(M,{color:"cyan",bold:!0,children:`\u203A ${e+1}. `}),A(M,{bold:!0,children:n||A(M,{dimColor:!0,children:"(empty)"})})]}):j(H,{paddingLeft:2,children:[A(M,{dimColor:!0,children:` ${e+1}. `}),A(M,{dimColor:!0,children:n||"(empty)"})]})})});import{memo as ps,useEffect as hs,useState as ms}from"react";import{Box as fr,Text as jt}from"ink";import{jsx as gr,jsxs as Kt}from"react/jsx-runtime";var yr,br=D(()=>{"use strict";st();yr=ps(function({state:e}){let[n,r]=ms(0);return hs(()=>{let o=setInterval(()=>r(s=>(s+1)%le.length),80);return()=>clearInterval(o)},[]),Kt(fr,{flexDirection:"column",marginBottom:1,children:[gr(jt,{bold:!0,children:e.query}),Kt(fr,{marginTop:1,children:[Kt(jt,{color:"cyan",children:[le[n]," "]}),gr(jt,{dimColor:!0,children:"Planning\u2026"})]})]})})});import{memo as fs}from"react";import{Box as xr,Text as pt}from"ink";import{jsx as Gt,jsxs as Qt}from"react/jsx-runtime";var kr,wr=D(()=>{"use strict";kr=fs(function({state:e}){if(!e.clarifyContext)return null;let{originalQuery:n,questions:r}=e.clarifyContext;return Qt(xr,{flexDirection:"column",marginBottom:1,children:[Gt(pt,{bold:!0,children:n}),Gt(pt,{dimColor:!0,children:"A few questions to narrow this down."}),Gt(xr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.map((o,s)=>Qt(pt,{children:[Qt(pt,{dimColor:!0,children:["(",s+1,")"]})," ",o]},s))})]})})});import{memo as Tr,useEffect as gs,useState as ys}from"react";import{Box as Te,Text as N}from"ink";import{Fragment as ks,jsx as ne,jsxs as K}from"react/jsx-runtime";function xs(t){try{return new URL(t).host}catch{return null}}function ht(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 Sr,bs,Cr=D(()=>{"use strict";st();Sr=Tr(function({state:e}){let[n,r]=ys(0);if(gs(()=>{let o=setInterval(()=>r(s=>(s+1)%le.length),80);return()=>clearInterval(o)},[]),e.uiPhase==="boot_error"){let o=e.bootError,s=o?.kind??"llm",l=s==="llm"?"LLM":"reranker",a=s==="llm"?"/model":"/reranker",d=s==="llm"?"/reranker":"/model";return K(Te,{flexDirection:"column",marginBottom:1,children:[K(N,{color:"red",bold:!0,children:["\u2717 Boot failed (",l,")"]}),ne(Te,{paddingLeft:2,children:ne(N,{children:o?.message??"Unknown error"})}),ne(Te,{paddingLeft:2,marginTop:1,children:K(N,{dimColor:!0,children:["Type ",K(N,{color:"cyan",children:[a," "]}),ne(N,{dimColor:!0,children:"<path-to-gguf>"}),K(N,{dimColor:!0,children:[" to use a local ",l,", or "]}),ne(N,{color:"cyan",children:d}),ne(N,{dimColor:!0,children:" for the other, or "}),ne(N,{color:"cyan",children:"/quit"}),ne(N,{dimColor:!0,children:" to exit."})]})})]})}return e.uiPhase==="downloading"?K(Te,{flexDirection:"column",marginBottom:1,children:[K(Te,{children:[K(N,{color:"cyan",children:[le[n]," "]}),ne(N,{bold:!0,children:"Downloading models"})]}),e.downloads.map(o=>ne(bs,{item:o},o.id))]}):K(Te,{marginBottom:1,children:[K(N,{color:"cyan",children:[le[n]," "]}),ne(N,{bold:!0,children:e.loadingLabel??"Loading\u2026"})]})}),bs=Tr(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),l=e.url?xs(e.url):null,a=e.started&&l!==null,d=e.done?"\u2713 ":a?"\u25CF ":"\u25CB ",c=e.done?"green":a?"cyan":void 0,u=!a&&!e.done;return K(Te,{paddingLeft:2,children:[ne(N,{color:c,dimColor:u,children:d}),K(N,{dimColor:u,children:[e.label.padEnd(28)," "]}),e.done?ne(N,{dimColor:!0,children:ht(e.got)}):a?K(ks,{children:[ne(N,{color:"cyan",children:s}),K(N,{children:[" ",String(n).padStart(2),"% \xB7 ",ht(e.got)," / ",ht(e.total)]}),K(N,{dimColor:!0,children:[" \xB7 ",l]})]}):K(N,{dimColor:!0,children:["queued \xB7 ",ht(e.total)]})]})})});import{Box as mt,Static as ws,Text as vr}from"ink";import{jsx as G,jsxs as Vt}from"react/jsx-runtime";function Rr({bus:t,dispatch:e,bootstrap:n}){let r=qn(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",l=r.uiPhase==="composer"||r.uiPhase==="done"||r.uiPhase==="clarifying"||r.uiPhase==="boot_error";return Vt(Et.Provider,{value:e,children:[G(ws,{items:r.scrollback,children:a=>a.kind==="agent"?G(mt,{paddingX:2,children:G(zn,{agent:a.agent})},a.key):Vt(mt,{flexDirection:"column",paddingX:2,marginBottom:1,children:[G(vr,{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"}),G(mt,{paddingLeft:2,marginTop:1,children:G(vr,{children:a.body})})]},a.key)}),Vt(mt,{flexDirection:"column",paddingX:2,paddingY:1,children:[o&&G(Fn,{query:r.query,warm:r.warm}),(r.uiPhase==="downloading"||r.uiPhase==="loading"||r.uiPhase==="boot_error")&&G(Sr,{state:r}),r.uiPhase==="planning"&&G(yr,{state:r}),r.uiPhase==="plan_review"&&G(hr,{state:r}),r.uiPhase==="clarifying"&&G(kr,{state:r}),s&&G(Gn,{state:r}),s&&G(Vn,{state:r}),r.uiPhase==="done"&&G(er,{state:r}),l&&G(ur,{state:r}),G(rr,{state:r})]})]})}var Ar=D(()=>{"use strict";Nn();rt();$n();Hn();Qn();Xn();tr();or();dr();mr();br();wr();Cr()});var Pr={};Nr(Pr,{render:()=>Cs});import Ts from"react";import{render as Ss}from"ink";function Cs(t,e,n=[]){return Ss(Ts.createElement(Rr,{bus:t,dispatch:e,bootstrap:n}),{incrementalRendering:!0})}var Er=D(()=>{"use strict";Ar()});import*as z from"node:fs";import*as pe from"node:path";import{parseArgs as vs}from"node:util";import{main as Rs,ensure as Xt,createSignal as As,spawn as Ps,each as Se,call as Be}from"effection";import{createContext as Es}from"@lloyal-labs/lloyal.node";import{initAgents as Is,JsonlTraceWriter as _s}from"@lloyal-labs/lloyal-agents";var gt=!1,Lr=!1;function an(t){gt=t}function ln(t){Lr=t}var yt=!!process.stdout.isTTY,bt=yt?{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:""},sn="";function Ur(){sn&&(sn="",process.stdout.write("\r\x1B[K"))}var Ke=(...t)=>{gt||(Ur(),console.log(...t))};function cn(t,e){gt&&console.log(JSON.stringify({event:t,...e}))}import*as ee from"node:fs";import*as X from"node:path";import*as xt from"node:os";import*as Ge from"node:path";function ye(t){if(!t)return"";let e=t==="~"?xt.homedir():t.startsWith("~/")?Ge.join(xt.homedir(),t.slice(2)):t;return Ge.resolve(e)}function kt(){return{version:1,sources:{},defaults:{reasoningMode:"flat",maxTurns:10},model:{}}}function dn(t){try{let e=ee.readFileSync(t,"utf8"),n=JSON.parse(e);if(n.version!==1)return null;let r=kt();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=X.resolve(t),o=dn(r),s=o??kt(),l=n.TAVILY_API_KEY?.trim()||void 0,a=n.LLAMA_CTX_SIZE?.trim(),d=a&&/^\d+$/.test(a)?parseInt(a,10):void 0,c=e.tavilyKey??l??s.sources.tavilyKey,u=e.corpusPath??s.sources.corpusPath,m=u?ye(u):void 0,w=e.outputDir??s.sources.outputDir,S=w?ye(w):void 0,q=e.reasoningMode??s.defaults.reasoningMode??"flat",E=e.modelPath??s.model.path,y=E?ye(E):void 0,g=e.reranker??s.model.reranker,I=e.nCtx??d??s.model.nCtx,W={version:1,sources:{tavilyKey:c,corpusPath:m,outputDir:S},defaults:{reasoningMode:q,maxTurns:s.defaults.maxTurns},model:{path:y,reranker:g,nCtx:I}},R={tavilyKey:e.tavilyKey?"cli":l?"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:W,origin:R,path:r,loadedFromFile:!!o}}function ve(t,e,n=process.env){let r=X.resolve(e),o=dn(r)??kt(),s=[],l={...o.sources,...t.sources??{}};t.sources?.tavilyKey===""&&delete l.tavilyKey,t.sources?.corpusPath===""&&delete l.corpusPath,t.sources?.outputDir===""&&delete l.outputDir,n.TAVILY_API_KEY&&t.sources&&"tavilyKey"in t.sources&&(delete l.tavilyKey,s.push("sources.tavilyKey"));let a={version:1,sources:l,defaults:{...o.defaults,...t.defaults??{}},model:{...o.model,...t.model??{}}},d=X.dirname(r);ee.mkdirSync(d,{recursive:!0});let c=r+".tmp-"+process.pid;ee.writeFileSync(c,JSON.stringify(a,null,2)+`
|
|
7
|
+
`,"utf8"),ee.renameSync(c,r);let u=Fr(r);return{path:r,gitignored:u,skipped:s}}function Fr(t){try{let e=$r(X.dirname(t));if(!e)return!1;let n=X.join(e,".gitignore"),r=X.relative(e,t).replace(/\\/g,"/"),o=ee.existsSync(n)?ee.readFileSync(n,"utf8"):"",s=X.basename(t);if(new RegExp(`(^|\\n)\\s*(${un(r)}|${un(s)})\\s*(\\n|$)`).test(o))return!1;let a=o.length===0||o.endsWith(`
|
|
8
8
|
`)?"":`
|
|
9
|
-
`;return
|
|
10
|
-
`),!0}catch{return!1}}function
|
|
9
|
+
`;return ee.appendFileSync(n,a+r+`
|
|
10
|
+
`),!0}catch{return!1}}function un(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $r(t){let e=X.resolve(t);for(;;){if(ee.existsSync(X.join(e,".git")))return e;let n=X.dirname(e);if(n===e)return null;e=n}}function pn(){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 Ms}from"@lloyal-labs/rig";import{createReranker as Os,WebSource as Bs,CorpusSource as Ds,chunkResources as qs,resolveCorpusInput as Ns}from"@lloyal-labs/rig/node";import Ls from"ignore";import{call as wt}from"effection";import{Ctx as St,Events as Qe,agentPool as Xr,createToolkit as Jr,useAgent as Zr,chain as eo,parallel as to,renderTemplate as De,withSharedRoot as no,DefaultAgentPolicy as Rn}from"@lloyal-labs/lloyal-agents";import{reportTool as Tn,PlanTool as ro}from"@lloyal-labs/rig";import{taskToContent as Sn}from"@lloyal-labs/rig";var hn=`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
|
|
|
@@ -94,7 +94,7 @@ BAD \u2014 individual task issues (for research intent):
|
|
|
94
94
|
|
|
95
95
|
<%= it.context %>
|
|
96
96
|
<% } -%>
|
|
97
|
-
`;var
|
|
97
|
+
`;var mn=`You're a research planner. You analyze a user query and pick ONE of three dispositions, producing a JSON plan. Output JSON only.
|
|
98
98
|
---
|
|
99
99
|
The query: "<%= it.query %>"
|
|
100
100
|
|
|
@@ -180,27 +180,7 @@ BAD \u2014 individual task issues (for research intent):
|
|
|
180
180
|
|
|
181
181
|
<%= it.context %>
|
|
182
182
|
<% } -%>
|
|
183
|
-
`;var
|
|
184
|
-
---
|
|
185
|
-
Research notes:
|
|
186
|
-
|
|
187
|
-
<%= it.agentFindings %>
|
|
188
|
-
|
|
189
|
-
---
|
|
190
|
-
|
|
191
|
-
Source passages:
|
|
192
|
-
|
|
193
|
-
<%= it.sourcePassages %>
|
|
194
|
-
|
|
195
|
-
Answer: "<%= it.query %>"
|
|
196
|
-
`;var An=`You are a consistency checker. Compare the responses below. Output JSON only.
|
|
197
|
-
|
|
198
|
-
Converged means: the responses agree on the key conclusions, even if they differ in detail, emphasis, or wording. Disagreement on minor points doesn't break convergence \u2014 disagreement on the core answer does.
|
|
199
|
-
---
|
|
200
|
-
Do these responses agree on the key conclusions?
|
|
201
|
-
|
|
202
|
-
<%= it.responses %>
|
|
203
|
-
`;var Pn=`You are a research reporter. The agent has been terminated due to budget constraints and must deliver findings now.
|
|
183
|
+
`;var fn="You are a research assistant.";var gn=`You are a research reporter. The agent has been terminated due to budget constraints and must deliver findings now.
|
|
204
184
|
|
|
205
185
|
Call the report tool with the most important findings from the research above. Prioritize in this order:
|
|
206
186
|
1. Direct quotes and specific evidence that answer the task
|
|
@@ -210,7 +190,7 @@ Call the report tool with the most important findings from the research above. P
|
|
|
210
190
|
IMPORTANT: You have approximately <%= it.budget %> words for your report. Be concise \u2014 if you exceed the budget your report will be cut off.
|
|
211
191
|
---
|
|
212
192
|
Report your findings.
|
|
213
|
-
`;var
|
|
193
|
+
`;var yn=`You are writing an analytical research report that answers the user's question below.
|
|
214
194
|
|
|
215
195
|
Above this message is the research that has been done: a series of conversation turns where each user turn asks a sub-question and the assistant turn that follows contains the findings for that sub-question.
|
|
216
196
|
|
|
@@ -321,7 +301,7 @@ OUTPUT FORMAT: emit the markdown report directly as your reply. Do NOT wrap it i
|
|
|
321
301
|
Research question: "<%= it.query %>"
|
|
322
302
|
|
|
323
303
|
Write the markdown report now.
|
|
324
|
-
`;var
|
|
304
|
+
`;var bn=`You are writing an analytical research report that answers the user's question below.
|
|
325
305
|
|
|
326
306
|
The findings below come from N research agents that ran in parallel. Each agent covered a distinct facet of the question independently \u2014 they did not see each other's work. Your job is to synthesize their fan-in into a single coherent argument.
|
|
327
307
|
|
|
@@ -436,7 +416,7 @@ Findings from <%= it.agentCount %> parallel research agents:
|
|
|
436
416
|
<%= it.findings %>
|
|
437
417
|
|
|
438
418
|
Write the markdown report now.
|
|
439
|
-
`;var
|
|
419
|
+
`;var xn=`Apply the **corpus_research** skill.
|
|
440
420
|
|
|
441
421
|
You are a thorough research assistant analyzing a knowledge base to complete your task.
|
|
442
422
|
<% if (it.agentCount > 1) { -%>
|
|
@@ -464,7 +444,7 @@ PROCESS:
|
|
|
464
444
|
3. Based on what you read, identify specific claims to verify or details that are missing, then grep/search for those.
|
|
465
445
|
4. Call report() with comprehensive findings: direct quotes, data points, source URLs. State what you found AND what you checked but could not find. Do not summarize \u2014 preserve the detail.
|
|
466
446
|
|
|
467
|
-
`;var
|
|
447
|
+
`;var kn=`Apply the **web_research** skill.
|
|
468
448
|
|
|
469
449
|
You are a thorough research assistant investigating with your tools to complete your task.
|
|
470
450
|
<% if (it.agentCount > 1) { -%>
|
|
@@ -497,7 +477,7 @@ PROCESS:
|
|
|
497
477
|
2. Immediately fetch the most information-dense links from the search results: research papers, community discussions (Reddit, HN, forums), survey articles that name many specific works.
|
|
498
478
|
3. From what you read, identify the specific projects, techniques, or entities relevant to your task. If a follow-up search would target a different angle, run it \u2014 but only after reading what you already have.
|
|
499
479
|
4. Call report() with comprehensive findings: direct quotes, data points, source URLs. State what you found AND what you checked but could not find. Do not summarize \u2014 preserve the detail.
|
|
500
|
-
`;var
|
|
480
|
+
`;var wn=`You are an assistant working as part of a multi-agent workflow. You have access to the tools below, grouped by skill. You should only use the tools for a given skill when that particular skill is requested explicitly in your task instructions.
|
|
501
481
|
|
|
502
482
|
# Skills
|
|
503
483
|
|
|
@@ -619,27 +599,25 @@ ASSISTANT calls: report({"summary": "(no findings \u2014 no corpus inspection pe
|
|
|
619
599
|
\u2717 WRONG. Research skills require gathering evidence before reporting. report is the terminal \u2014 calling it without prior grep/search/read_file produces an empty finding.
|
|
620
600
|
|
|
621
601
|
<% } -%>
|
|
622
|
-
`;function
|
|
602
|
+
`;function Re(t){let e=t.trim(),n=e.indexOf(`
|
|
623
603
|
---
|
|
624
|
-
`);return n===-1?{system:e,user:""}:{system:e.slice(0,n).trim(),user:e.slice(n+5).trim()}}var
|
|
625
|
-
|
|
626
|
-
${n.context}`:`Today's date: ${s}`,l=yield*a.execute({query:t,context:p});return yield*o({type:"plan",intent:l.intent,tasks:l.tasks,clarifyQuestions:l.clarifyQuestions,tokenCount:l.tokenCount,timeMs:l.timeMs}),l}function*_e(t,e,n,r){let o=yield*Bt.expect(),s=u=>o.send(u),i=yield*$o(t,e);yield*s({type:"answer",text:i.answer});let p=(yield*Ot.expect())._storeKvPressure(),l=p.nCtx||1;yield*s({type:"stats",timings:[{label:"Plan",tokens:n.tokenCount,detail:n.intent,timeMs:n.timeMs},{label:"Passthrough",tokens:i.tokenCount,detail:"trunk stream",timeMs:i.timeMs}],ctxPct:Math.round(100*p.cellsUsed/l),ctxPos:p.cellsUsed,ctxTotal:l}),yield*s({type:"complete",data:{intent:n.intent,planTokens:n.tokenCount,passthroughTokens:i.tokenCount,wallTimeMs:Math.round(performance.now()-r),planMs:Math.round(n.timeMs),passthroughMs:Math.round(i.timeMs)}})}function*Dt(t,e,n,r,o,s,i){let a=yield*Bt.expect(),p=P=>a.send(P);if(e.intent!=="research")throw new Error(`runResearchBranch: expected plan.intent=research, got ${e.intent}`);let l=e.tasks,u=zn();yield*p({type:"research:start",agentCount:l.length,mode:s.reasoningMode});let h=at();for(let P of r)yield*P.bind({reranker:o});let x=new Map(r.map(P=>[P,P.createScorer(t)])),k=r.flatMap(P=>P.tools),M=r[0],H=x.get(M),R=r.some(P=>P.name==="web"),g=r.some(P=>typeof P.promptData=="function"),Q=Te(Fo,{hasWeb:R,hasCorpus:g}),L=Ro([...k,Nn]),Y=0,V=0,{answer:Z,totalTokens:te,totalToolCalls:ie,synthTokens:W}=yield*Po({parent:n.trunk??void 0,systemPrompt:Q,toolsJson:L.toolsJson},function*(P){s.reasoningMode==="flat"&&(yield*p({type:"fanout:tasks",tasks:l}));let ne=yield*Dn({tools:[...k,Nn],parent:P,terminalTool:"report",maxTurns:s.maxTurns,pruneOnReport:!0,policy:Uo(),scorer:H,enableThinking:!0,orchestrate:s.reasoningMode==="flat"?qn(l.map((we,re)=>({content:Ln(we),systemPrompt:$n(M,{maxTurns:s.maxTurns,agentCount:l.length,siblingTasks:l.filter((Ae,$e)=>$e!==re).map(Ae=>Ae.description),date:u,taskIndex:0}),seed:1e3+re}))):Ao(l,(we,re)=>({task:{content:Ln(we),systemPrompt:$n(M,{maxTurns:s.maxTurns,agentCount:1,siblingTasks:[],date:u,taskIndex:re})},userContent:`Research task: ${we.description}`,beforeSpawn:function*(){yield*p({type:"spine:task",taskIndex:re,taskCount:l.length,description:we.description}),yield*p({type:"spine:source",taskIndex:re,source:M.name})},afterExtend:function*(Ae,$e){yield*p({type:"spine:task:done",taskIndex:re,stageFindings:Ae,accumulated:$e})}}))});V=h(),yield*p({type:"research:done",totalTokens:ne.totalTokens,totalToolCalls:ne.totalToolCalls,timeMs:V}),yield*p({type:"synthesize:start"});let oo=at(),fn=s.reasoningMode==="flat"?qo:Do,so=s.reasoningMode==="flat"?ne.agents.map((we,re)=>{let Ae=l[re]?.description??`task ${re+1}`,$e=we.result?.trim()||"(no findings)";return`### Agent ${re+1}: ${Ae}
|
|
604
|
+
`);return n===-1?{system:e,user:""}:{system:e.slice(0,n).trim(),user:e.slice(n+5).trim()}}var oo=Re(hn),so=Re(mn),io=Re(fn),ao=Re(gn),lo=Re(yn),co=Re(bn),uo=xn,po=kn,ho=wn;function mo(){return new Rn({budget:{context:{softLimit:2048,hardLimit:1024},time:{softLimit:24e4,hardLimit:36e4}},recovery:{prompt:ao},terminalTool:"report"})}var Tt=class extends Rn{onProduced(...e){let[,n]=e;return!n.toolCalls[0]&&n.content?{type:"free_text_report",content:n.content}:super.onProduced(...e)}};function Cn(t,e){return t.promptData?De(uo,{...t.promptData(),...e}):t.name==="web"?De(po,e):io.system}function An(){return new Date().toISOString().slice(0,10)}function vn(){let t=performance.now();return()=>performance.now()-t}function Ct(t){return{intent:"research",tasks:[{description:t}],clarifyQuestions:[],tokenCount:0,timeMs:0}}function*fo(t,e){let n=e.trunk;if(!n)throw new Error("runPassthrough: session has no trunk");let r=yield*St.expect(),o=r.getTurnSeparator(),{prompt:s}=r.formatChatSync(JSON.stringify([{role:"user",content:t}]),{addGenerationPrompt:!0,enableThinking:!1}),l=[...o,...r.tokenizeSync(s,!1)];yield*wt(()=>n.prefill(l));let a=performance.now(),d=0,c=[];for(;;){let{token:u,text:m,isStop:w}=n.produceSync();if(w)break;yield*wt(()=>n.commit(u)),d++,c.push(m)}return{answer:c.join(""),tokenCount:d,timeMs:performance.now()-a}}function*go(t,e,n){let r=yield*Qe.expect(),o=u=>r.send(u);yield*o({type:"query",query:t,warm:!!e.trunk});let s=An(),l=n.reasoningMode==="flat"?so:oo,a=new ro({prompt:l,session:e,maxQuestions:10}),d=n.context?`Today's date: ${s}
|
|
627
605
|
|
|
628
|
-
${$e}`}).
|
|
606
|
+
${n.context}`:`Today's date: ${s}`,c=yield*a.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*Ae(t,e,n,r,o){let s=yield*Qe.expect(),l=d=>s.send(d);yield*l({type:"plan:start",query:t,mode:o.reasoningMode});let a=yield*go(t,e,{reasoningMode:o.reasoningMode,context:o.context});if(a.intent==="clarify")return{type:"clarify",plan:a};if(a.intent==="passthrough"){if(!e.trunk){let c=Ct(t);return o.onStart?.(),yield*qe(t,c,e,n,r,{...o}),{type:"done"}}o.onStart?.();let d=yield*fo(t,e);return yield*l({type:"answer",text:d.answer}),yield*yo(a,d,o.wallStartMs),{type:"done"}}return{type:"research_plan",plan:a}}function*qe(t,e,n,r,o,s){if(e.intent!=="research")throw new Error(`runResearchPlan: expected plan.intent=research, got ${e.intent}`);let l=yield*Qe.expect(),a=C=>l.send(C),d=e.tasks,c=An();yield*a({type:"research:start",agentCount:d.length,mode:s.reasoningMode});let u=vn();for(let C of r)yield*C.bind({reranker:o});let m=new Map(r.map(C=>[C,C.createScorer(t)])),w=r.flatMap(C=>C.tools),S=r[0],q=m.get(S),E=r.some(C=>C.name==="web"),y=r.some(C=>typeof C.promptData=="function"),g=De(ho,{hasWeb:E,hasCorpus:y}),I=Jr([...w,Tn]),W=0,R=0,{answer:ge,totalTokens:Z,totalToolCalls:re,synthTokens:Y}=yield*no({parent:n.trunk??void 0,systemPrompt:g,toolsJson:I.toolsJson},function*(C){s.reasoningMode==="flat"&&(yield*a({type:"fanout:tasks",tasks:d}));let b=yield*Xr({tools:[...w,Tn],parent:C,terminalTool:"report",maxTurns:s.maxTurns,pruneOnReport:!0,policy:mo(),scorer:q,enableThinking:!0,orchestrate:s.reasoningMode==="flat"?to(d.map((h,x)=>({content:Sn(h),systemPrompt:Cn(S,{maxTurns:s.maxTurns,agentCount:d.length,siblingTasks:d.filter((O,T)=>T!==x).map(O=>O.description),date:c,taskIndex:0}),seed:1e3+x}))):eo(d,(h,x)=>({task:{content:Sn(h),systemPrompt:Cn(S,{maxTurns:s.maxTurns,agentCount:1,siblingTasks:[],date:c,taskIndex:x})},userContent:`Research task: ${h.description}`,beforeSpawn:function*(){yield*a({type:"spine:task",taskIndex:x,taskCount:d.length,description:h.description}),yield*a({type:"spine:source",taskIndex:x,source:S.name})},afterExtend:function*(O,T){yield*a({type:"spine:task:done",taskIndex:x,stageFindings:O,accumulated:T})}}))});if(R=u(),yield*a({type:"research:done",totalTokens:b.totalTokens,totalToolCalls:b.totalToolCalls,timeMs:R}),d.length===1)return{answer:b.agents[0]?.result?.trim()??"",totalTokens:b.totalTokens,totalToolCalls:b.totalToolCalls,synthTokens:0};yield*a({type:"synthesize:start"});let Q=vn(),oe=s.reasoningMode==="flat"?co:lo,f=s.reasoningMode==="flat"?b.agents.map((h,x)=>{let O=d[x]?.description??`task ${x+1}`,T=h.result?.trim()||"(no findings)";return`### Agent ${x+1}: ${O}
|
|
629
607
|
|
|
630
|
-
|
|
608
|
+
${T}`}).join(`
|
|
631
609
|
|
|
632
|
-
`),
|
|
610
|
+
`):void 0,i={query:t,findings:f,agentCount:d.length},p=yield*Zr({systemPrompt:De(oe.system,i),task:De(oe.user,i),parent:C,policy:new Tt,maxTurns:s.maxTurns});return W=Q(),yield*a({type:"synthesize:done",agentId:p.id,ppl:p.branch.disposed?0:p.branch.perplexity,tokenCount:p.tokenCount,toolCallCount:p.toolCallCount,timeMs:W}),{answer:p.result||"",totalTokens:b.totalTokens,totalToolCalls:b.totalToolCalls,synthTokens:p.tokenCount}});yield*a({type:"answer",text:ge}),ge&&(yield*wt(()=>n.commitTurn(t,ge))),yield*bo({plan:e,researchTokens:Z,researchToolCalls:re,researchTimeMs:R,synthTokens:Y,synthTimeMs:W,wallStartMs:s.wallStartMs,send:a})}function*yo(t,e,n){let r=yield*Qe.expect(),o=c=>r.send(c),l=(yield*St.expect())._storeKvPressure(),a=l.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*l.cellsUsed/a),ctxPos:l.cellsUsed,ctxTotal:a}),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*bo(t){let n=(yield*St.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 ae from"node:fs";import*as En from"node:os";import*as be from"node:path";var Pn={name:"reasoning.run",version:"0.1.1",description:"Local deep-research agent composer \u2014 runs on your machine, zero-config after the first query. Built with Lloyal HDK.",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.0.0","@lloyal-labs/lloyal.node":"^2.1.0","@lloyal-labs/rig":"^2.0.1","@lloyal-labs/sdk":"^2.0.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:["deep-research","local-llm","agents","llama.cpp","cli","tui","ink"],repository:{type:"git",url:"git+https://github.com/lloyal-ai/reasoning-run.git"},license:"SEE LICENSE IN LICENSE"};var ko=`reasoning.run/${Pn.version}`,vt=[{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}],wo=vt.find(t=>t.kind==="llm"),To=vt.find(t=>t.kind==="reranker");function Ve(){let t=process.env.XDG_CACHE_HOME||be.join(En.homedir(),".cache");return be.join(t,"lloyal","models")}function Ne(t,e){if(!t){let r=e==="llm"?wo:To;return{path:be.join(Ve(),r.filename),entry:r}}let n=vt.find(r=>r.id===t);return n?{path:be.join(Ve(),n.filename),entry:n}:{path:be.resolve(t),entry:null}}async function In(t,e={}){let n=be.join(Ve(),t.filename);if(ae.existsSync(n))return n;ae.mkdirSync(Ve(),{recursive:!0});let r=n+".partial";try{ae.unlinkSync(r)}catch{}let o=[];for(let s of t.urls)try{return await So(s,r,n,t.sizeBytes,e)}catch(l){o.push(` ${s}: ${l.message}`);try{ae.unlinkSync(r)}catch{}}throw new Error(`Failed to download ${t.label} from any source:
|
|
633
611
|
${o.join(`
|
|
634
|
-
`)}`)}async function
|
|
612
|
+
`)}`)}async function So(t,e,n,r,o){let s=await fetch(t,{redirect:"follow",headers:{"User-Agent":ko}});if(!s.ok||!s.body)throw new Error(`HTTP ${s.status} ${s.statusText}`);let l=Number(s.headers.get("content-length")??r),a=ae.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,l,t))};try{for await(let m of s.body)a.write(m),d+=m.byteLength,u()}catch(m){throw a.destroy(),m}return await new Promise((m,w)=>{a.end(S=>S?w(S):m())}),ae.renameSync(e,n),u(!0),n}import*as Le from"node:fs";import*as Ue from"node:path";var Xe=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=Ue.resolve(e.outputDir,n),Le.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:report":{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}
|
|
635
613
|
|
|
636
614
|
${r?`**Task:** ${r}
|
|
637
615
|
|
|
638
616
|
`:""}---
|
|
639
617
|
|
|
640
|
-
`;
|
|
641
|
-
`,"utf8")}finish(){if(this.currentDir&&this.lastAnswer&&this.query){let e=this.startedAt?Date.now()-this.startedAt:0,r=[...this.agentToOrdinal.values()].sort((
|
|
642
|
-
`),o=this.synthStats?` \xB7 ${this.synthStats.tokens} synth tokens \xB7 ppl ${this.synthStats.ppl.toFixed(2)}`:"",s=`> ${new Date().toISOString()} \xB7 ${this.mode}${o} \xB7 ${(e/1e3).toFixed(1)}s`,
|
|
618
|
+
`;Le.writeFileSync(Ue.join(this.currentDir,`annexure-${e}.md`),o+n.trimEnd()+`
|
|
619
|
+
`,"utf8")}finish(){if(this.currentDir&&this.lastAnswer&&this.query){let e=this.startedAt?Date.now()-this.startedAt:0,r=[...this.agentToOrdinal.values()].sort((d,c)=>d-c).map(d=>{let c=this.taskByOrdinal.get(d);return`- [Annexure ${d}](./annexure-${d}.md)${c?` \u2014 ${c}`:""}`}).join(`
|
|
620
|
+
`),o=this.synthStats?` \xB7 ${this.synthStats.tokens} synth tokens \xB7 ppl ${this.synthStats.ppl.toFixed(2)}`:"",s=`> ${new Date().toISOString()} \xB7 ${this.mode}${o} \xB7 ${(e/1e3).toFixed(1)}s`,l=r?`
|
|
643
621
|
---
|
|
644
622
|
|
|
645
623
|
## Annexures
|
|
@@ -650,15 +628,15 @@ ${r}
|
|
|
650
628
|
${s}
|
|
651
629
|
|
|
652
630
|
${this.lastAnswer.trim()}
|
|
653
|
-
${
|
|
654
|
-
`),process.exit(1));var
|
|
655
|
-
`),process.exit(1));var
|
|
656
|
-
`),
|
|
657
|
-
`)
|
|
658
|
-
`),process.exit(2));let
|
|
659
|
-
`),process.exit(2)),
|
|
660
|
-
`),
|
|
661
|
-
|
|
662
|
-
`)
|
|
663
|
-
${
|
|
631
|
+
${l}`;Le.writeFileSync(Ue.join(this.currentDir,"report.md"),a,"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 Us=pe.join(process.cwd(),"harness.json"),{values:$,positionals:Fs}=vs({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=$["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 He=Fs[0]||void 0,rn=$.jsonl,Or=$.verbose,Ye=$["output-dir"],ue=$.query,de=$.config??Us,je=$["n-ctx"];je!==void 0&&!/^\d+$/.test(je)&&(process.stderr.write(`Invalid --n-ctx: ${je}. Expected a positive integer.
|
|
633
|
+
`),process.exit(1));var Br=je!==void 0?parseInt(je,10):void 0,on=Ce(de,{modelPath:He,reranker:$.reranker,corpusPath:$.corpus,reasoningMode:fe,nCtx:Br,outputDir:Ye}),P=on.config,xe=on.origin,$s=$["findings-budget"]?parseInt($["findings-budget"],10):void 0,en=Ne(P.model.path,"llm"),tn=Ne(P.model.reranker,"reranker"),Ir=en.path,_r=tn.path,Ws=P.model.nCtx??32768;rn&&an(!0);Or&&ln(!0);var zs=!Or&&!rn;if(zs)try{z.closeSync(2),z.openSync(process.platform==="win32"?"\\\\.\\NUL":"/dev/null","w")}catch{}var Hs=10,nn=new Map;function*Mr(t,e){let n=nn.get(t);if(n)return n;let{cwd:r,pattern:o}=Ns(t),s=o??"**/*.{md,mdx}",l=pe.join(r,".gitignore"),a=z.existsSync(l)?Ls().add(z.readFileSync(l,"utf8")):null,d=z.globSync(s,{cwd:r}),c=(a?d.filter(S=>!a.ignores(S)):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 S=0;S<c.length;S++){let q=c[S];e.send({type:"weights:label",label:`Indexing: ${q} (${S+1}/${c.length})`}),yield*Be(()=>new Promise(E=>{setImmediate(()=>{try{u.push({name:q,content:z.readFileSync(pe.join(r,q),"utf8")})}catch{}E()})}))}e.send({type:"weights:label",label:"Chunking corpus\u2026"}),yield*Be(()=>new Promise(S=>setImmediate(S)));let m=qs(u),w={resources:u,chunks:m};return nn.set(t,w),w}function Oe(t){let e=[];if(t.sources.corpusPath){let n=nn.get(t.sources.corpusPath);n&&e.push(new Ds(n.resources,n.chunks,{grep:{maxResults:50,lineMaxChars:200},readFile:{defaultMaxLines:100}}))}return t.sources.tavilyKey&&e.push(new Bs(new Ms(t.sources.tavilyKey),{topN:5,fetch:{maxChars:3e3,topK:5,timeout:1e4,tokenBudget:1200}})),e}function Jt(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 Zt=t=>t instanceof Error?t.message:String(t),Ys=t=>t instanceof Error?t.stack??t.message:String(t);Rs(function*(){let t=pe.basename(Ir).replace(/-Q\w+\.gguf$/,""),e=pe.basename(_r).replace(/-q\w+\.gguf$/i,""),n=yt&&!rn;n||(Ke(),Ke(`${bt.bold} Deep Research${bt.reset}`),Ke());let r=pn(),o=As(),s=[en,tn].filter(i=>i.entry!==null&&!z.existsSync(i.path)).map(i=>({id:i.entry.id,label:i.entry.label,sizeBytes:i.entry.sizeBytes})),l=null;if(n){let i=yield*Be(()=>Promise.resolve().then(()=>(Er(),Pr))),p=[{type:"config:loaded",config:P,origin:xe,path:on.path}];s.length>0&&p.push({type:"download:plan",entries:s}),l=i.render(r,h=>o.send(h),p),yield*Xt(()=>{l?.unmount()})}else r.subscribe(i=>{cn(i.type,i)});function*a(i){if(z.existsSync(i.path))return i.path;if(!i.entry)throw new Error(`Model not found: ${i.path}. Pass --model <path> or use /model <path> to set a local .gguf file.`);let p=i.entry;return r.send({type:"download:start",id:p.id,label:p.label,sizeBytes:p.sizeBytes}),yield*Be(()=>In(p,{onProgress:(h,x,O)=>{r.send({type:"download:progress",id:p.id,got:h,total:x,url:O})}})),r.send({type:"download:complete",id:p.id}),i.path}function d(i){let p=i.filter(h=>h.entry!==null&&!z.existsSync(h.path)).map(h=>({id:h.entry.id,label:h.entry.label,sizeBytes:h.entry.sizeBytes}));p.length>0&&r.send({type:"download:plan",entries:p})}function*c(){for(let i of yield*Se(o)){if(i.type==="quit"||i.type==="set_model_path"||i.type==="set_reranker_path")return yield*Se.next(),i;yield*Se.next()}return{type:"quit"}}let u=en,m=Ir,w=t,S=tn,q=_r,E=e,y=null,g=null,I=!0;for(;y===null||g===null;){let i="llm";try{I||d([u,S]),I=!1,i="llm",yield*a(u),i="reranker",yield*a(S),i="llm",r.send({type:"weights:start",label:`Loading ${w}\u2026`}),y=yield*Be(()=>Es({modelPath:m,nCtx:Ws,nSeqMax:64,typeK:"q4_0",typeV:"q4_0"})),i="reranker",r.send({type:"weights:label",label:`Loading ${E}\u2026`}),g=yield*Be(()=>Os(q,{nSeqMax:8,nCtx:16384}))}catch(p){if(y){try{y.dispose?.()}catch{}y=null}g=null,r.send({type:"boot:error",kind:i,message:Zt(p)});let h=yield*c();h.type==="quit"&&(l?.unmount(),process.exit(0)),h.type==="set_model_path"?(ve({model:{path:h.path}},de),u=Ne(h.path,"llm"),m=u.path,w=u.entry?.label??pe.basename(m)):(ve({model:{reranker:h.path}},de),S=Ne(h.path,"reranker"),q=S.path,E=S.entry?.label??pe.basename(q));let x=Ce(de,{modelPath:h.type==="set_model_path"?h.path:He,reranker:h.type==="set_reranker_path"?h.path:$.reranker,corpusPath:$.corpus,reasoningMode:fe,outputDir:Ye,nCtx:Br});P=x.config,xe=x.origin}}yield*Xt(()=>{g.dispose()}),r.send({type:"weights:done"});let W=ye(P.sources.outputDir||process.cwd());z.mkdirSync(W,{recursive:!0});let R=new Date().toISOString().replace(/[:.]/g,"-").replace("Z",""),ge=pe.join(W,`trace-${R}.jsonl`),Z=z.openSync(ge,"w"),re=new _s(Z);yield*Xt(()=>{re.flush();try{z.closeSync(Z)}catch{}});let Y=new Xe,{session:C,events:b}=yield*Is(y,{traceWriter:re});if(yield*Ps(function*(){for(let i of yield*Se(b))Y.handle(i),r.send(i),yield*Se.next()}),P.sources.corpusPath)try{let i=yield*Mr(P.sources.corpusPath,r);r.send({type:"corpus:indexed",corpusPath:P.sources.corpusPath,fileCount:i.resources.length,chunkCount:i.chunks.length})}catch(i){r.send({type:"ui:error",message:`Corpus disabled: ${i.message}. Use /scan to fix.`})}r.send({type:"ui:composer"});let Q={maxTurns:Hs,findingsMaxChars:$s,reasoningMode:P.defaults.reasoningMode};function oe(i,p){let h=P.sources.outputDir??process.cwd();Y.start({outputDir:h,query:i,mode:p})}if(!n){ue||(process.stderr.write(`Non-TTY mode requires --query.
|
|
635
|
+
`),process.exit(2));let i=Oe(P);i.length===0&&(process.stderr.write(`No source configured. Set TAVILY_API_KEY, pass --corpus <dir>, or store one in harness.json.
|
|
636
|
+
`),process.exit(2));let p=performance.now(),h=yield*Ae(ue,C,i,g,{...Q,wallStartMs:p,onStart:()=>oe(ue,P.defaults.reasoningMode)});h.type==="clarify"&&(process.stderr.write(`Planner asked clarifying questions; non-TTY mode can't answer. Aborting.
|
|
637
|
+
`),process.exit(2)),h.type==="research_plan"&&(oe(ue,P.defaults.reasoningMode),yield*qe(ue,h.plan,C,i,g,{...Q,wallStartMs:p}));return}let f=null;if(ue){let i=P.defaults.reasoningMode,p=performance.now(),h=Oe(P),x=yield*Ae(ue,C,h,g,{...Q,reasoningMode:i,wallStartMs:p,onStart:()=>oe(ue,i)});x.type==="research_plan"?(f={plan:x.plan,query:ue,mode:i,wallStartMs:p},yield*b.send({type:"ui:plan_review"})):x.type==="clarify"?f={plan:x.plan,query:ue,mode:i,wallStartMs:p}:yield*b.send({type:"ui:composer"})}for(let i of yield*Se(o))try{if(i.type==="quit")break;if(i.type==="set_tavily_key"){P={...P,sources:{...P.sources,tavilyKey:i.key}};let p=ve({sources:{tavilyKey:i.key}},de),h=Ce(de,{modelPath:He,reranker:$.reranker,corpusPath:$.corpus,reasoningMode:fe,outputDir:Ye});P=h.config,xe=h.origin,yield*b.send({type:"config:updated",config:P,origin:xe,savedTo:p.path,gitignored:p.gitignored,skipped:p.skipped})}else if(i.type==="set_output_dir"){let p=i.path?ye(i.path):"",h=ve({sources:{outputDir:p}},de),x=Ce(de,{modelPath:He,reranker:$.reranker,corpusPath:$.corpus,reasoningMode:fe,outputDir:Ye});P=x.config,xe=x.origin,yield*b.send({type:"config:updated",config:P,origin:xe,savedTo:h.path,gitignored:h.gitignored,skipped:h.skipped})}else if(i.type==="set_corpus_path"){let p=i.path?ye(i.path):"";if(p){r.send({type:"weights:start",label:"Indexing corpus\u2026"});let O;try{O=yield*Mr(p,r)}catch(T){r.send({type:"weights:done"}),yield*b.send({type:"ui:error",message:`Cannot use ${p}: ${T.message}`});continue}r.send({type:"corpus:indexed",corpusPath:p,fileCount:O.resources.length,chunkCount:O.chunks.length}),r.send({type:"weights:done"})}let h=ve({sources:{corpusPath:p}},de),x=Ce(de,{modelPath:He,reranker:$.reranker,corpusPath:$.corpus,reasoningMode:fe,outputDir:Ye});P=x.config,xe=x.origin,yield*b.send({type:"config:updated",config:P,origin:xe,savedTo:h.path,gitignored:h.gitignored,skipped:h.skipped}),p&&(yield*b.send({type:"ui:composer"}))}else if(i.type==="submit_query"){let p=Oe(P);if(p.length===0){yield*b.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."});continue}let h=performance.now();if(i.skipPlanner){let O=Ct(i.query);yield*b.send({type:"plan:start",query:i.query,mode:i.mode}),yield*b.send({type:"query",query:i.query,warm:!!C.trunk}),yield*b.send({type:"plan",intent:O.intent,tasks:O.tasks,clarifyQuestions:O.clarifyQuestions,tokenCount:O.tokenCount,timeMs:O.timeMs}),oe(i.query,i.mode),yield*qe(i.query,O,C,p,g,{...Q,reasoningMode:i.mode,wallStartMs:h}),yield*b.send({type:"ui:composer"});continue}let x=yield*Ae(i.query,C,p,g,{...Q,reasoningMode:i.mode,context:Jt(p),wallStartMs:h,onStart:()=>oe(i.query,i.mode)});x.type==="research_plan"?(f={plan:x.plan,query:i.query,mode:i.mode,wallStartMs:h},yield*b.send({type:"ui:plan_review"})):x.type==="clarify"?f={plan:x.plan,query:i.query,mode:i.mode,wallStartMs:h}:yield*b.send({type:"ui:composer"})}else if(i.type==="submit_clarification"&&f){let{query:p,plan:h,mode:x,wallStartMs:O}=f,T=Oe(P),L=["Prior clarification exchange:",...h.clarifyQuestions.map((ft,Dr)=>`(${Dr+1}) ${ft}`),"",`User response: ${i.answer}`,"","Use this exchange to proceed with research if possible."].join(`
|
|
638
|
+
`),V=yield*Ae(p,C,T,g,{...Q,reasoningMode:x,context:[Jt(T),L].filter(Boolean).join(`
|
|
639
|
+
|
|
640
|
+
`),wallStartMs:O,onStart:()=>oe(p,x)});V.type==="research_plan"?(f={plan:V.plan,query:p,mode:x,wallStartMs:O},yield*b.send({type:"ui:plan_review"})):V.type==="clarify"?f={plan:V.plan,query:p,mode:x,wallStartMs:O}:(f=null,yield*b.send({type:"ui:composer"}))}else if(i.type==="change_mode"&&f){let p=Oe(P),h=yield*Ae(f.query,C,p,g,{...Q,reasoningMode:i.mode,context:Jt(p),wallStartMs:f.wallStartMs,onStart:()=>oe(f.query,i.mode)});h.type==="research_plan"?(f={...f,plan:h.plan,mode:i.mode},yield*b.send({type:"ui:plan_review"})):h.type==="clarify"?f={...f,plan:h.plan,mode:i.mode}:(f=null,yield*b.send({type:"ui:composer"}))}else if(i.type==="accept_plan"&&f){if(f.plan.intent==="clarify"){f=null,yield*b.send({type:"ui:composer"});continue}let p=Oe(P);if(p.length===0){yield*b.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."}),f=null;continue}oe(f.query,f.mode),yield*qe(f.query,f.plan,C,p,g,{...Q,reasoningMode:f.mode,wallStartMs:f.wallStartMs}),f=null,yield*b.send({type:"ui:composer"})}else if(i.type==="cancel_plan")f=null,yield*b.send({type:"ui:composer"});else if(i.type==="edit_plan")f=null,yield*b.send({type:"ui:composer",prefill:i.query});else if(i.type==="update_task_description"&&f)f.plan.tasks=f.plan.tasks.map((p,h)=>h===i.index?{...p,description:i.description}:p),yield*b.send({type:"plan:task_updated",index:i.index,description:i.description});else if(i.type==="add_task"&&f){let p=Math.max(0,Math.min(f.plan.tasks.length,i.afterIndex+1));f.plan.tasks=[...f.plan.tasks.slice(0,p),{description:""},...f.plan.tasks.slice(p)],yield*b.send({type:"plan:task_added",afterIndex:i.afterIndex})}else if(i.type==="delete_task"&&f)f.plan.tasks.length>1&&(f.plan.tasks=f.plan.tasks.filter((p,h)=>h!==i.index),yield*b.send({type:"plan:task_deleted",index:i.index}));else if(i.type==="move_task"&&f){let p=f.plan.tasks.length;if(i.from!==i.to&&i.from>=0&&i.from<p&&i.to>=0&&i.to<p){let h=[...f.plan.tasks],[x]=h.splice(i.from,1);h.splice(i.to,0,x),f.plan.tasks=h,yield*b.send({type:"plan:task_moved",from:i.from,to:i.to})}}}catch(p){f=null,yield*b.send({type:"ui:error",message:Zt(p)})}finally{yield*Se.next()}}).catch(t=>{process.stderr.write(`Error: ${Zt(t)}
|
|
641
|
+
${Ys(t)}
|
|
664
642
|
`),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "reasoning.run",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Local deep-research agent composer — runs on your machine, zero-config after the first query. Built
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Local deep-research agent composer — runs on your machine, zero-config after the first query. Built with Lloyal HDK.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"reasoning.run": "bin/run.js"
|
|
7
7
|
},
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"prepublishOnly": "npm run build"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
+
"@inkjs/ui": "^2.0.0",
|
|
23
24
|
"@lloyal-labs/lloyal-agents": "^2.0.0",
|
|
24
25
|
"@lloyal-labs/lloyal.node": "^2.1.0",
|
|
25
26
|
"@lloyal-labs/rig": "^2.0.1",
|