reasoning.run 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +69 -21
  2. package/dist/bundle.mjs +45 -67
  3. package/package.json +13 -5
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # reasoning.run
2
2
 
3
- Local deep-research agent composer runs on your machine, zero-config after the first query.
3
+ A private reasoner for your terminal. Direct conversation or grounded multi-agent research, GPU-native and fully local. No API keys, no inference servers.
4
4
 
5
5
  ```
6
6
  npx reasoning.run
@@ -8,13 +8,26 @@ npx reasoning.run
8
8
 
9
9
  Then type a research question.
10
10
 
11
- ## What it does
11
+ <p>
12
+ <img src="assets/demo-readme.gif" alt="reasoning.run: clarifying questions → plan approval → 5 research agents in parallel → synthesized report" width="100%">
13
+ <br>
14
+ <em>Qwen3.5 4B + Qwen3 0.6B reranker · 5 parallel agents · shared 32K context · fully offline on M2 MacBook Pro 16 GB</em>
15
+ </p>
12
16
 
13
- - Downloads a Qwen3.5-4B LLM and Qwen3 reranker on first run (~3 GB, cached in `~/.cache/lloyal/models/`).
14
- - Runs a planner that decomposes your question into research tasks.
15
- - Shows the plan in an Ink-based composer; press Enter to approve or `E` to edit.
16
- - Spawns research agents (parallel for `Fast` mode, chained for `Deep` mode) that query your corpus and/or the web via Tavily.
17
- - Synthesizes findings into a coherent answer, streamed live.
17
+ > 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.
18
+
19
+ **Empirically:** 5 research agents running concurrently in a shared 32K-token context window, Qwen3.5-4B as the LLM, on a MacBook Pro M2 (16 GB unified memory). No GPU server, no API keys, no inference fees. Every token is decoded on the device that asked the question.
20
+
21
+ ## What you get
22
+
23
+ - **Plan, edit, run.** A small planner decomposes your question into research tasks. You see the plan in a TUI editor — navigate with ↑↓, edit a task with ⏎, add/delete/reorder with `A`/`D`/`⇧↑↓`. Press START on a plan you actually agree with. Nothing runs until you say so.
24
+ - **5 agents in one context window.** HDK's [Continuous Context](https://hdk.lloyal.ai/reference/continuous-context-spine) lets agents share GPU KV state, not strings — five research agents fit inside a single 32K-token budget on a 16 GB MacBook. Decoded in-process, no API calls, no inference server.
25
+ - **Retrieval inside the loop.** Each agent searches, fetches, and reranks chunks *during* generation via HDK's [RIG](https://hdk.lloyal.ai/learn/sources) primitives — Tavily for web, local markdown for corpus. Adaptive tool use, multi-hop reasoning.
26
+ - **Warm follow-ups.** Subsequent queries in the same session reuse the trunk's KV. The planner runs instantly; agents fork from a context that already remembers the prior turn.
27
+ - **Hot model swap.** `/model <path>` rebuilds the harness against a new `.gguf` mid-session. Test against different model sizes and quants in seconds, same process.
28
+ - **Bundled output per query.** `report.md` (synth answer) + `annexure-N.md` (each research agent's full report) on disk. Grep, diff, share.
29
+
30
+ First run downloads a Qwen3.5-4B LLM and Qwen3 reranker (~3 GB total, cached in `~/.cache/lloyal/models/`). After that it's all local.
18
31
 
19
32
  ## Configuration
20
33
 
@@ -28,25 +41,33 @@ State lives in `./harness.json` (auto-created, auto-gitignored on first save):
28
41
  "outputDir": "./reasoning-runs" // optional — defaults to cwd
29
42
  },
30
43
  "defaults": {
31
- "reasoningMode": "deep" // or "flat"
44
+ "reasoningMode": "flat" // or "deep"
32
45
  },
33
46
  "model": {
47
+ "path": "/path/to/llm.gguf", // optional — local LLM (else catalog default)
48
+ "reranker": "/path/to/rerank.gguf",// optional — local reranker (else catalog default)
34
49
  "nCtx": 32768 // LLM context window
35
50
  }
36
51
  }
37
52
  ```
38
53
 
39
- ### Settings in the composer
54
+ ### Slash commands
40
55
 
41
- Press `Esc` to open the menu mode:
56
+ Type `/` in the composer to open the command palette. Tab autocompletes; Enter runs.
42
57
 
43
- - `W` set Tavily key (or clear with empty)
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
48
-
49
- Everything persists to `harness.json` the moment you save.
58
+ | Command | Effect |
59
+ |---|---|
60
+ | `/web <key>` | Set Tavily API key. Empty value clears. |
61
+ | `/scan <path>` | Set local file/glob source. Empty value clears. |
62
+ | `/output <dir>` | Set the run-artifact output directory. Empty value resets to cwd. |
63
+ | `/model <path>` | Use a local LLM `.gguf` instead of the catalog default. |
64
+ | `/reranker <path>` | Use a local reranker `.gguf` instead of the catalog default. |
65
+ | `/deep` | Switch to deep (chain) reasoning mode. |
66
+ | `/flat` | Switch to flat (parallel) reasoning mode. |
67
+ | `/help` | Show the command list inline. |
68
+ | `/quit` | Exit. |
69
+
70
+ Settings persist to `harness.json` the moment you submit. `/model` and `/reranker` **hot-swap the live model mid-session**: type `/model ~/qwen3-8b.gguf` and the harness disposes the current `ctx`, downloads (if needed), loads the new weights, and returns you to the composer — same process, same Ink session, no restart. (Same flow recovers from boot-time download failures: type `/model <path>` at the BootStatus prompt to continue with a local file.)
50
71
 
51
72
  ## Run artifacts
52
73
 
@@ -72,6 +93,23 @@ Every query writes a self-contained bundle under `<output-dir>/<ISO-timestamp>/`
72
93
  - `TAVILY_API_KEY` — wins over the stored key; never persists to disk while set.
73
94
  - `LLAMA_CTX_SIZE` — context window fallback.
74
95
 
96
+ ## CLI flags
97
+
98
+ All optional. Anything you can set in `harness.json` you can also set on the command line; CLI > env > file > defaults.
99
+
100
+ | Flag | Effect |
101
+ |---|---|
102
+ | `--query <q>` | Run one query non-interactively, then exit. Implied non-TTY mode. |
103
+ | `--reasoning-mode <flat\|deep>` | Override the default reasoning mode. |
104
+ | `--n-ctx <int>` | LLM context window in tokens. |
105
+ | `--corpus <path>` | Local file/glob source (same as `/scan`). |
106
+ | `--output-dir <dir>` | Where run artifacts are written (same as `/output`). |
107
+ | `--reranker <path>` | Local reranker `.gguf` (same as `/reranker`). |
108
+ | `--findings-budget <int>` | Cap (in chars) on per-agent findings forwarded to synth. Default unbounded. |
109
+ | `--config <path>` | Use a non-default `harness.json`. |
110
+ | `--jsonl` | Stream events as JSONL to stdout (good for piping). |
111
+ | `--verbose` | Verbose logs. |
112
+
75
113
  ## Keyboard shortcuts
76
114
 
77
115
  Standard readline chords (work in every terminal):
@@ -88,11 +126,21 @@ Standard readline chords (work in every terminal):
88
126
 
89
127
  For Cmd+Backspace / Cmd+arrow to work, turn on "Natural Text Editing" in iTerm2, or use Ghostty.
90
128
 
91
- ## Source
129
+ ## How it's built
130
+
131
+ reasoning.run is a working harness on [Lloyal's **Harness Development Kit**](https://hdk.lloyal.ai/) — the same primitives ship agentic AI directly into desktop and mobile apps, no cloud round-trip required. Specifically:
132
+
133
+ - **`useAgent`** — single agents with tools and a terminal report tool. Powers the planner, the bridge, and synth.
134
+ - **`agentPool` + `parallel`/`chain`** — multi-agent orchestration. Drives the research phase: parallel fan-out for `Flat` mode, chained tasks for `Deep` mode.
135
+ - **Playbooks convention** — planner, web_research, corpus_research, and synth agents share a single tool palette amortized at the harness's shared root. Tool schemas decoded once; each agent reads its role from a short suffix. See [Playbooks](https://hdk.lloyal.ai/reference/playbooks).
136
+ - **Continuous Context Spine** — agents share GPU KV state instead of re-tokenizing strings, so 5 concurrent agents fit inside one 32K-token context budget on consumer hardware. Also why subsequent queries in the same session are warm and instant — the prior turn's tokens are still in the trunk's KV.
137
+ - **Retrieval-Interleaved Generation (RIG)** — `WebSource` (Tavily) and `CorpusSource` (local markdown) plug in via the `Source` contract, with reranker-scored chunks fed inline during generation.
138
+ - **Bring your own data via the `Source` contract.** Tavily and local markdown are bundled; the contract is small enough to wrap a vector DB, REST API, JIRA, or any other domain knowledge surface. See [Custom Sources](https://hdk.lloyal.ai/guides/custom-source).
139
+ - **`@lloyal-labs/lloyal.node`** — llama.cpp Node binding for in-process inference.
140
+
141
+ 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
142
 
93
- - Built on [`@lloyal-labs/*`](https://github.com/lloyal-ai/lloyal-sdk) for the agent runtime, session/branch primitives, and RIG tools.
94
- - Local inference via `@lloyal-labs/lloyal.node` (llama.cpp Node binding).
95
- - UI via Ink (React for terminals).
143
+ UI is [Ink](https://github.com/vadimdemedes/ink) (React for terminals).
96
144
 
97
145
  ## License
98
146
 
package/dist/bundle.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- var ao=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var lo=(t,e)=>{for(var n in e)ao(t,n,{get:e[n],enumerable:!0})};var ut,Nt=E(()=>{"use strict";ut={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},verify:{active:!1,count:0,done:!1,timeMs:null},evalState: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 Lt(t){let e=process.env.HOME;return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Ko(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 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 sr(t){let e=t.indexOf(`
5
- `);return e<=0?"":t.slice(e+1).trimStart()}var os,zt,Ht,Yt,jt,as,ls,yt,Kt=E(()=>{"use strict";Wt();os=["thinking","content","tool"];zt=Oe(function({item:e,color:n}){let r=e.live?e.body.includes(`
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"),j.renameSync(l,r);let u=po(r);return{path:r,gitignored:u,skipped:s}}function po(t){try{let e=ho(z.dirname(t));if(!e)return!1;let n=z.join(e,".gitignore"),r=z.relative(e,t).replace(/\\/g,"/"),o=j.existsSync(n)?j.readFileSync(n,"utf8"):"",s=z.basename(t);if(new RegExp(`(^|\\n)\\s*(${wn(r)}|${wn(s)})\\s*(\\n|$)`).test(o))return!1;let a=o.length===0||o.endsWith(`
2
+ var Wr=Object.defineProperty;var q=(t,e)=>()=>(t&&(e=t(t=0)),e);var zr=(t,e)=>{for(var n in e)Wr(t,n,{get:e[n],enumerable:!0})};var rt,Mt=q(()=>{"use strict";rt={query:"",warm:!1,uiPhase:"boot",phase:"idle",mode:null,plan:null,agents:new Map,researchAgentIds:[],sourceCount:0,synth:{open:!1,buffer:"",done:!1,stats:null},answer:null,pressure:null,timings:[],startedAt:Date.now(),pipelineElapsedMs:0,pipelineResumedAt:null,nextTimelineId:0,nextLabelIdx:0,pendingTaskIndex:null,pendingTaskDescription:null,researchSpawnCount:0,config:null,configOrigin:null,toast:null,composerPrefill:"",clarifyContext:null,downloads:[],loadingLabel:null,nextToastId:0,scrollback:[],corpusStatus:null,bootError:null}});function _t(t){let e=process.env.HOME;return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Io(t){let e=t.replace(/^\s*\n/,"").replace(/\*\*/g,"").replace(/^#+\s*/,"").trim();if(!e)return"Thinking\u2026";let n=e.split(`
3
+ `)[0].trim();return n.length>72?n.slice(0,72).trimEnd()+"\u2026":n}function ot(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Mo(t,e){let n;try{n=JSON.parse(e)}catch{n={}}let r=typeof n.query=="string"?n.query:typeof n.pattern=="string"?n.pattern:typeof n.url=="string"?n.url:typeof n.filename=="string"?n.filename:"";return r?`"${r.length>48?r.slice(0,48)+"\u2026":r}"`:""}function _o(t,e){try{let r=JSON.parse(e);if(t==="web_search"&&Array.isArray(r)){let o=r,s=Array.from(new Set(o.map(a=>a.url?ot(a.url):"").filter(Boolean))).slice(0,3);return{summary:`${o.length} results`,hosts:s,resultCount:o.length,preview:o[0]?.title??null}}if(t==="search"&&Array.isArray(r)){let o=r;return{summary:`${o.length} results`,hosts:[],resultCount:o.length,preview:o[0]?.heading??null}}if(t==="grep"&&typeof r=="object"&&r!==null){let o=r;return{summary:`${o.totalMatches??0} matches`,hosts:[],resultCount:o.totalMatches??null,preview:null}}if(t==="fetch_page"&&typeof r=="object"&&r!==null){let o=r;if(o.error)return{summary:o.error,hosts:[],resultCount:null,preview:null};let s=o.url?[ot(o.url)]:[];return{summary:`${e.length}b`,hosts:s,resultCount:null,preview:o.title??null}}if(t==="web_fetch"&&typeof r=="object"&&r!==null){let o=r,s=o.url?[ot(o.url)]:[];return{summary:`${e.length}b`,hosts:s,resultCount:null,preview:o.title??null}}}catch{}let n=Array.from(e.matchAll(/https?:\/\/[^\s\])>"]+/g)).map(r=>r[0]);if(n.length>0){let r=Array.from(new Set(n.map(ot))).slice(0,3);return{summary:`${n.length} links`,hosts:r,resultCount:n.length,preview:null}}return{summary:`${e.length}b`,hosts:[],resultCount:null,preview:null}}function se(t,e,n){let r=t.agents.get(e);if(!r)return t;let o=new Map(t.agents);return o.set(e,n(r)),{...t,agents:o}}function Dn(t,e,n={}){if(t.agents.has(e))return t;let r={id:e,label:`A${t.nextLabelIdx}`,phase:"idle",tokenCount:0,toolCallCount:0,taskIndex:null,taskDescription:null,dependencyHint:null,currentThinkId:null,pendingToolCallId:null,contentBuffer:"",timeline:[],...n},o=new Map(t.agents);return o.set(e,r),{...t,agents:o,nextLabelIdx:t.nextLabelIdx+1}}function it(t,e){return{...t,timeline:[...t.timeline,e]}}function Nn(t,e,n){return{...t,timeline:t.timeline.map(r=>r.id===e?n(r):r)}}function qn(t,e){let n=t.nextTimelineId;return{...se(t,e,o=>it({...o,currentThinkId:n,phase:"thinking"},{kind:"think",id:n,title:"Thinking\u2026",body:"",live:!0,openedAt:Date.now(),closedAt:null})),nextTimelineId:t.nextTimelineId+1}}function st(t,e,n){let r=t.agents.get(e);if(!r||r.currentThinkId===null)return t;let o=r.currentThinkId,s=Io(n);return se(t,e,a=>Nn({...a,currentThinkId:null,phase:"content"},o,i=>i.kind==="think"?{...i,body:n,title:s,live:!1,closedAt:Date.now()}:i))}function Ot(t,e){switch(e.type){case"query":return{...rt,config:t.config,configOrigin:t.configOrigin,uiPhase:t.uiPhase,mode:t.mode,nextToastId:t.nextToastId,toast:t.toast,scrollback:t.scrollback,query:e.query,warm:e.warm,phase:"plan",startedAt:Date.now()};case"plan":return{...t,uiPhase:e.intent==="clarify"?"clarifying":t.uiPhase,phase:e.intent==="research"?"plan":"done",plan:{intent:e.intent,tasks:e.tasks,clarifyQuestions:e.clarifyQuestions,tokenCount:e.tokenCount,timeMs:e.timeMs},clarifyContext:e.intent==="clarify"?{originalQuery:t.query,questions:e.clarifyQuestions}:null};case"plan:task_updated":{if(!t.plan||e.index<0||e.index>=t.plan.tasks.length)return t;let n=t.plan.tasks.map((r,o)=>o===e.index?{...r,description:e.description}:r);return{...t,plan:{...t.plan,tasks:n}}}case"plan:task_added":{if(!t.plan)return t;let n=Math.max(0,Math.min(t.plan.tasks.length,e.afterIndex+1)),r=[...t.plan.tasks.slice(0,n),{description:""},...t.plan.tasks.slice(n)];return{...t,plan:{...t.plan,tasks:r}}}case"plan:task_deleted":{if(!t.plan||t.plan.tasks.length<=1||e.index<0||e.index>=t.plan.tasks.length)return t;let n=t.plan.tasks.filter((r,o)=>o!==e.index);return{...t,plan:{...t.plan,tasks:n}}}case"plan:task_moved":{if(!t.plan)return t;let n=t.plan.tasks.length;if(e.from===e.to||e.from<0||e.from>=n||e.to<0||e.to>=n)return t;let r=[...t.plan.tasks],[o]=r.splice(e.from,1);return r.splice(e.to,0,o),{...t,plan:{...t.plan,tasks:r}}}case"research:start":return{...t,uiPhase:"research",phase:"research",mode:e.mode==="flat"?"flat":"deep",pipelineResumedAt:Date.now()};case"research:done":return{...t,phase:"synth"};case"fanout:tasks":return t;case"spine:task":return{...t,pendingTaskIndex:e.taskIndex,pendingTaskDescription:e.description};case"spine:source":case"spine:task:done":return t;case"synthesize:start":return{...t,phase:"synth",synth:{open:!0,buffer:"",done:!1,stats:null}};case"synthesize:done":{let n=t.synth.buffer.trim(),r=n?[...t.scrollback,{key:`synth-${t.scrollback.length}-${Date.now()}`,kind:"synth",body:n}]:t.scrollback;return{...t,scrollback:r,synth:{...t.synth,open:!1,done:!0,stats:{tokens:e.tokenCount,toolCalls:e.toolCallCount,ppl:e.ppl,timeMs:e.timeMs}}}}case"answer":return{...t,answer:e.text};case"stats":return{...t,timings:e.timings,pressure:{pct:e.ctxPct,cellsUsed:e.ctxPos,nCtx:e.ctxTotal}};case"complete":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,phase:"done",uiPhase:"done",pipelineElapsedMs:n,pipelineResumedAt:null}}case"config:loaded":return{...t,config:e.config,configOrigin:e.origin};case"config:updated":{let n=t.nextToastId+1,r=e.skipped.length>0?`saved \u2192 ${_t(e.savedTo)} (skipped: ${e.skipped.join(", ")} \u2014 env active)`:e.gitignored?`saved \u2192 ${_t(e.savedTo)} (added to .gitignore)`:`saved \u2192 ${_t(e.savedTo)}`;return{...t,config:e.config,configOrigin:e.origin,toast:{id:n,message:r,tone:e.skipped.length>0?"warn":"success"},nextToastId:n}}case"plan:start":{let r=t.uiPhase==="composer"||t.uiPhase==="done"||t.uiPhase==="boot"?{pipelineElapsedMs:0,startedAt:Date.now()}:{};return{...t,...r,uiPhase:"planning",phase:"plan",plan:null,query:e.query,mode:e.mode==="flat"?"flat":"deep",pipelineResumedAt:Date.now()}}case"ui:composer":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,uiPhase:"composer",composerPrefill:e.prefill??"",clarifyContext:null,pipelineElapsedMs:n,pipelineResumedAt:null}}case"ui:plan_review":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,uiPhase:"plan_review",pipelineElapsedMs:n,pipelineResumedAt:null}}case"ui:error":{let n=t.nextToastId+1;return{...t,uiPhase:"composer",toast:{id:n,message:e.message,tone:"error"},nextToastId:n}}case"download:plan":return{...t,uiPhase:"downloading",downloads:e.entries.map(n=>({id:n.id,label:n.label,got:0,total:n.sizeBytes,done:!1,started:!1}))};case"download:start":return{...t,uiPhase:"downloading",downloads:t.downloads.map(n=>n.id===e.id?{...n,started:!0}:n)};case"download:progress":return{...t,downloads:t.downloads.map(n=>n.id===e.id?{...n,started:!0,got:e.got,total:e.total,url:e.url??n.url}:n)};case"download:complete":return{...t,downloads:t.downloads.map(n=>n.id===e.id?{...n,got:n.total||n.got,done:!0}:n)};case"weights:start":return{...t,uiPhase:"loading",loadingLabel:e.label};case"weights:label":return{...t,loadingLabel:e.label};case"weights:done":return{...t,loadingLabel:null};case"corpus:indexed":return{...t,corpusStatus:{fileCount:e.fileCount,chunkCount:e.chunkCount}};case"boot:error":return{...t,uiPhase:"boot_error",bootError:{kind:e.kind,message:e.message}};case"agent:spawn":{if(t.phase!=="research")return Dn(t,e.agentId,{phase:"idle",taskIndex:null});let n,r,o=t.pendingTaskIndex,s=t.pendingTaskDescription;t.mode==="deep"?(n=o??t.researchSpawnCount,r=s??t.plan?.tasks[n]?.description??null,o=null,s=null):(n=t.researchSpawnCount,r=t.plan?.tasks[n]?.description??null);let a=t.mode==="deep"&&n>0?`builds on Task ${n}`:null,i=Dn(t,e.agentId,{phase:"thinking",taskIndex:n,taskDescription:r,dependencyHint:a});return i={...i,researchAgentIds:[...i.researchAgentIds,e.agentId],researchSpawnCount:t.researchSpawnCount+1,pendingTaskIndex:o,pendingTaskDescription:s},qn(i,e.agentId)}case"agent:produce":{if(t.phase==="synth"&&t.synth.open)return{...t,synth:{...t.synth,buffer:t.synth.buffer+e.text}};if(t.phase!=="research")return t;let n=t.agents.get(e.agentId);if(!n||n.taskIndex===null)return t;let r=t,o=n;if(o.phase==="content")return se(r,o.id,w=>({...w,tokenCount:e.tokenCount,contentBuffer:w.contentBuffer+e.text}));if(o.phase!=="thinking"||o.currentThinkId===null)if(o.phase==="tool"||o.phase==="idle")r=qn(r,o.id),o=r.agents.get(o.id);else return se(r,o.id,w=>({...w,tokenCount:e.tokenCount}));let s=o.currentThinkId,a=o.timeline.find(w=>w.id===s);if(!a||a.kind!=="think")return r;let i=a.body+e.text,d=i.indexOf(Bn);if(d===-1)return se(r,o.id,w=>Nn({...w,tokenCount:e.tokenCount},s,v=>v.kind==="think"?{...v,body:i}:v));let c=i.slice(0,d),u=i.slice(d+Bn.length),m=st(r,o.id,c);return se(m,o.id,w=>({...w,tokenCount:e.tokenCount,contentBuffer:u}))}case"agent:tool_call":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let a=n.timeline.find(d=>d.id===n.currentThinkId),i=a&&a.kind==="think"?a.body:"";r=st(r,e.agentId,i)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,a=>({...a,phase:"tool",toolCallCount:a.toolCallCount+1}));let o=r.nextTimelineId;return{...se(r,e.agentId,a=>it({...a,phase:"tool",toolCallCount:a.toolCallCount+1,pendingToolCallId:o,contentBuffer:""},{kind:"tool_call",id:o,tool:e.tool,argsSummary:Mo(e.tool,e.args)})),nextTimelineId:r.nextTimelineId+1}}case"agent:tool_result":{let n=t.agents.get(e.agentId);if(!n)return t;if(n.taskIndex==null)return se(t,e.agentId,i=>({...i,phase:"idle"}));let r=_o(e.tool,e.result),o=t.nextTimelineId,s=Array.from(new Set(r.hosts));return{...se(t,e.agentId,i=>it({...i,phase:"idle",pendingToolCallId:null},{kind:"tool_result",id:o,tool:e.tool,callId:n.pendingToolCallId,byteLength:e.result.length,preview:r.preview,hosts:s,resultCount:r.resultCount})),nextTimelineId:t.nextTimelineId+1,sourceCount:t.sourceCount+s.length}}case"agent:tool_progress":return t;case"agent:report":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let u=n.timeline.find(w=>w.id===n.currentThinkId),m=u&&u.kind==="think"?u.body:"";r=st(r,e.agentId,m)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,u=>({...u,phase:"done",contentBuffer:""}));let o=r.nextTimelineId,s=se(r,e.agentId,u=>it({...u,phase:"done",contentBuffer:""},{kind:"report",id:o,body:e.result,tokenCount:u.tokenCount})),a=s.agents.get(e.agentId),i=s.researchAgentIds.includes(e.agentId),d=i&&a?[...s.scrollback,{key:`agent-${e.agentId}-${s.scrollback.length}`,kind:"agent",agent:a}]:s.scrollback,c=i?s.researchAgentIds.filter(u=>u!==e.agentId):s.researchAgentIds;return{...s,nextTimelineId:r.nextTimelineId+1,scrollback:d,researchAgentIds:c}}case"agent:done":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let o=n.timeline.find(a=>a.id===n.currentThinkId),s=o&&o.kind==="think"?o.body:"";r=st(r,e.agentId,s)}return se(r,e.agentId,o=>({...o,phase:"idle"}))}case"agent:tick":return{...t,pressure:{pct:e.nCtx>0?Math.round(100*e.cellsUsed/e.nCtx):0,cellsUsed:e.cellsUsed,nCtx:e.nCtx}};default:return t}}var Bn,Ln=q(()=>{"use strict";Mt();Bn="</think>"});import{useEffect as Oo,useReducer as Bo}from"react";function Fn(t,e=[]){let[n,r]=Bo(Ot,e,o=>o.reduce(Ot,rt));return Oo(()=>t.subscribe(r),[t]),n}var Un=q(()=>{"use strict";Mt();Ln()});import{createContext as Do,useContext as qo}from"react";function at(){return qo(Bt)}var No,Bt,lt=q(()=>{"use strict";No=()=>{},Bt=Do(No)});import{memo as Lo}from"react";import{Box as Fo,Text as $n}from"ink";import{jsx as Wn,jsxs as Uo}from"react/jsx-runtime";var zn,Hn=q(()=>{"use strict";zn=Lo(function({query:e,warm:n}){return e?Uo(Fo,{flexDirection:"column",marginBottom:1,children:[Wn($n,{bold:!0,children:e}),n?Wn($n,{dimColor:!0,children:"follow-up \xB7 warm session"}):null]}):null})});function ct(t){let e=Number.parseInt(t.slice(1),10);return!Number.isFinite(e)||e<0?Dt[0]:Dt[e%Dt.length]}var Dt,qt=q(()=>{"use strict";Dt=["cyan","yellow","green","magenta","red","blue"]});var de,ut=q(()=>{"use strict";de=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});import{memo as _e,useEffect as $o,useState as Wo}from"react";import{Box as W,Text as M}from"ink";import{jsx as R,jsxs as $}from"react/jsx-runtime";function Ho(t){return zo.includes(t.phase)}function Yo(t){let e=t.indexOf(`
4
+ `);if(e<=0)return"Thinking\u2026";let n=t.slice(0,e).trim();return n?n.length>72?n.slice(0,72).trimEnd()+"\u2026":n:"Thinking\u2026"}function Yn(t){let e=t.indexOf(`
5
+ `);return e<=0?"":t.slice(e+1).trimStart()}var zo,Nt,Lt,Ft,Ut,jo,Ko,dt,$t=q(()=>{"use strict";qt();ut();zo=["thinking","content","tool"];Nt=_e(function({item:e,color:n}){let r=e.live?e.body.includes(`
6
+ `)?Yo(e.body):"Thinking\u2026":e.title,o=e.live?Yn(e.body):Yn(e.body).trim();return $(W,{flexDirection:"column",marginBottom:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u2726 "}),R(M,{bold:!0,children:r})]}),o?R(W,{paddingLeft:2,children:$(M,{children:[o,e.live?"\u258E":""]})}):e.live?R(W,{paddingLeft:2,children:R(M,{dimColor:!0,children:"\u258E"})}):null]})});Lt=_e(function({item:e,pending:n=!1}){let[r,o]=Wo(0);return $o(()=>{if(!n)return;let s=setInterval(()=>o(a=>(a+1)%de.length),80);return()=>clearInterval(s)},[n]),$(W,{flexShrink:0,children:[n?$(M,{color:"cyan",children:[de[r]," "]}):R(M,{dimColor:!0,children:"\u203A "}),R(M,{color:"cyan",children:e.tool}),e.argsSummary?$(M,{dimColor:!0,children:[" ",e.argsSummary]}):null]})}),Ft=_e(function({item:e}){let n=e.hosts.length>0?e.hosts.join(" \xB7 "):null;return $(W,{flexDirection:"column",flexShrink:0,children:[$(W,{paddingLeft:2,children:[R(M,{color:"green",children:"\u2713 "}),R(M,{children:e.resultCount??e.byteLength+"b"}),typeof e.resultCount=="number"?R(M,{children:" results"}):null]}),n?R(W,{paddingLeft:4,children:R(M,{dimColor:!0,children:n})}):e.preview?R(W,{paddingLeft:4,children:R(M,{dimColor:!0,children:e.preview.length>60?e.preview.slice(0,60)+"\u2026":e.preview})}):null]})}),Ut=_e(function({item:e,color:n}){let r=e.body.trim();return $(W,{flexDirection:"column",marginTop:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u2713 "}),R(M,{bold:!0,children:"report"}),$(M,{dimColor:!0,children:[" \xB7 ",e.tokenCount," tok"]})]}),r?R(W,{paddingLeft:2,children:R(M,{children:r})}):null]})}),jo=_e(function({buffer:e,color:n}){return $(W,{flexDirection:"column",marginTop:1,flexShrink:0,children:[$(W,{children:[R(M,{color:n,children:"\u25B8 "}),R(M,{dimColor:!0,bold:!0,children:"streaming"})]}),R(W,{paddingLeft:2,children:$(M,{dimColor:!0,children:[e,"\u258E"]})})]})}),Ko=3,dt=_e(function({agent:e,headerPrefix:n,bodyHeight:r,width:o}){let s=ct(e.label),a=Ho(e),i=e.taskDescription??null,d=r+Ko;return $(W,{flexDirection:"column",width:o,height:d,paddingX:1,marginRight:1,flexShrink:0,overflow:"hidden",children:[$(W,{flexShrink:0,children:[n?$(M,{dimColor:!0,children:[n," \xB7 "]}):null,R(M,{color:s,bold:!0,children:e.label}),R(W,{flexGrow:1}),R(M,{color:a?s:"green",children:a?"\u25CF":"\u2713"})]}),i?R(M,{dimColor:!0,children:i}):null,e.dependencyHint?$(M,{dimColor:!0,children:["\u2191 ",e.dependencyHint]}):null,$(W,{flexDirection:"column",flexGrow:1,justifyContent:"flex-end",overflow:"hidden",children:[e.timeline.map(c=>c.kind==="think"?R(Nt,{item:c,color:s},c.id):c.kind==="tool_call"?R(Lt,{item:c,pending:e.pendingToolCallId===c.id},c.id):c.kind==="tool_result"?R(Ft,{item:c},c.id):c.kind==="report"?R(Ut,{item:c,color:s},c.id):null),e.contentBuffer?R(jo,{buffer:e.contentBuffer,color:s}):null]})]})})});import{Box as pt,Text as ht}from"ink";import{jsx as be,jsxs as Wt}from"react/jsx-runtime";function jn({agent:t}){let e=ct(t.label),n=t.taskDescription?t.taskDescription.length>80?t.taskDescription.slice(0,80)+"\u2026":t.taskDescription:null;return Wt(pt,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,marginBottom:1,children:[Wt(pt,{flexShrink:0,children:[be(ht,{color:e,bold:!0,children:t.label}),be(pt,{flexGrow:1}),be(ht,{color:"green",children:"\u2713"})]}),n?be(ht,{dimColor:!0,children:n}):null,t.dependencyHint?Wt(ht,{dimColor:!0,children:["\u2191 ",t.dependencyHint]}):null,be(pt,{flexDirection:"column",children:t.timeline.map(r=>r.kind==="think"?be(Nt,{item:r,color:e},r.id):r.kind==="tool_call"?be(Lt,{item:r},r.id):r.kind==="tool_result"?be(Ft,{item:r},r.id):r.kind==="report"?be(Ut,{item:r,color:e},r.id):null)})]})}var Kn=q(()=>{"use strict";qt();$t()});import{useEffect as Go,useState as Qo}from"react";import{useStdout as Vo}from"ink";function Gn(){let{stdout:t}=Vo(),[e,n]=Qo(()=>[t?.columns??120,t?.rows??40]);return Go(()=>{if(!t)return;let r=()=>{n([t.columns??120,t.rows??40])};return t.on("resize",r),()=>{t.off("resize",r)}},[t]),e}function Qn(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),r=e%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}var zt=q(()=>{"use strict"});import{Box as Ht}from"ink";import{jsx as Oe}from"react/jsx-runtime";function Xn({state:t}){let[e,n]=Gn(),r=t.researchAgentIds.map(a=>t.agents.get(a)).filter(a=>!!a);if(r.length===0)return null;let o=Math.max(Yt,n-Xo);if(t.mode==="flat"){let a=r.length,i=Math.max(Vn*a,e-4),d=Math.max(Vn,Math.floor(i/a)-1);return d*a+a<=e?Oe(Ht,{flexDirection:"row",marginBottom:1,children:r.map(u=>Oe(dt,{agent:u,headerPrefix:null,bodyHeight:o,width:d},u.id))}):Oe(Ht,{flexDirection:"column",marginBottom:1,children:r.map(u=>Oe(dt,{agent:u,headerPrefix:null,bodyHeight:Math.max(Yt,Math.floor(o/a))},u.id))})}let s=Math.max(Yt,Math.floor(o/Math.max(1,r.length)));return Oe(Ht,{flexDirection:"column",marginBottom:1,children:r.map(a=>Oe(dt,{agent:a,headerPrefix:`Task ${(a.taskIndex??0)+1}`,bodyHeight:s},a.id))})}var Xo,Vn,Yt,Jn=q(()=>{"use strict";$t();zt();Xo=18,Vn=26,Yt=10});import{Box as je,Text as ve}from"ink";import{jsx as Re,jsxs as Ke}from"react/jsx-runtime";function Zn({state:t}){let{synth:e}=t;if(!e.open&&!e.done)return null;let n=e.done?Ke(je,{children:[Re(ve,{bold:!0,children:"Synthesis "}),Re(ve,{color:"green",children:"\u2713"}),e.stats?Ke(ve,{dimColor:!0,children:[" ","\xB7 ",e.stats.tokens," tok \xB7 ",e.stats.toolCalls," tools \xB7"," ",Number.isFinite(e.stats.ppl)?`ppl ${e.stats.ppl.toFixed(2)} \xB7 `:"",Jo(e.stats.timeMs)]}):null]}):Ke(je,{children:[Re(ve,{bold:!0,children:"Synthesis"}),Re(ve,{color:"cyan",children:" \u25CF"})]}),r=e.buffer.trim();return Ke(je,{flexDirection:"column",marginBottom:1,children:[n,e.open&&r?Re(je,{paddingLeft:2,marginTop:0,children:Ke(ve,{children:[r,"\u258E"]})}):e.open?Re(je,{paddingLeft:2,children:Re(ve,{dimColor:!0,children:"\u258E"})}):null]})}var Jo,er=q(()=>{"use strict";Jo=t=>`${(t/1e3).toFixed(1)}s`});import{Box as tr,Text as nr}from"ink";import{jsx as jt,jsxs as Zo}from"react/jsx-runtime";function rr({state:t}){return!t.answer||t.synth.done&&t.synth.buffer.trim().length>0?null:Zo(tr,{flexDirection:"column",marginBottom:1,children:[jt(nr,{dimColor:!0,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"}),jt(tr,{marginTop:1,paddingLeft:2,children:jt(nr,{children:t.answer.trim()})})]})}var or=q(()=>{"use strict"});import{useEffect as es,useState as ts}from"react";import{Box as sr,Text as ae}from"ink";import{Fragment as is,jsx as pe,jsxs as Ge}from"react/jsx-runtime";function ns(t,e=12){let n=Math.min(e,Math.max(0,Math.round(t/100*e)));return"\u2588".repeat(n)+"\u2591".repeat(e-n)}function rs(t){return t>=90?"red":t>=70?"yellow":"green"}function os(t){let e=0;for(let n of t.agents.values())n.phase!=="done"&&n.phase!=="idle"&&e++;return e}function ss(t){let e=t.pipelineResumedAt,[,n]=ts(0);return es(()=>{if(e===null)return;let r=setInterval(()=>n(o=>o+1),250);return()=>clearInterval(r)},[e]),e===null?t.pipelineElapsedMs:t.pipelineElapsedMs+(Date.now()-e)}function ir({state:t}){let e=ss(t),n=t.pressure?.pct??0,r=os(t),o=rs(n);return pe(sr,{borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,paddingTop:0,children:Ge(sr,{flexDirection:"row",children:[pe(ae,{dimColor:!0,children:"KV "}),pe(ae,{color:o,children:ns(n)}),Ge(ae,{children:[" ",String(n).padStart(2," "),"%"]}),pe(ae,{dimColor:!0,children:" \xB7 "}),pe(ae,{children:t.phase}),pe(ae,{dimColor:!0,children:" \xB7 \u23F1 "}),pe(ae,{children:Qn(e)}),pe(ae,{dimColor:!0,children:" \xB7 "}),Ge(ae,{children:[r," active"]}),t.sourceCount>0?Ge(is,{children:[pe(ae,{dimColor:!0,children:" \xB7 "}),pe(ae,{dimColor:!0,children:"\u2315 "}),Ge(ae,{children:[t.sourceCount," sources"]})]}):null]})})}var ar=q(()=>{"use strict";zt()});import{useState as as}from"react";import{Text as Be,useInput as ls}from"ink";import{jsx as mt,jsxs as cr}from"react/jsx-runtime";function xe({value:t,onChange:e,onSubmit:n,onCancel:r,placeholder:o="",focused:s=!0,mask:a=!1,color:i}){let[d,c]=as(t.length),u=Math.min(d,t.length);ls((p,g)=>{if(g.return){n?.(t);return}if(g.escape){r?.();return}if(g.leftArrow){g.meta||g.ctrl?c(lr(t,u)):c(Math.max(0,u-1));return}if(g.rightArrow){g.meta||g.ctrl?c(cs(t,u)):c(Math.min(t.length,u+1));return}if(p==="\x1B[H"||p==="\x1BOH"){c(0);return}if(p==="\x1B[F"||p==="\x1BOF"){c(t.length);return}if(g.backspace||g.delete){if(u===0)return;if(g.meta||g.ctrl){let A=lr(t,u);e(t.slice(0,A)+t.slice(u)),c(A);return}let C=t.slice(0,u-1)+t.slice(u);c(u-1),e(C);return}if(g.ctrl&&p==="a"){c(0);return}if(g.ctrl&&p==="e"){c(t.length);return}if(g.ctrl&&p==="u"){e(t.slice(u)),c(0);return}if(g.ctrl&&p==="k"){e(t.slice(0,u));return}if(g.ctrl&&p==="w"){let C=t.slice(0,u),A=/\S+\s*$/.exec(C),T=A?A.index:0;e(t.slice(0,T)+t.slice(u)),c(T);return}if(!(g.ctrl||g.meta||g.tab||g.upArrow||g.downArrow)&&p.length>0){let C=t.slice(0,u)+p+t.slice(u);c(u+p.length),e(C)}},{isActive:s});let m=a?"*".repeat(t.length):t;if(t.length===0)return cr(Be,{children:[mt(Be,{color:i,children:s?"\u258E":""}),mt(Be,{dimColor:!0,children:o})]});if(!s)return mt(Be,{color:i,children:m});let v=m.slice(0,u),L=m.slice(u,u+1),P=m.slice(u+1);return cr(Be,{color:i,children:[v,mt(Be,{inverse:!0,children:L||" "}),P]})}function lr(t,e){if(e<=0)return 0;let n=e;for(;n>0&&/\s/.test(t[n-1]);)n--;for(;n>0&&!/\s/.test(t[n-1]);)n--;return n}function cs(t,e){let n=t.length;if(e>=n)return n;let r=e;for(;r<n&&/\s/.test(t[r]);)r++;for(;r<n&&!/\s/.test(t[r]);)r++;return r}var Kt=q(()=>{"use strict"});import{memo as qe,useEffect as Gt,useState as De}from"react";import{Box as ee,Text as O,useInput as us}from"ink";import{jsx as k,jsxs as re}from"react/jsx-runtime";function ur(t){if(!t.startsWith("/"))return null;let e=t.slice(1).trimStart();if(!e)return{name:"",value:""};let n=e.search(/\s/),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1).trim();return{name:r,value:o}}function ds(t){if(!t)return[];if(!t.name)return ft;let e=t.name.toLowerCase();return ft.filter(n=>n.name.startsWith(e))}var ft,hr,dr,Qt,ps,hs,pr,mr=q(()=>{"use strict";lt();Kt();ft=[{name:"scan",desc:"Set local file source (path or glob)",kind:"value"},{name:"web",desc:"Set web search key",kind:"value"},{name:"model",desc:"Set local LLM .gguf path",kind:"value"},{name:"reranker",desc:"Set local reranker .gguf path",kind:"value"},{name:"output",desc:"Set output directory",kind:"value"},{name:"deep",desc:"Use deep (chain) reasoning",kind:"instant"},{name:"flat",desc:"Use flat (parallel) reasoning",kind:"instant"},{name:"help",desc:"Show this list",kind:"instant"},{name:"quit",desc:"Quit",kind:"instant"}];hr=qe(function({state:e}){let n=at(),r=e.config?.defaults.reasoningMode??"flat",[o,s]=De(r),[a,i]=De("query"),[d,c]=De(""),[u,m]=De(""),[w,v]=De(!1),L=e.scrollback.length>0,[P,p]=De(L?"start":"plan");Gt(()=>{L&&p("start")},[L]),Gt(()=>{e.composerPrefill&&e.composerPrefill!==d&&c(e.composerPrefill)},[e.composerPrefill]),Gt(()=>{s(r)},[r]);let g=e.configOrigin?.tavilyKey??"unset",C=e.configOrigin?.corpusPath??"unset",A=e.configOrigin?.outputDir??"default",T=g!=="unset",F=T||C!=="unset",J=g==="env",K=e.clarifyContext!==null,B=ur(d),D=B!==null,U=ds(B);us((x,h)=>{if(h.ctrl&&x==="c"){n({type:"quit"});return}if(h.tab&&h.shift){!D&&!K&&p(l=>l==="plan"?"start":"plan");return}if(h.tab){if(D&&B&&B.name&&U.length===1){let l=U[0];c("/"+l.name+(l.kind==="value"?" ":""));return}return}if(h.escape){if(K){n({type:"cancel_plan"}),c("");return}c(""),v(!1);return}},{isActive:a==="query"});let Se=x=>{let h=x.trim();if(h){if(!K){let l=ur(h);if(l){Ee(l);return}}if(K){n({type:"submit_clarification",answer:h}),c("");return}F&&(n({type:"submit_query",query:h,mode:o,skipPlanner:P==="start"}),c(""))}},Ee=({name:x,value:h})=>{if(!x)return;let l=ft.find(f=>f.name===x);if(l){if(c(""),v(!1),l.kind==="instant"){x==="deep"?s("deep"):x==="flat"?s("flat"):x==="quit"?n({type:"quit"}):x==="help"&&v(!0);return}if(h){x==="web"?n({type:"set_tavily_key",key:h}):x==="scan"?n({type:"set_corpus_path",path:h}):x==="output"?n({type:"set_output_dir",path:h}):x==="model"?n({type:"set_model_path",path:h}):x==="reranker"&&n({type:"set_reranker_path",path:h});return}if(x==="web"){if(J)return;m(e.config?.sources.tavilyKey??""),i("web")}else x==="scan"?(m(e.config?.sources.corpusPath??""),i("scan")):x==="output"?(m(e.config?.sources.outputDir??""),i("output")):x==="model"?(m(e.config?.model.path??""),i("model")):x==="reranker"&&(m(e.config?.model.reranker??""),i("reranker"))}};return re(ee,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[a==="query"?re(ee,{children:[k(O,{children:"\u203A "}),k(xe,{value:d,onChange:c,onSubmit:Se,focused:!0,placeholder:K?"Answer the questions above, or Esc to cancel\u2026":F?"Ask a research question, or / for commands\u2026":"Type / for commands (e.g. /web, /scan) to add a source"})]}):a==="web"?re(ee,{children:[k(O,{color:"yellow",children:"Web search key \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_tavily_key",key:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,mask:!0,placeholder:"tvly-..."})]}):a==="scan"?re(ee,{children:[k(O,{color:"yellow",children:"Scan path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_corpus_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/docs or /path/**/*.md"})]}):a==="output"?re(ee,{children:[k(O,{color:"yellow",children:"Output dir \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_output_dir",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:`${process.cwd()} (default)`})]}):a==="model"?re(ee,{children:[k(O,{color:"yellow",children:"Model path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_model_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/qwen3.5-4b.gguf"})]}):re(ee,{children:[k(O,{color:"yellow",children:"Reranker path \u203A "}),k(xe,{value:u,onChange:m,onSubmit:()=>{n({type:"set_reranker_path",path:u.trim()}),i("query"),m("")},onCancel:()=>{i("query"),m("")},focused:!0,placeholder:"/path/to/qwen3-reranker.gguf"})]}),a==="query"&&!K&&D?k(ee,{flexDirection:"column",marginTop:0,children:U.length===0?k(O,{color:"red",children:"no matching command"}):U.map(x=>k(dr,{cmd:x},x.name))}):null,a==="query"&&!D&&w?k(ee,{flexDirection:"column",marginTop:0,children:ft.map(x=>k(dr,{cmd:x},x.name))}):null,re(ee,{marginTop:0,children:[k(Qt,{label:"Web",origin:g,value:T?"set":null,disabled:J}),k(O,{children:" "}),k(Qt,{label:"Scan",origin:C,value:e.config?.sources.corpusPath?e.corpusStatus?`${e.corpusStatus.fileCount} files`:e.config.sources.corpusPath:null}),k(O,{children:" "}),k(Qt,{label:"Output",origin:A,value:e.config?.sources.outputDir??null}),k(ee,{flexGrow:1}),a==="query"&&!K&&!D?k(hs,{submitMode:P}):null]}),k(ee,{marginTop:0,children:k(ps,{field:a,hasSource:F,inSlash:D,clarifying:K})}),e.toast?k(ee,{marginTop:0,children:k(O,{color:e.toast.tone==="error"?"red":e.toast.tone==="warn"?"yellow":"green",children:e.toast.message})}):null]})}),dr=qe(function({cmd:e}){return re(ee,{children:[re(O,{color:"cyan",children:["/",e.name]}),re(O,{dimColor:!0,children:[" \xB7 ",e.desc]}),e.kind==="value"?k(O,{dimColor:!0,children:" <value>"}):null]})}),Qt=qe(function({label:e,origin:n,value:r,disabled:o=!1}){let s=n!=="unset";return re(O,{children:[re(O,{color:s?"green":"gray",dimColor:o,children:[e," ",s?e==="Scan"&&r?r:"\u2713":"\u2014"]}),k(O,{dimColor:!0,children:n==="env"?" (env)":n==="cli"?" (cli)":""})]})}),ps=qe(function({field:e,hasSource:n,inSlash:r,clarifying:o}){return e==="web"||e==="scan"||e==="output"||e==="model"||e==="reranker"?k(O,{dimColor:!0,children:"\u23CE save (empty to clear) \xB7 Ctrl+U clear \xB7 Esc cancel"}):o?k(O,{color:"yellow",children:"\u23CE submit answer \xB7 Esc cancel"}):r?k(O,{dimColor:!0,children:"Tab complete \xB7 \u23CE run \xB7 Esc clear"}):n?k(O,{dimColor:!0,children:"\u21E7Tab Plan/Start \xB7 / commands"}):k(O,{color:"yellow",children:"\u26A0 Add a source via /web or /scan"})}),hs=qe(function({submitMode:e}){return re(ee,{children:[k(pr,{label:"PLAN",focused:e==="plan",hue:"cyan"}),k(O,{children:" "}),k(pr,{label:"START",focused:e==="start",hue:"green"})]})}),pr=qe(function({label:e,focused:n,hue:r}){let s=` ${n?"\u25C9":"\u25CB"} ${e} `;return n?k(O,{backgroundColor:r,color:"black",bold:!0,children:s}):k(O,{dimColor:!0,children:s})})});import{memo as Vt,useEffect as fr,useRef as ms,useState as gt}from"react";import{Box as Y,Text as _,useInput as fs}from"ink";import{jsx as E,jsxs as Q}from"react/jsx-runtime";var gr,gs,ys,yr=q(()=>{"use strict";lt();Kt();gr=Vt(function({state:e}){let n=at(),r=e.plan,[o,s]=gt(e.mode??"flat"),[a,i]=gt(()=>r?.tasks.length??0),[d,c]=gt(null),[u,m]=gt("");fr(()=>{e.mode&&e.mode!==o&&s(e.mode),c(null),i(r?.tasks.length??0)},[e.mode]),fr(()=>{r&&a>r.tasks.length&&i(r.tasks.length)},[r?.tasks.length]);let w=ms({focusedIndex:a,editingIndex:d,mode:o,plan:r,query:e.query});if(w.current={focusedIndex:a,editingIndex:d,mode:o,plan:r,query:e.query},fs((P,p)=>{let g=w.current,C=g.plan,A=g.editingIndex,T=g.focusedIndex,le=g.mode;if(!C||A!==null)return;if(C.intent!=="research"){if(p.return){C.intent==="clarify"&&n({type:"edit_plan",query:g.query});return}p.escape&&n({type:"cancel_plan"}),p.ctrl&&P==="c"&&n({type:"quit"});return}if(p.ctrl&&P==="c"){n({type:"quit"});return}if(p.escape){n({type:"cancel_plan"});return}let F=T>=C.tasks.length;if(p.shift&&p.upArrow){!F&&T>0&&(n({type:"move_task",from:T,to:T-1}),i(T-1));return}if(p.shift&&p.downArrow){!F&&T<C.tasks.length-1&&(n({type:"move_task",from:T,to:T+1}),i(T+1));return}if(p.upArrow){i(Math.max(0,T-1));return}if(p.downArrow){i(Math.min(C.tasks.length,T+1));return}if(p.return){F?n({type:"accept_plan"}):(m(C.tasks[T]?.description??""),c(T));return}if(P==="a"||P==="A"||P==="+"){let J=F?C.tasks.length-1:T,K=J+1;n({type:"add_task",afterIndex:J}),i(K),m(""),c(K);return}if(P==="d"||P==="D"||p.delete){!F&&C.tasks.length>1&&n({type:"delete_task",index:T});return}if(P==="t"||P==="T"){let J=le==="deep"?"flat":"deep";s(J),n({type:"change_mode",mode:J});return}}),!r)return null;if(r.intent==="clarify")return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(Y,{marginBottom:1,children:E(_,{bold:!0,children:e.query})}),E(_,{dimColor:!0,children:"A few questions to narrow this down."}),E(Y,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.clarifyQuestions.map((P,p)=>Q(_,{children:[Q(_,{dimColor:!0,children:["(",p+1,")"]})," ",P]},p))}),E(Y,{marginTop:1,children:E(_,{dimColor:!0,children:"\u23CE answer \xB7 Esc cancel"})})]});if(r.intent==="passthrough")return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(_,{bold:!0,children:e.query}),E(_,{dimColor:!0,children:"Answering directly \u2014 no research needed."})]});let v=o==="flat"?"parallel":"chained",L=d!==null;return Q(Y,{flexDirection:"column",marginBottom:1,children:[E(Y,{marginBottom:1,children:E(_,{bold:!0,children:e.query})}),Q(Y,{marginBottom:1,children:[E(_,{dimColor:!0,children:"Research plan"}),Q(_,{dimColor:!0,children:[" \xB7 ",r.tasks.length," ",v," tasks"]}),L?Q(_,{color:"yellow",children:[" \xB7 editing row ",d+1]}):null]}),Q(Y,{flexDirection:"column",children:[r.tasks.map((P,p)=>E(ys,{index:p,description:P.description,focused:p===a,editing:p===d,draft:u,onDraftChange:m,onSubmit:g=>{n({type:"update_task_description",index:p,description:g.trim()}),c(null)},onCancel:()=>c(null)},p)),E(gs,{focused:a>=r.tasks.length&&!L})]}),Q(Y,{marginTop:1,children:[Q(_,{color:o==="deep"?"cyan":void 0,bold:o==="deep",children:[o==="deep"?"\u25C6":"\u25CB"," Deep"]}),E(_,{children:" "}),Q(_,{color:o==="flat"?"cyan":void 0,bold:o==="flat",children:[o==="flat"?"\u25C6":"\u25CB"," Flat"]}),E(_,{dimColor:!0,children:" T toggle mode (re-plans, discards edits)"})]}),E(Y,{marginTop:1,children:L?E(_,{dimColor:!0,children:"\u23CE save \xB7 Esc revert"}):Q(_,{dimColor:!0,children:["\u2191\u2193 select \xB7 \u23CE ",a>=r.tasks.length?"start research":"edit"," \xB7 A add \xB7 D delete \xB7 \u21E7\u2191\u2193 reorder \xB7 Esc cancel"]})})]})}),gs=Vt(function({focused:e}){return e?E(Y,{paddingLeft:2,marginTop:1,children:E(_,{backgroundColor:"green",color:"black",bold:!0,children:" \u25B6 START research "})}):E(Y,{paddingLeft:2,marginTop:1,children:E(_,{dimColor:!0,children:" \u25B6 START research"})})}),ys=Vt(function({index:e,description:n,focused:r,editing:o,draft:s,onDraftChange:a,onSubmit:i,onCancel:d}){return o?Q(Y,{paddingLeft:2,children:[E(_,{color:"yellow",bold:!0,children:`\u25B6 ${e+1}. `}),E(Y,{flexGrow:1,children:E(xe,{value:s,onChange:a,onSubmit:i,onCancel:d,focused:!0,placeholder:"(empty \u2014 type a task description)"})})]}):r?Q(Y,{paddingLeft:2,children:[E(_,{color:"cyan",bold:!0,children:`\u203A ${e+1}. `}),E(_,{bold:!0,children:n||E(_,{dimColor:!0,children:"(empty)"})})]}):Q(Y,{paddingLeft:2,children:[E(_,{dimColor:!0,children:` ${e+1}. `}),E(_,{dimColor:!0,children:n||"(empty)"})]})})});import{memo as bs,useEffect as xs,useState as ks}from"react";import{Box as br,Text as Xt}from"ink";import{jsx as xr,jsxs as Jt}from"react/jsx-runtime";var kr,wr=q(()=>{"use strict";ut();kr=bs(function({state:e}){let[n,r]=ks(0);return xs(()=>{let o=setInterval(()=>r(s=>(s+1)%de.length),80);return()=>clearInterval(o)},[]),Jt(br,{flexDirection:"column",marginBottom:1,children:[xr(Xt,{bold:!0,children:e.query}),Jt(br,{marginTop:1,children:[Jt(Xt,{color:"cyan",children:[de[n]," "]}),xr(Xt,{dimColor:!0,children:"Planning\u2026"})]})]})})});import{memo as ws}from"react";import{Box as Tr,Text as yt}from"ink";import{jsx as Zt,jsxs as en}from"react/jsx-runtime";var Sr,Cr=q(()=>{"use strict";Sr=ws(function({state:e}){if(!e.clarifyContext)return null;let{originalQuery:n,questions:r}=e.clarifyContext;return en(Tr,{flexDirection:"column",marginBottom:1,children:[Zt(yt,{bold:!0,children:n}),Zt(yt,{dimColor:!0,children:"A few questions to narrow this down."}),Zt(Tr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.map((o,s)=>en(yt,{children:[en(yt,{dimColor:!0,children:["(",s+1,")"]})," ",o]},s))})]})})});import{memo as vr,useEffect as Ts,useState as Ss}from"react";import{Box as Pe,Text as N}from"ink";import{Fragment as Rs,jsx as oe,jsxs as V}from"react/jsx-runtime";function vs(t){try{return new URL(t).host}catch{return null}}function bt(t){return t>=1e9?(t/1e9).toFixed(1)+" GB":t>=1e6?(t/1e6).toFixed(0)+" MB":t>=1e3?(t/1e3).toFixed(0)+" KB":`${t} B`}var Rr,Cs,Pr=q(()=>{"use strict";ut();Rr=vr(function({state:e}){let[n,r]=Ss(0);if(Ts(()=>{let o=setInterval(()=>r(s=>(s+1)%de.length),80);return()=>clearInterval(o)},[]),e.uiPhase==="boot_error"){let o=e.bootError,s=o?.kind??"llm",a=s==="llm"?"LLM":"reranker",i=s==="llm"?"/model":"/reranker",d=s==="llm"?"/reranker":"/model";return V(Pe,{flexDirection:"column",marginBottom:1,children:[V(N,{color:"red",bold:!0,children:["\u2717 Boot failed (",a,")"]}),oe(Pe,{paddingLeft:2,children:oe(N,{children:o?.message??"Unknown error"})}),oe(Pe,{paddingLeft:2,marginTop:1,children:V(N,{dimColor:!0,children:["Type ",V(N,{color:"cyan",children:[i," "]}),oe(N,{dimColor:!0,children:"<path-to-gguf>"}),V(N,{dimColor:!0,children:[" to use a local ",a,", or "]}),oe(N,{color:"cyan",children:d}),oe(N,{dimColor:!0,children:" for the other, or "}),oe(N,{color:"cyan",children:"/quit"}),oe(N,{dimColor:!0,children:" to exit."})]})})]})}return e.uiPhase==="downloading"?V(Pe,{flexDirection:"column",marginBottom:1,children:[V(Pe,{children:[V(N,{color:"cyan",children:[de[n]," "]}),oe(N,{bold:!0,children:"Downloading models"})]}),e.downloads.map(o=>oe(Cs,{item:o},o.id))]}):V(Pe,{marginBottom:1,children:[V(N,{color:"cyan",children:[de[n]," "]}),oe(N,{bold:!0,children:e.loadingLabel??"Loading\u2026"})]})}),Cs=vr(function({item:e}){let n=e.total>0?Math.min(100,Math.floor(e.got/e.total*100)):0,r=16,o=Math.floor(n/100*r),s="\u2588".repeat(o)+"\u2591".repeat(r-o),a=e.url?vs(e.url):null,i=e.started&&a!==null,d=e.done?"\u2713 ":i?"\u25CF ":"\u25CB ",c=e.done?"green":i?"cyan":void 0,u=!i&&!e.done;return V(Pe,{paddingLeft:2,children:[oe(N,{color:c,dimColor:u,children:d}),V(N,{dimColor:u,children:[e.label.padEnd(28)," "]}),e.done?oe(N,{dimColor:!0,children:bt(e.got)}):i?V(Rs,{children:[oe(N,{color:"cyan",children:s}),V(N,{children:[" ",String(n).padStart(2),"% \xB7 ",bt(e.got)," / ",bt(e.total)]}),V(N,{dimColor:!0,children:[" \xB7 ",a]})]}):V(N,{dimColor:!0,children:["queued \xB7 ",bt(e.total)]})]})})});import{Box as xt,Static as Ps,Text as Ar}from"ink";import{jsx as X,jsxs as tn}from"react/jsx-runtime";function Er({bus:t,dispatch:e,bootstrap:n}){let r=Fn(t,n),o=r.uiPhase!=="composer"&&r.uiPhase!=="boot"&&r.uiPhase!=="downloading"&&r.uiPhase!=="loading"&&r.uiPhase!=="planning"&&r.uiPhase!=="plan_review"&&r.uiPhase!=="clarifying",s=r.uiPhase==="research"||r.uiPhase==="done",a=r.uiPhase==="composer"||r.uiPhase==="done"||r.uiPhase==="clarifying"||r.uiPhase==="boot_error";return tn(Bt.Provider,{value:e,children:[X(Ps,{items:r.scrollback,children:i=>i.kind==="agent"?X(xt,{paddingX:2,children:X(jn,{agent:i.agent})},i.key):tn(xt,{flexDirection:"column",paddingX:2,marginBottom:1,children:[X(Ar,{dimColor:!0,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"}),X(xt,{paddingLeft:2,marginTop:1,children:X(Ar,{children:i.body})})]},i.key)}),tn(xt,{flexDirection:"column",paddingX:2,paddingY:1,children:[o&&X(zn,{query:r.query,warm:r.warm}),(r.uiPhase==="downloading"||r.uiPhase==="loading"||r.uiPhase==="boot_error")&&X(Rr,{state:r}),r.uiPhase==="planning"&&X(kr,{state:r}),r.uiPhase==="plan_review"&&X(gr,{state:r}),r.uiPhase==="clarifying"&&X(Sr,{state:r}),s&&X(Xn,{state:r}),s&&X(Zn,{state:r}),r.uiPhase==="done"&&X(rr,{state:r}),a&&X(hr,{state:r}),X(ir,{state:r})]})]})}var Ir=q(()=>{"use strict";Un();lt();Hn();Kn();Jn();er();or();ar();mr();yr();wr();Cr();Pr()});var Mr={};zr(Mr,{render:()=>Is});import As from"react";import{render as Es}from"ink";function Is(t,e,n=[]){return Es(As.createElement(Er,{bus:t,dispatch:e,bootstrap:n}),{incrementalRendering:!0})}var _r=q(()=>{"use strict";Ir()});import*as H from"node:fs";import*as ge from"node:path";import{parseArgs as Ms}from"node:util";import{main as _s,ensure as kt,createSignal as Os,spawn as Or,each as Ae,call as Fe}from"effection";import{createContext as Bs}from"@lloyal-labs/lloyal.node";import{initAgents as Ds,JsonlTraceWriter as qs}from"@lloyal-labs/lloyal-agents";var wt=!1,Hr=!1;function un(t){wt=t}function dn(t){Hr=t}var Tt=!!process.stdout.isTTY,St=Tt?{bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m",green:"\x1B[32m",cyan:"\x1B[36m",yellow:"\x1B[33m",red:"\x1B[31m"}:{bold:"",dim:"",reset:"",green:"",cyan:"",yellow:"",red:""},cn="";function Yr(){cn&&(cn="",process.stdout.write("\r\x1B[K"))}var Je=(...t)=>{wt||(Yr(),console.log(...t))};function pn(t,e){wt&&console.log(JSON.stringify({event:t,...e}))}import*as ne from"node:fs";import*as Z from"node:path";import*as Ct from"node:os";import*as Ze from"node:path";function ke(t){if(!t)return"";let e=t==="~"?Ct.homedir():t.startsWith("~/")?Ze.join(Ct.homedir(),t.slice(2)):t;return Ze.resolve(e)}function vt(){return{version:1,sources:{},defaults:{reasoningMode:"flat",maxTurns:10},model:{}}}function mn(t){try{let e=ne.readFileSync(t,"utf8"),n=JSON.parse(e);if(n.version!==1)return null;let r=vt();return{version:1,sources:{...r.sources,...n.sources??{}},defaults:{...r.defaults,...n.defaults??{}},model:{...r.model,...n.model??{}}}}catch{return null}}function Ce(t,e,n=process.env){let r=Z.resolve(t),o=mn(r),s=o??vt(),a=n.TAVILY_API_KEY?.trim()||void 0,i=n.LLAMA_CTX_SIZE?.trim(),d=i&&/^\d+$/.test(i)?parseInt(i,10):void 0,c=e.tavilyKey??a??s.sources.tavilyKey,u=e.corpusPath??s.sources.corpusPath,m=u?ke(u):void 0,w=e.outputDir??s.sources.outputDir,v=w?ke(w):void 0,L=e.reasoningMode??s.defaults.reasoningMode??"flat",P=e.modelPath??s.model.path,p=P?ke(P):void 0,g=e.reranker??s.model.reranker,C=e.nCtx??d??s.model.nCtx,A={version:1,sources:{tavilyKey:c,corpusPath:m,outputDir:v},defaults:{reasoningMode:L,maxTurns:s.defaults.maxTurns},model:{path:p,reranker:g,nCtx:C}},T={tavilyKey:e.tavilyKey?"cli":a?"env":s.sources.tavilyKey?"file":"unset",corpusPath:e.corpusPath?"cli":s.sources.corpusPath?"file":"unset",reasoningMode:e.reasoningMode?"cli":o?.defaults.reasoningMode?"file":"default",modelPath:e.modelPath?"cli":o?.model.path?"file":"default",reranker:e.reranker?"cli":o?.model.reranker?"file":"default",nCtx:e.nCtx!==void 0?"cli":d!==void 0?"env":o?.model.nCtx!==void 0?"file":"default",outputDir:e.outputDir?"cli":o?.sources.outputDir?"file":"default"};return{config:A,origin:T,path:r,loadedFromFile:!!o}}function we(t,e,n=process.env){let r=Z.resolve(e),o=mn(r)??vt(),s=[],a={...o.sources,...t.sources??{}};t.sources?.tavilyKey===""&&delete a.tavilyKey,t.sources?.corpusPath===""&&delete a.corpusPath,t.sources?.outputDir===""&&delete a.outputDir,n.TAVILY_API_KEY&&t.sources&&"tavilyKey"in t.sources&&(delete a.tavilyKey,s.push("sources.tavilyKey"));let i={version:1,sources:a,defaults:{...o.defaults,...t.defaults??{}},model:{...o.model,...t.model??{}}},d=Z.dirname(r);ne.mkdirSync(d,{recursive:!0});let c=r+".tmp-"+process.pid;ne.writeFileSync(c,JSON.stringify(i,null,2)+`
7
+ `,"utf8"),ne.renameSync(c,r);let u=jr(r);return{path:r,gitignored:u,skipped:s}}function jr(t){try{let e=Kr(Z.dirname(t));if(!e)return!1;let n=Z.join(e,".gitignore"),r=Z.relative(e,t).replace(/\\/g,"/"),o=ne.existsSync(n)?ne.readFileSync(n,"utf8"):"",s=Z.basename(t);if(new RegExp(`(^|\\n)\\s*(${hn(r)}|${hn(s)})\\s*(\\n|$)`).test(o))return!1;let i=o.length===0||o.endsWith(`
8
8
  `)?"":`
9
- `;return j.appendFileSync(n,a+r+`
10
- `),!0}catch{return!1}}function wn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ho(t){let e=z.resolve(t);for(;;){if(j.existsSync(z.join(e,".git")))return e;let n=z.dirname(e);if(n===e)return null;e=n}}function vn(){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 oi}from"@lloyal-labs/rig";import{createReranker as si,WebSource as ii,CorpusSource as ai,chunkResources as li,resolveCorpusInput as ci}from"@lloyal-labs/rig/node";import ui from"ignore";import{call as Mt}from"effection";import{Ctx as Ot,Events as Bt,agent as So,agentPool as Dn,createToolkit as Ro,useAgent as Eo,chain as Ao,parallel as qn,renderTemplate as Te,withSharedRoot as Po,DefaultAgentPolicy as Wn}from"@lloyal-labs/lloyal-agents";import{reportTool as Nn,PlanTool as Io,taskToContent as Ln}from"@lloyal-labs/rig";var Cn=`You're a research planner. You analyze a user query and pick ONE of three dispositions, producing a JSON plan. Output JSON only.
9
+ `;return ne.appendFileSync(n,i+r+`
10
+ `),!0}catch{return!1}}function hn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Kr(t){let e=Z.resolve(t);for(;;){if(ne.existsSync(Z.join(e,".git")))return e;let n=Z.dirname(e);if(n===e)return null;e=n}}function fn(){let t=[],e=new Set;return{send(n){if(t!==null){t.push(n);return}for(let r of e)r(n)},subscribe(n){if(e.add(n),t!==null){let r=t;t=null;for(let o of r)n(o)}return()=>{e.delete(n)}}}}import{TavilyProvider as Ns}from"@lloyal-labs/rig";import{createReranker as Ls,WebSource as Fs,CorpusSource as Us,chunkResources as $s,resolveCorpusInput as Ws}from"@lloyal-labs/rig/node";import zs from"ignore";import{call as Rt}from"effection";import{Ctx as At,Events as et,agentPool as ro,createToolkit as oo,useAgent as so,chain as io,parallel as ao,renderTemplate as $e,withSharedRoot as lo,DefaultAgentPolicy as En}from"@lloyal-labs/lloyal-agents";import{reportTool as vn,PlanTool as co}from"@lloyal-labs/rig";import{taskToContent as Rn}from"@lloyal-labs/rig";var gn=`You're a research planner. You analyze a user query and pick ONE of three dispositions, producing a JSON plan. Output JSON only.
11
11
  ---
12
12
  The query: "<%= it.query %>"
13
13
 
@@ -94,7 +94,7 @@ BAD \u2014 individual task issues (for research intent):
94
94
 
95
95
  <%= it.context %>
96
96
  <% } -%>
97
- `;var Sn=`You're a research planner. You analyze a user query and pick ONE of three dispositions, producing a JSON plan. Output JSON only.
97
+ `;var yn=`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 Rn="You are a research assistant.";var En=`Based on the research notes and source passages below, answer the question in 3-5 sentences. Use your own judgment to identify the key conclusions \u2014 do not paraphrase the research notes.
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 bn="You are a research assistant.";var xn=`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 In=`You are writing an analytical research report that answers the user's question below.
193
+ `;var kn=`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 Mn=`You are writing an analytical research report that answers the user's question below.
304
+ `;var wn=`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 _n=`Apply the **corpus_research** skill.
419
+ `;var Tn=`Apply the **corpus_research** playbook.
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 On=`Apply the **web_research** skill.
447
+ `;var Sn=`Apply the **web_research** playbook.
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,9 +477,9 @@ 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 Bn=`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.
480
+ `;var Cn=`You are an assistant working as part of a multi-agent workflow. You have access to the tools below, grouped by playbook. You should only use the tools for a given playbook when that particular playbook is requested explicitly in your task instructions.
501
481
 
502
- # Skills
482
+ # Playbooks
503
483
 
504
484
  <% if (it.hasWeb) { -%>
505
485
  ## web_research
@@ -515,7 +495,7 @@ Use when: investigating a local document corpus \u2014 finding occurrences of te
515
495
  <% } -%>
516
496
  # Tool selection rule
517
497
 
518
- The agent system message will tell you which skill to apply. Use only that skill's tools. The agent system message also carries an engineered PROCESS that dictates intra-skill ordering. Follow that PROCESS, but constrained to the assigned skill's palette.
498
+ The agent system message will tell you which playbook to apply. Use only that playbook's tools. The agent system message also carries an engineered PROCESS that dictates intra-playbook ordering. Follow that PROCESS, but constrained to the assigned playbook's palette.
519
499
 
520
500
  # Examples
521
501
 
@@ -523,7 +503,7 @@ The agent system message will tell you which skill to apply. Use only that skill
523
503
  ## GOOD: web_research applied correctly
524
504
 
525
505
  SYSTEM:
526
- Apply the **web_research** skill.
506
+ Apply the **web_research** playbook.
527
507
  You are a thorough research assistant. PROCESS: 1) broad web_search; 2) fetch_page on top 2\u20133 results; 3) report.
528
508
 
529
509
  USER:
@@ -544,7 +524,7 @@ ASSISTANT calls: report({"summary": "Project Alpha findings: \u2026"})
544
524
  ## GOOD: corpus_research applied correctly
545
525
 
546
526
  SYSTEM:
547
- Apply the **corpus_research** skill.
527
+ Apply the **corpus_research** playbook.
548
528
  You are analyzing a local knowledge base. PROCESS: 1) grep or search; 2) read_file on matches; 3) report.
549
529
 
550
530
  USER:
@@ -565,7 +545,7 @@ ASSISTANT calls: report({"summary": "Project Beta findings: \u2026"})
565
545
  ## BAD: corpus_research requested, web_research tool used
566
546
 
567
547
  SYSTEM:
568
- Apply the **corpus_research** skill.
548
+ Apply the **corpus_research** playbook.
569
549
  You are analyzing a local knowledge base. PROCESS: grep/search \u2192 read_file \u2192 report.
570
550
 
571
551
  USER:
@@ -578,7 +558,7 @@ ASSISTANT calls: web_search({"query": "Project Beta"})
578
558
  ## BAD: web_research requested, corpus_research tool used
579
559
 
580
560
  SYSTEM:
581
- Apply the **web_research** skill.
561
+ Apply the **web_research** playbook.
582
562
  PROCESS: search \u2192 fetch \u2192 report.
583
563
 
584
564
  USER:
@@ -593,7 +573,7 @@ ASSISTANT calls: grep({"pattern": "Project Alpha"})
593
573
  ## BAD: web_research requested, report called without prior retrieval
594
574
 
595
575
  SYSTEM:
596
- Apply the **web_research** skill.
576
+ Apply the **web_research** playbook.
597
577
  PROCESS: search \u2192 fetch \u2192 report.
598
578
 
599
579
  USER:
@@ -601,14 +581,14 @@ Research task: Project Alpha
601
581
 
602
582
  ASSISTANT calls: report({"summary": "(no findings \u2014 no research performed)"})
603
583
 
604
- \u2717 WRONG. Research skills require gathering evidence before reporting. report is the terminal \u2014 calling it without prior web_search/fetch_page produces an empty finding.
584
+ \u2717 WRONG. Research playbooks require gathering evidence before reporting. report is the terminal \u2014 calling it without prior web_search/fetch_page produces an empty finding.
605
585
 
606
586
  <% } -%>
607
587
  <% if (it.hasCorpus) { -%>
608
588
  ## BAD: corpus_research requested, report called without prior retrieval
609
589
 
610
590
  SYSTEM:
611
- Apply the **corpus_research** skill.
591
+ Apply the **corpus_research** playbook.
612
592
  PROCESS: grep/search \u2192 read_file \u2192 report.
613
593
 
614
594
  USER:
@@ -616,49 +596,47 @@ Research task: Project Beta
616
596
 
617
597
  ASSISTANT calls: report({"summary": "(no findings \u2014 no corpus inspection performed)"})
618
598
 
619
- \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.
599
+ \u2717 WRONG. Research playbooks 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 ge(t){let e=t.trim(),n=e.indexOf(`
602
+ `;function Ie(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 Mo=ge(Cn),_o=ge(Sn),Oo=ge(Rn),Fn=ge(En),Un=ge(An),Bo=ge(Pn),Do=ge(In),qo=ge(Mn),No=_n,Lo=On,Fo=Bn;function Uo(){return new Wn({budget:{context:{softLimit:2048,hardLimit:1024},time:{softLimit:24e4,hardLimit:36e4}},recovery:{prompt:Bo},terminalTool:"report"})}var _t=class extends Wn{onProduced(...e){let[,n]=e;return!n.toolCalls[0]&&n.content?{type:"free_text_report",content:n.content}:super.onProduced(...e)}};function $n(t,e){return t.promptData?Te(No,{...t.promptData(),...e}):t.name==="web"?Te(Lo,e):Oo.system}function zn(){return new Date().toISOString().slice(0,10)}function at(){let t=performance.now();return()=>performance.now()-t}function*$o(t,e){let n=e.trunk;if(!n)throw new Error("runPassthrough: session has no trunk \u2014 passthrough requires a warm session");let r=yield*Ot.expect(),o=r.getTurnSeparator(),{prompt:s}=r.formatChatSync(JSON.stringify([{role:"user",content:t}]),{addGenerationPrompt:!0,enableThinking:!1}),i=[...o,...r.tokenizeSync(s,!1)];yield*Mt(()=>n.prefill(i));let a=performance.now(),p=0,l=[];for(;;){let{token:u,text:h,isStop:x}=n.produceSync();if(x)break;yield*Mt(()=>n.commit(u)),p++,l.push(h)}return{answer:l.join(""),tokenCount:p,timeMs:performance.now()-a}}function*Me(t,e,n){let r=yield*Bt.expect(),o=u=>r.send(u);yield*o({type:"query",query:t,warm:!!e.trunk});let s=zn(),i=n.reasoningMode==="flat"?_o:Mo,a=new Io({prompt:i,session:e,maxQuestions:10}),p=n.context?`Today's date: ${s}
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 uo=Ie(gn),po=Ie(yn),ho=Ie(bn),mo=Ie(xn),fo=Ie(kn),go=Ie(wn),yo=Tn,bo=Sn,xo=Cn;function ko(){return new En({budget:{context:{softLimit:2048,hardLimit:1024},time:{softLimit:24e4,hardLimit:36e4}},recovery:{prompt:mo},terminalTool:"report"})}var Pt=class extends En{onProduced(...e){let[,n]=e;return!n.toolCalls[0]&&n.content?{type:"free_text_report",content:n.content}:super.onProduced(...e)}};function Pn(t,e){return t.promptData?$e(yo,{...t.promptData(),...e}):t.name==="web"?$e(bo,e):ho.system}function In(){return new Date().toISOString().slice(0,10)}function An(){let t=performance.now();return()=>performance.now()-t}function Et(t){return{intent:"research",tasks:[{description:t}],clarifyQuestions:[],tokenCount:0,timeMs:0}}function*wo(t,e){let n=e.trunk;if(!n)throw new Error("runPassthrough: session has no trunk");let r=yield*At.expect(),o=r.getTurnSeparator(),{prompt:s}=r.formatChatSync(JSON.stringify([{role:"user",content:t}]),{addGenerationPrompt:!0,enableThinking:!1}),a=[...o,...r.tokenizeSync(s,!1)];yield*Rt(()=>n.prefill(a));let i=performance.now(),d=0,c=[];for(;;){let{token:u,text:m,isStop:w}=n.produceSync();if(w)break;yield*Rt(()=>n.commit(u)),d++,c.push(m)}return{answer:c.join(""),tokenCount:d,timeMs:performance.now()-i}}function*To(t,e,n){let r=yield*et.expect(),o=u=>r.send(u);yield*o({type:"query",query:t,warm:!!e.trunk});let s=In(),a=n.reasoningMode==="flat"?po:uo,i=new co({prompt:a,session:e,maxQuestions:10}),d=n.context?`Today's date: ${s}
627
605
 
628
- ${$e}`}).join(`
606
+ ${n.context}`:`Today's date: ${s}`,c=yield*i.execute({query:t,context:d});return yield*o({type:"plan",intent:c.intent,tasks:c.tasks,clarifyQuestions:c.clarifyQuestions,tokenCount:c.tokenCount,timeMs:c.timeMs}),c}function*Me(t,e,n,r,o){let s=yield*et.expect(),a=d=>s.send(d);yield*a({type:"plan:start",query:t,mode:o.reasoningMode});let i=yield*To(t,e,{reasoningMode:o.reasoningMode,context:o.context});if(i.intent==="clarify")return{type:"clarify",plan:i};if(i.intent==="passthrough"){if(!e.trunk){let c=Et(t);return o.onStart?.(),yield*We(t,c,e,n,r,{...o}),{type:"done"}}o.onStart?.();let d=yield*wo(t,e);return yield*a({type:"answer",text:d.answer}),yield*So(i,d,o.wallStartMs),{type:"done"}}return{type:"research_plan",plan:i}}function*We(t,e,n,r,o,s){if(e.intent!=="research")throw new Error(`runResearchPlan: expected plan.intent=research, got ${e.intent}`);let a=yield*et.expect(),i=B=>a.send(B),d=e.tasks,c=In();yield*i({type:"research:start",agentCount:d.length,mode:s.reasoningMode});let u=An();for(let B of r)yield*B.bind({reranker:o});let m=new Map(r.map(B=>[B,B.createScorer(t)])),w=r.flatMap(B=>B.tools),v=r[0],L=m.get(v),P=r.some(B=>B.name==="web"),p=r.some(B=>typeof B.promptData=="function"),g=$e(xo,{hasWeb:P,hasCorpus:p}),C=oo([...w,vn]),A=0,T=0,{answer:le,totalTokens:F,totalToolCalls:J,synthTokens:K}=yield*lo({parent:n.trunk??void 0,systemPrompt:g,toolsJson:C.toolsJson},function*(B){s.reasoningMode==="flat"&&(yield*i({type:"fanout:tasks",tasks:d}));let D=yield*ro({tools:[...w,vn],parent:B,terminalTool:"report",maxTurns:s.maxTurns,pruneOnReport:!0,policy:ko(),scorer:L,enableThinking:!0,orchestrate:s.reasoningMode==="flat"?ao(d.map((z,b)=>({content:Rn(z),systemPrompt:Pn(v,{maxTurns:s.maxTurns,agentCount:d.length,siblingTasks:d.filter((G,x)=>x!==b).map(G=>G.description),date:c,taskIndex:0}),seed:1e3+b}))):io(d,(z,b)=>({task:{content:Rn(z),systemPrompt:Pn(v,{maxTurns:s.maxTurns,agentCount:1,siblingTasks:[],date:c,taskIndex:b})},userContent:`Research task: ${z.description}`,beforeSpawn:function*(){yield*i({type:"spine:task",taskIndex:b,taskCount:d.length,description:z.description}),yield*i({type:"spine:source",taskIndex:b,source:v.name})},afterExtend:function*(G,x){yield*i({type:"spine:task:done",taskIndex:b,stageFindings:G,accumulated:x})}}))});if(T=u(),yield*i({type:"research:done",totalTokens:D.totalTokens,totalToolCalls:D.totalToolCalls,timeMs:T}),d.length===1)return{answer:D.agents[0]?.result?.trim()??"",totalTokens:D.totalTokens,totalToolCalls:D.totalToolCalls,synthTokens:0};yield*i({type:"synthesize:start"});let U=An(),Se=s.reasoningMode==="flat"?go:fo,Ee=s.reasoningMode==="flat"?D.agents.map((z,b)=>{let G=d[b]?.description??`task ${b+1}`,x=z.result?.trim()||"(no findings)";return`### Agent ${b+1}: ${G}
629
607
 
630
- `):void 0,gn={query:t,findings:so,agentCount:l.length},ke=yield*Eo({systemPrompt:Te(fn.system,gn),task:Te(fn.user,gn),parent:P,policy:new _t,maxTurns:s.maxTurns});Y=oo();let io=ke.result||"";return yield*p({type:"synthesize:done",agentId:ke.id,ppl:ke.branch.disposed?0:ke.branch.perplexity,tokenCount:ke.tokenCount,toolCallCount:ke.toolCallCount,timeMs:Y}),{answer:io,totalTokens:ne.totalTokens,totalToolCalls:ne.totalToolCalls,synthTokens:ke.tokenCount}});yield*p({type:"answer",text:Z});let C=Te(Fn.user,{agentFindings:Z||"(none)",sourcePassages:"(spine)",query:t}),Fe=at();yield*p({type:"verify:start",count:s.verifyCount,mode:s.reasoningMode});let de=yield*Dn({orchestrate:qn(Array.from({length:s.verifyCount},(P,ne)=>({content:C,systemPrompt:Fn.system,seed:2e3+ne})))});yield*p({type:"verify:done",count:s.verifyCount,timeMs:Fe()});let c=de.agents.map(P=>P.agent.rawOutput).map((P,ne)=>`Response ${ne+1}: ${P.trim()}`).join(`
608
+ ${x}`}).join(`
631
609
 
632
- `),m=at(),d=yield*So({systemPrompt:Un.system,task:Te(Un.user,{responses:c}),schema:{type:"object",properties:{converged:{type:"boolean"}},required:["converged"]}}),f=m(),w=null;try{w=JSON.parse(d.rawOutput).converged}catch{}yield*p({type:"eval:done",converged:w,tokenCount:d.tokenCount,sampleCount:s.verifyCount,timeMs:f}),Z&&(yield*Mt(()=>n.commitTurn(t,Z)));let Ue=(yield*Ot.expect())._storeKvPressure(),ot=Ue.nCtx||1,xe=[{label:"Plan",tokens:e.tokenCount,detail:e.intent,timeMs:e.timeMs},{label:"Research",tokens:te,detail:`${ie} tools`,timeMs:V},{label:"Synthesize",tokens:W,detail:"spine fork",timeMs:Y},{label:"Eval",tokens:d.tokenCount,detail:`converged: ${w?"yes":"no"}`,timeMs:f}];yield*p({type:"stats",timings:xe,ctxPct:Math.round(100*Ue.cellsUsed/ot),ctxPos:Ue.cellsUsed,ctxTotal:ot}),yield*p({type:"complete",data:{intent:e.intent,planTokens:e.tokenCount,agentTokens:te,synthTokens:W,evalTokens:d.tokenCount,converged:w,totalToolCalls:ie,agentCount:l.length,wallTimeMs:Math.round(performance.now()-i),planMs:Math.round(e.timeMs),researchMs:Math.round(V),synthMs:Math.round(Y),evalMs:Math.round(f)}})}function*Hn(t,e,n,r,o,s){let i=performance.now(),a=yield*Me(t,e,{reasoningMode:o.reasoningMode,context:s});return a.intent==="clarify"?{type:"clarify",questions:a.clarifyQuestions}:a.intent==="passthrough"?(yield*_e(t,e,a,i),{type:"done"}):(yield*Dt(t,a,e,n,r,o,i),{type:"done"})}import*as oe from"node:fs";import*as jn from"node:os";import*as ye from"node:path";var Yn={name:"reasoning.run",version:"0.1.0",description:"Local deep-research agent composer \u2014 runs on your machine, zero-config after the first query. Built on @lloyal-labs/*.",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:{"@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 zo=`reasoning.run/${Yn.version}`,qt=[{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}],Ho=qt.find(t=>t.kind==="llm"),Yo=qt.find(t=>t.kind==="reranker");function lt(){let t=process.env.XDG_CACHE_HOME||ye.join(jn.homedir(),".cache");return ye.join(t,"lloyal","models")}function We(t,e){if(!t){let r=e==="llm"?Ho:Yo;return{path:ye.join(lt(),r.filename),entry:r}}let n=qt.find(r=>r.id===t);return n?{path:ye.join(lt(),n.filename),entry:n}:{path:ye.resolve(t),entry:null}}async function Kn(t,e={}){let n=ye.join(lt(),t.filename);if(oe.existsSync(n))return n;oe.mkdirSync(lt(),{recursive:!0});let r=n+".partial";try{oe.unlinkSync(r)}catch{}let o=[];for(let s of t.urls)try{return await jo(s,r,n,t.sizeBytes,e)}catch(i){o.push(` ${s}: ${i.message}`);try{oe.unlinkSync(r)}catch{}}throw new Error(`Failed to download ${t.label} from any source:
610
+ `):void 0,Ue={query:t,findings:Ee,agentCount:d.length},ce=yield*so({systemPrompt:$e(Se.system,Ue),task:$e(Se.user,Ue),parent:B,policy:new Pt,maxTurns:s.maxTurns});return A=U(),yield*i({type:"synthesize:done",agentId:ce.id,ppl:ce.branch.disposed?0:ce.branch.perplexity,tokenCount:ce.tokenCount,toolCallCount:ce.toolCallCount,timeMs:A}),{answer:ce.result||"",totalTokens:D.totalTokens,totalToolCalls:D.totalToolCalls,synthTokens:ce.tokenCount}});yield*i({type:"answer",text:le}),le&&(yield*Rt(()=>n.commitTurn(t,le))),yield*Co({plan:e,researchTokens:F,researchToolCalls:J,researchTimeMs:T,synthTokens:K,synthTimeMs:A,wallStartMs:s.wallStartMs,send:i})}function*So(t,e,n){let r=yield*et.expect(),o=c=>r.send(c),a=(yield*At.expect())._storeKvPressure(),i=a.nCtx||1,d=[{label:"Plan",tokens:t.tokenCount,detail:t.intent,timeMs:t.timeMs},{label:"Passthrough",tokens:e.tokenCount,detail:"trunk stream",timeMs:e.timeMs}];yield*o({type:"stats",timings:d,ctxPct:Math.round(100*a.cellsUsed/i),ctxPos:a.cellsUsed,ctxTotal:i}),yield*o({type:"complete",data:{intent:t.intent,planTokens:t.tokenCount,passthroughTokens:e.tokenCount,wallTimeMs:Math.round(performance.now()-n),planMs:Math.round(t.timeMs),passthroughMs:Math.round(e.timeMs)}})}function*Co(t){let n=(yield*At.expect())._storeKvPressure(),r=n.nCtx||1,o=[{label:"Plan",tokens:t.plan.tokenCount,detail:t.plan.intent,timeMs:t.plan.timeMs},{label:"Research",tokens:t.researchTokens,detail:`${t.researchToolCalls} tools`,timeMs:t.researchTimeMs},{label:"Synthesize",tokens:t.synthTokens,detail:t.synthTokens>0?"spine fork":"skipped (single task)",timeMs:t.synthTimeMs}];yield*t.send({type:"stats",timings:o,ctxPct:Math.round(100*n.cellsUsed/r),ctxPos:n.cellsUsed,ctxTotal:r}),yield*t.send({type:"complete",data:{intent:t.plan.intent,planTokens:t.plan.tokenCount,agentTokens:t.researchTokens,synthTokens:t.synthTokens,totalToolCalls:t.researchToolCalls,agentCount:t.plan.tasks.length,wallTimeMs:Math.round(performance.now()-t.wallStartMs),planMs:Math.round(t.plan.timeMs),researchMs:Math.round(t.researchTimeMs),synthMs:Math.round(t.synthTimeMs)}})}import*as ue from"node:fs";import*as _n from"node:os";import*as Te from"node:path";var Mn={name:"reasoning.run",version:"0.1.2",description:"A private reasoner for your terminal. Direct conversation or grounded multi-agent research, GPU-native and fully local. No API keys, no inference servers.",bin:{"reasoning.run":"bin/run.js"},files:["bin","dist","LICENSE","README.md"],scripts:{build:"esbuild src/main.ts --bundle --platform=node --target=node22 --format=esm --packages=external --loader:.eta=text --outfile=dist/bundle.mjs --minify --legal-comments=none","build:watch":"esbuild src/main.ts --bundle --platform=node --target=node22 --format=esm --packages=external --loader:.eta=text --outfile=dist/bundle.mjs --watch",start:"npm run build && node bin/run.js",smoke:"tsx src/tui-ink/__bus-smoke.ts && tsx src/tui-ink/__reducer-smoke.ts && tsx src/tui-ink/__config-smoke.ts && tsx src/__download-smoke.ts && tsx src/__rundir-smoke.ts","smoke:visual":"tsx src/tui-ink/__visual-smoke.tsx",prepublishOnly:"npm run build"},dependencies:{"@inkjs/ui":"^2.0.0","@lloyal-labs/lloyal-agents":"^2.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:["reasoning","private-reasoner","deep-research","grounded-reasoning","multi-agent","agents","rag","local-llm","offline","on-device","gpu","llama.cpp","cli","tui"],repository:{type:"git",url:"git+https://github.com/lloyal-ai/reasoning-run.git"},license:"SEE LICENSE IN LICENSE"};var Ro=`reasoning.run/${Mn.version}`,It=[{id:"qwen3.5-4b-q4",label:"Qwen3.5-4B Q4_K_M",kind:"llm",urls:["https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/resolve/main/Qwen3.5-4B-Q4_K_M.gguf","https://models.lloyal.ai/Qwen3.5-4B-Q4_K_M.gguf"],filename:"Qwen3.5-4B-Q4_K_M.gguf",sizeBytes:26e8,recommendedNCtx:32768},{id:"qwen3-reranker-0.6b-q8",label:"Qwen3-Reranker 0.6B Q8_0",kind:"reranker",urls:["https://huggingface.co/ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/resolve/main/qwen3-reranker-0.6b-q8_0.gguf","https://models.lloyal.ai/qwen3-reranker-0.6b-q8_0.gguf"],filename:"qwen3-reranker-0.6b-q8_0.gguf",sizeBytes:63e7}],Po=It.find(t=>t.kind==="llm"),Ao=It.find(t=>t.kind==="reranker");function tt(){let t=process.env.XDG_CACHE_HOME||Te.join(_n.homedir(),".cache");return Te.join(t,"lloyal","models")}function ye(t,e){if(!t){let r=e==="llm"?Po:Ao;return{path:Te.join(tt(),r.filename),entry:r}}let n=It.find(r=>r.id===t);return n?{path:Te.join(tt(),n.filename),entry:n}:{path:Te.resolve(t),entry:null}}async function On(t,e={}){let n=Te.join(tt(),t.filename);if(ue.existsSync(n))return n;ue.mkdirSync(tt(),{recursive:!0});let r=n+".partial";try{ue.unlinkSync(r)}catch{}let o=[];for(let s of t.urls)try{return await Eo(s,r,n,t.sizeBytes,e)}catch(a){o.push(` ${s}: ${a.message}`);try{ue.unlinkSync(r)}catch{}}throw new Error(`Failed to download ${t.label} from any source:
633
611
  ${o.join(`
634
- `)}`)}async function jo(t,e,n,r,o){let s=await fetch(t,{redirect:"follow",headers:{"User-Agent":zo}});if(!s.ok||!s.body)throw new Error(`HTTP ${s.status} ${s.statusText}`);let i=Number(s.headers.get("content-length")??r),a=oe.createWriteStream(e),p=0,l=0,u=(h=!1)=>{if(!o.onProgress)return;let x=Date.now();!h&&x-l<200||(l=x,o.onProgress(p,i,t))};try{for await(let h of s.body)a.write(h),p+=h.byteLength,u()}catch(h){throw a.destroy(),h}return await new Promise((h,x)=>{a.end(k=>k?x(k):h())}),oe.renameSync(e,n),u(!0),n}import*as ze from"node:fs";import*as He from"node:path";var ct=class{currentDir=null;inResearch=!1;spawnOrdinal=0;agentToOrdinal=new Map;taskByOrdinal=new Map;lastAnswer=null;query=null;mode=null;startedAt=null;synthStats=null;start(e){let n=new Date().toISOString().replace(/[:.]/g,"-").replace("Z","");return this.currentDir=He.resolve(e.outputDir,n),ze.mkdirSync(this.currentDir,{recursive:!0}),this.inResearch=!1,this.spawnOrdinal=0,this.agentToOrdinal.clear(),this.taskByOrdinal.clear(),this.lastAnswer=null,this.query=e.query,this.mode=e.mode,this.startedAt=Date.now(),this.synthStats=null,this.currentDir}handle(e){if(this.currentDir)switch(e.type){case"research:start":this.inResearch=!0;break;case"research:done":this.inResearch=!1;break;case"fanout:tasks":e.tasks.forEach((n,r)=>this.taskByOrdinal.set(r+1,n.description));break;case"spine:task":this.taskByOrdinal.set(e.taskIndex+1,e.description);break;case"agent:spawn":this.inResearch&&!this.agentToOrdinal.has(e.agentId)&&(this.spawnOrdinal+=1,this.agentToOrdinal.set(e.agentId,this.spawnOrdinal));break;case"agent: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}
612
+ `)}`)}async function Eo(t,e,n,r,o){let s=await fetch(t,{redirect:"follow",headers:{"User-Agent":Ro}});if(!s.ok||!s.body)throw new Error(`HTTP ${s.status} ${s.statusText}`);let a=Number(s.headers.get("content-length")??r),i=ue.createWriteStream(e),d=0,c=0,u=(m=!1)=>{if(!o.onProgress)return;let w=Date.now();!m&&w-c<200||(c=w,o.onProgress(d,a,t))};try{for await(let m of s.body)i.write(m),d+=m.byteLength,u()}catch(m){throw i.destroy(),m}return await new Promise((m,w)=>{i.end(v=>v?w(v):m())}),ue.renameSync(e,n),u(!0),n}import*as ze from"node:fs";import*as He from"node:path";var nt=class{currentDir=null;inResearch=!1;spawnOrdinal=0;agentToOrdinal=new Map;taskByOrdinal=new Map;lastAnswer=null;query=null;mode=null;startedAt=null;synthStats=null;start(e){let n=new Date().toISOString().replace(/[:.]/g,"-").replace("Z","");return this.currentDir=He.resolve(e.outputDir,n),ze.mkdirSync(this.currentDir,{recursive:!0}),this.inResearch=!1,this.spawnOrdinal=0,this.agentToOrdinal.clear(),this.taskByOrdinal.clear(),this.lastAnswer=null,this.query=e.query,this.mode=e.mode,this.startedAt=Date.now(),this.synthStats=null,this.currentDir}handle(e){if(this.currentDir)switch(e.type){case"research:start":this.inResearch=!0;break;case"research:done":this.inResearch=!1;break;case"fanout:tasks":e.tasks.forEach((n,r)=>this.taskByOrdinal.set(r+1,n.description));break;case"spine:task":this.taskByOrdinal.set(e.taskIndex+1,e.description);break;case"agent:spawn":this.inResearch&&!this.agentToOrdinal.has(e.agentId)&&(this.spawnOrdinal+=1,this.agentToOrdinal.set(e.agentId,this.spawnOrdinal));break;case"agent: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
618
  `;ze.writeFileSync(He.join(this.currentDir,`annexure-${e}.md`),o+n.trimEnd()+`
641
- `,"utf8")}finish(){if(this.currentDir&&this.lastAnswer&&this.query){let e=this.startedAt?Date.now()-this.startedAt:0,r=[...this.agentToOrdinal.values()].sort((p,l)=>p-l).map(p=>{let l=this.taskByOrdinal.get(p);return`- [Annexure ${p}](./annexure-${p}.md)${l?` \u2014 ${l}`:""}`}).join(`
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`,i=r?`
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`,a=r?`
643
621
  ---
644
622
 
645
623
  ## Annexures
646
624
 
647
625
  ${r}
648
- `:"",a=`# ${this.query}
626
+ `:"",i=`# ${this.query}
649
627
 
650
628
  ${s}
651
629
 
652
630
  ${this.lastAnswer.trim()}
653
- ${i}`;ze.writeFileSync(He.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 di=ue.join(process.cwd(),"harness.json"),{values:B,positionals:pi}=Js({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}),me=B["reasoning-mode"];me!==void 0&&me!=="flat"&&me!=="deep"&&(process.stderr.write(`Invalid --reasoning-mode: ${me}. Expected "flat" or "deep".
654
- `),process.exit(1));var et=pi[0]||void 0,hn=B.jsonl,no=B.verbose,tt=B["output-dir"],he=B.query,ce=B.config??di,nt=B["n-ctx"];nt!==void 0&&!/^\d+$/.test(nt)&&(process.stderr.write(`Invalid --n-ctx: ${nt}. Expected a positive integer.
655
- `),process.exit(1));var ro=nt!==void 0?parseInt(nt,10):void 0,mn=Pe(ce,{modelPath:et,reranker:B.reranker,corpusPath:B.corpus,reasoningMode:me,nCtx:ro,outputDir:tt}),v=mn.config,be=mn.origin,hi=B["findings-budget"]?parseInt(B["findings-budget"],10):void 0,un=We(v.model.path,"llm"),dn=We(v.model.reranker,"reranker"),Zr=un.path,eo=dn.path,mi=v.model.nCtx??32768;hn&&bn(!0);no&&xn(!0);var fi=!no&&!hn;if(fi)try{N.closeSync(2),N.openSync(process.platform==="win32"?"\\\\.\\NUL":"/dev/null","w")}catch{}var gi=3,yi=10,pn=new Map;function*to(t,e){let n=pn.get(t);if(n)return n;let{cwd:r,pattern:o}=ci(t),s=o??"**/*.{md,mdx}",i=ue.join(r,".gitignore"),a=N.existsSync(i)?ui().add(N.readFileSync(i,"utf8")):null,p=N.globSync(s,{cwd:r}),l=(a?p.filter(k=>!a.ignores(k)):p).sort();l.length===0&&(process.stderr.write(`Error: no .md(x) files matched: ${r}/${s}
656
- `),process.exit(1)),e.send({type:"weights:label",label:`Indexing corpus (${l.length} files)\u2026`});let u=[];for(let k=0;k<l.length;k++){let M=l[k];e.send({type:"weights:label",label:`Indexing: ${M} (${k+1}/${l.length})`}),yield*Le(()=>new Promise(H=>{setImmediate(()=>{try{u.push({name:M,content:N.readFileSync(ue.join(r,M),"utf8")})}catch{}H()})}))}e.send({type:"weights:label",label:"Chunking corpus\u2026"}),yield*Le(()=>new Promise(k=>setImmediate(k)));let h=li(u),x={resources:u,chunks:h};return pn.set(t,x),x}function Ze(t){let e=[];if(t.sources.corpusPath){let n=pn.get(t.sources.corpusPath);n&&e.push(new ai(n.resources,n.chunks,{grep:{maxResults:50,lineMaxChars:200},readFile:{defaultMaxLines:100}}))}return t.sources.tavilyKey&&e.push(new ii(new oi(t.sources.tavilyKey),{topN:5,fetch:{maxChars:3e3,topK:5,timeout:1e4,tokenBudget:1200}})),e}function ln(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(`
657
- `)}var cn=t=>t instanceof Error?t.message:String(t),bi=t=>t instanceof Error?t.stack??t.message:String(t);Xs(function*(){let t=ue.basename(Zr).replace(/-Q\w+\.gguf$/,""),e=ue.basename(eo).replace(/-q\w+\.gguf$/i,""),n=Et&&!hn;n||(st(),st(`${At.bold} Deep Research${At.reset}`),st());let r=vn(),o=Zs(),s=[un,dn].filter(c=>c.entry!==null&&!N.existsSync(c.path)).map(c=>({id:c.entry.id,label:c.entry.label,sizeBytes:c.entry.sizeBytes})),i=null;if(n){let c=yield*Le(()=>Promise.resolve().then(()=>(Xr(),Jr))),m=[{type:"config:loaded",config:v,origin:be,path:mn.path}];s.length>0&&m.push({type:"download:plan",entries:s}),i=c.render(r,d=>o.send(d),m),yield*an(()=>{i?.unmount()})}else r.subscribe(c=>{kn(c.type,c)});function*a(c){if(N.existsSync(c.path))return c.path;if(!c.entry)throw new Error(`Model not found: ${c.path}. Pass --model <path> or use /model <path> to set a local .gguf file.`);let m=c.entry;return r.send({type:"download:start",id:m.id,label:m.label,sizeBytes:m.sizeBytes}),yield*Le(()=>Kn(m,{onProgress:(d,f,w)=>{r.send({type:"download:progress",id:m.id,got:d,total:f,url:w})}})),r.send({type:"download:complete",id:m.id}),c.path}function p(c){let m=c.filter(d=>d.entry!==null&&!N.existsSync(d.path)).map(d=>({id:d.entry.id,label:d.entry.label,sizeBytes:d.entry.sizeBytes}));m.length>0&&r.send({type:"download:plan",entries:m})}function*l(){for(let c of yield*Ee(o)){if(c.type==="quit"||c.type==="set_model_path"||c.type==="set_reranker_path")return yield*Ee.next(),c;yield*Ee.next()}return{type:"quit"}}let u=un,h=Zr,x=t,k=dn,M=eo,H=e,R=null,g=null,Q=!0;for(;R===null||g===null;){let c="llm";try{Q||p([u,k]),Q=!1,c="llm",yield*a(u),c="reranker",yield*a(k),c="llm",r.send({type:"weights:start",label:`Loading ${x}\u2026`}),R=yield*Le(()=>ti({modelPath:h,nCtx:mi,nSeqMax:64,typeK:"q4_0",typeV:"q4_0"})),c="reranker",r.send({type:"weights:label",label:`Loading ${H}\u2026`}),g=yield*Le(()=>si(M,{nSeqMax:8,nCtx:16384}))}catch(m){if(R){try{R.dispose?.()}catch{}R=null}g=null,r.send({type:"boot:error",kind:c,message:cn(m)});let d=yield*l();d.type==="quit"&&(i?.unmount(),process.exit(0)),d.type==="set_model_path"?(Ie({model:{path:d.path}},ce),u=We(d.path,"llm"),h=u.path,x=u.entry?.label??ue.basename(h)):(Ie({model:{reranker:d.path}},ce),k=We(d.path,"reranker"),M=k.path,H=k.entry?.label??ue.basename(M));let f=Pe(ce,{modelPath:d.type==="set_model_path"?d.path:et,reranker:d.type==="set_reranker_path"?d.path:B.reranker,corpusPath:B.corpus,reasoningMode:me,outputDir:tt,nCtx:ro});v=f.config,be=f.origin}}yield*an(()=>{g.dispose()}),r.send({type:"weights:done"});let L=fe(v.sources.outputDir||process.cwd());N.mkdirSync(L,{recursive:!0});let Y=new Date().toISOString().replace(/[:.]/g,"-").replace("Z",""),V=ue.join(L,`trace-${Y}.jsonl`),Z=N.openSync(V,"w"),te=new ri(Z);yield*an(()=>{te.flush();try{N.closeSync(Z)}catch{}});let ie=new ct,{session:W,events:C}=yield*ni(R,{traceWriter:te});if(yield*ei(function*(){for(let c of yield*Ee(C))ie.handle(c),r.send(c),yield*Ee.next()}),v.sources.corpusPath){let c=yield*to(v.sources.corpusPath,r);r.send({type:"corpus:indexed",corpusPath:v.sources.corpusPath,fileCount:c.resources.length,chunkCount:c.chunks.length})}r.send({type:"ui:composer"});let Fe={verifyCount:gi,maxTurns:yi,findingsMaxChars:hi,reasoningMode:v.defaults.reasoningMode};function de(c,m){let d=v.sources.outputDir??process.cwd();ie.start({outputDir:d,query:c,mode:m})}if(!n){he||(process.stderr.write(`Non-TTY mode requires --query.
658
- `),process.exit(2));let c=Ze(v);c.length===0&&(process.stderr.write(`No source configured. Set TAVILY_API_KEY, pass --corpus <dir>, or store one in harness.json.
659
- `),process.exit(2)),de(he,v.defaults.reasoningMode),yield*Hn(he,W,c,g,Fe);return}let b=null;if(he){let c=v.defaults.reasoningMode,m=performance.now();yield*C.send({type:"plan:start",query:he,mode:c});let d=yield*Me(he,W,{reasoningMode:c});d.intent==="passthrough"?(de(he,c),yield*_e(he,W,d,m),yield*C.send({type:"ui:composer"})):(b={plan:d,query:he,mode:c,wallStartMs:m},yield*C.send({type:"ui:plan_review"}))}for(let c of yield*Ee(o))try{if(c.type==="quit")break;if(c.type==="set_tavily_key"){v={...v,sources:{...v.sources,tavilyKey:c.key}};let m=Ie({sources:{tavilyKey:c.key}},ce),d=Pe(ce,{modelPath:et,reranker:B.reranker,corpusPath:B.corpus,reasoningMode:me,outputDir:tt});v=d.config,be=d.origin,yield*C.send({type:"config:updated",config:v,origin:be,savedTo:m.path,gitignored:m.gitignored,skipped:m.skipped})}else if(c.type==="set_output_dir"){let m=c.path?fe(c.path):"",d=Ie({sources:{outputDir:m}},ce),f=Pe(ce,{modelPath:et,reranker:B.reranker,corpusPath:B.corpus,reasoningMode:me,outputDir:tt});v=f.config,be=f.origin,yield*C.send({type:"config:updated",config:v,origin:be,savedTo:d.path,gitignored:d.gitignored,skipped:d.skipped})}else if(c.type==="set_corpus_path"){let m=c.path?fe(c.path):"",d=Ie({sources:{corpusPath:m}},ce),f=Pe(ce,{modelPath:et,reranker:B.reranker,corpusPath:B.corpus,reasoningMode:me,outputDir:tt});if(v=f.config,be=f.origin,yield*C.send({type:"config:updated",config:v,origin:be,savedTo:d.path,gitignored:d.gitignored,skipped:d.skipped}),v.sources.corpusPath){r.send({type:"weights:start",label:"Indexing corpus\u2026"});let w=yield*to(v.sources.corpusPath,r);r.send({type:"corpus:indexed",corpusPath:v.sources.corpusPath,fileCount:w.resources.length,chunkCount:w.chunks.length}),r.send({type:"weights:done"}),yield*C.send({type:"ui:composer"})}}else if(c.type==="submit_query"){let m=performance.now(),d=Ze(v);if(d.length===0){yield*C.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."});continue}let f=ln(d);yield*C.send({type:"plan:start",query:c.query,mode:c.mode});let w=yield*Me(c.query,W,{reasoningMode:c.mode,context:f});w.intent==="passthrough"?(de(c.query,c.mode),yield*_e(c.query,W,w,m),yield*C.send({type:"ui:composer"})):w.intent==="clarify"?b={plan:w,query:c.query,mode:c.mode,wallStartMs:m}:(b={plan:w,query:c.query,mode:c.mode,wallStartMs:m},yield*C.send({type:"ui:plan_review"}))}else if(c.type==="submit_clarification"&&b){let{query:m,plan:d,mode:f,wallStartMs:w}=b,rt=Ze(v),Ue=["Prior clarification exchange:",...d.clarifyQuestions.map((P,ne)=>`(${ne+1}) ${P}`),"",`User response: ${c.answer}`,"","Use this exchange to proceed with research if possible."].join(`
660
- `),ot=[ln(rt),Ue].filter(Boolean).join(`
661
-
662
- `);yield*C.send({type:"plan:start",query:m,mode:f});let xe=yield*Me(m,W,{reasoningMode:f,context:ot});xe.intent==="passthrough"?(de(m,f),yield*_e(m,W,xe,w),b=null,yield*C.send({type:"ui:composer"})):xe.intent==="clarify"?b={plan:xe,query:m,mode:f,wallStartMs:w}:(b={plan:xe,query:m,mode:f,wallStartMs:w},yield*C.send({type:"ui:plan_review"}))}else if(c.type==="change_mode"&&b){let m=Ze(v),d=ln(m);yield*C.send({type:"plan:start",query:b.query,mode:c.mode});let f=yield*Me(b.query,W,{reasoningMode:c.mode,context:d});f.intent==="passthrough"?(de(b.query,c.mode),yield*_e(b.query,W,f,b.wallStartMs),b=null,yield*C.send({type:"ui:composer"})):f.intent==="clarify"?b={...b,plan:f,mode:c.mode}:(b={...b,plan:f,mode:c.mode},yield*C.send({type:"ui:plan_review"}))}else if(c.type==="accept_plan"&&b){if(b.plan.intent==="clarify"){b=null,yield*C.send({type:"ui:composer"});continue}let m=Ze(v);if(m.length===0){yield*C.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."}),b=null;continue}de(b.query,b.mode),yield*Dt(b.query,b.plan,W,m,g,{...Fe,reasoningMode:b.mode},b.wallStartMs),b=null,yield*C.send({type:"ui:composer"})}else c.type==="cancel_plan"?(b=null,yield*C.send({type:"ui:composer"})):c.type==="edit_plan"&&(b=null,yield*C.send({type:"ui:composer",prefill:c.query}))}catch(m){b=null,yield*C.send({type:"ui:error",message:cn(m)})}finally{yield*Ee.next()}}).catch(t=>{process.stderr.write(`Error: ${cn(t)}
663
- ${bi(t)}
631
+ ${a}`;ze.writeFileSync(He.join(this.currentDir,"report.md"),i,"utf8")}this.reset()}reset(){this.currentDir=null,this.inResearch=!1,this.spawnOrdinal=0,this.agentToOrdinal.clear(),this.taskByOrdinal.clear(),this.lastAnswer=null,this.query=null,this.mode=null,this.startedAt=null,this.synthStats=null}};var Hs=ge.join(process.cwd(),"harness.json"),{values:j,positionals:Ys}=Ms({args:process.argv.slice(2),options:{query:{type:"string"},reranker:{type:"string"},corpus:{type:"string"},config:{type:"string"},"findings-budget":{type:"string"},"reasoning-mode":{type:"string"},"n-ctx":{type:"string"},"output-dir":{type:"string"},jsonl:{type:"boolean",default:!1},verbose:{type:"boolean",default:!1}},allowPositionals:!0}),fe=j["reasoning-mode"];fe!==void 0&&fe!=="flat"&&fe!=="deep"&&(process.stderr.write(`Invalid --reasoning-mode: ${fe}. Expected "flat" or "deep".
632
+ `),process.exit(1));var Dr=Ys[0]||void 0,an=j.jsonl,qr=j.verbose,Le=j["output-dir"],he=j.query,ie=j.config??Hs,Qe=j["n-ctx"];Qe!==void 0&&!/^\d+$/.test(Qe)&&(process.stderr.write(`Invalid --n-ctx: ${Qe}. Expected a positive integer.
633
+ `),process.exit(1));var on=Qe!==void 0?parseInt(Qe,10):void 0,ln=Ce(ie,{modelPath:Dr,reranker:j.reranker,corpusPath:j.corpus,reasoningMode:fe,nCtx:on,outputDir:Le}),S=ln.config,me=ln.origin,js=j["findings-budget"]?parseInt(j["findings-budget"],10):void 0,Nr=ye(S.model.path,"llm"),Lr=ye(S.model.reranker,"reranker"),Ll=Nr.path,Fl=Lr.path,Ul=S.model.nCtx??32768;an&&un(!0);qr&&dn(!0);var Ks=!qr&&!an;if(Ks)try{H.closeSync(2),H.openSync(process.platform==="win32"?"\\\\.\\NUL":"/dev/null","w")}catch{}var Gs=10,sn=new Map;function*Br(t,e){let n=sn.get(t);if(n)return n;let{cwd:r,pattern:o}=Ws(t),s=o??"**/*.{md,mdx}",a=ge.join(r,".gitignore"),i=H.existsSync(a)?zs().add(H.readFileSync(a,"utf8")):null,d=H.globSync(s,{cwd:r}),c=(i?d.filter(v=>!i.ignores(v)):d).sort();if(c.length===0)throw new Error(`No .md(x) files at ${r}${o?` matching ${o}`:""}`);e.send({type:"weights:label",label:`Indexing corpus (${c.length} files)\u2026`});let u=[];for(let v=0;v<c.length;v++){let L=c[v];e.send({type:"weights:label",label:`Indexing: ${L} (${v+1}/${c.length})`}),yield*Fe(()=>new Promise(P=>{setImmediate(()=>{try{u.push({name:L,content:H.readFileSync(ge.join(r,L),"utf8")})}catch{}P()})}))}e.send({type:"weights:label",label:"Chunking corpus\u2026"}),yield*Fe(()=>new Promise(v=>setImmediate(v)));let m=$s(u),w={resources:u,chunks:m};return sn.set(t,w),w}function Ne(t){let e=[];if(t.sources.corpusPath){let n=sn.get(t.sources.corpusPath);n&&e.push(new Us(n.resources,n.chunks,{grep:{maxResults:50,lineMaxChars:200},readFile:{defaultMaxLines:100}}))}return t.sources.tavilyKey&&e.push(new Fs(new Ns(t.sources.tavilyKey),{topN:5,fetch:{maxChars:3e3,topK:5,timeout:1e4,tokenBudget:1200}})),e}function nn(t){if(t.length===0)return"";let e=["Available research sources:"],n=!1;for(let r of t){let o=r;if(typeof o.promptData=="function"){let s=o.promptData();e.push("","## Local corpus"),e.push("Files and top-level topics (full-text searchable via grep/read/search tools):"),s.toc&&e.push(s.toc)}else r.name==="web"&&(n=!0)}return n&&(e.push("","## Web search"),e.push("web search is available for live web queries (web_search + fetch_page tools).")),e.join(`
634
+ `)}var rn=t=>t instanceof Error?t.message:String(t),Qs=t=>t instanceof Error?t.stack??t.message:String(t);_s(function*(){let t=Tt&&!an;t||(Je(),Je(`${St.bold} Deep Research${St.reset}`),Je());let e=fn(),n=Os(),r=Dr,o=j.reranker,s=[Nr,Lr].filter(p=>p.entry!==null&&!H.existsSync(p.path)).map(p=>({id:p.entry.id,label:p.entry.label,sizeBytes:p.entry.sizeBytes})),a=null;if(t){let p=yield*Fe(()=>Promise.resolve().then(()=>(_r(),Mr))),g=[{type:"config:loaded",config:S,origin:me,path:ln.path}];s.length>0&&g.push({type:"download:plan",entries:s}),a=p.render(e,C=>n.send(C),g),yield*kt(()=>{a?.unmount()})}else e.subscribe(p=>{pn(p.type,p)});let i=ke(S.sources.outputDir||process.cwd());H.mkdirSync(i,{recursive:!0});let d=new Date().toISOString().replace(/[:.]/g,"-").replace("Z",""),c=ge.join(i,`trace-${d}.jsonl`),u=H.openSync(c,"w"),m=new qs(u);yield*kt(()=>{m.flush();try{H.closeSync(u)}catch{}});function*w(p){if(H.existsSync(p.path))return p.path;if(!p.entry)throw new Error(`Model not found: ${p.path}. Pass --model <path> or use /model <path> to set a local .gguf file.`);let g=p.entry;return e.send({type:"download:start",id:g.id,label:g.label,sizeBytes:g.sizeBytes}),yield*Fe(()=>On(g,{onProgress:(C,A,T)=>{e.send({type:"download:progress",id:g.id,got:C,total:A,url:T})}})),e.send({type:"download:complete",id:g.id}),p.path}function v(p){let g=p.filter(C=>C.entry!==null&&!H.existsSync(C.path)).map(C=>({id:C.entry.id,label:C.entry.label,sizeBytes:C.entry.sizeBytes}));g.length>0&&e.send({type:"download:plan",entries:g})}function*L(){for(let p of yield*Ae(n)){if(p.type==="quit"||p.type==="set_model_path"||p.type==="set_reranker_path")return yield*Ae.next(),p;yield*Ae.next()}return{type:"quit"}}let P=0;for(;;){if(P>0){let A=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le,nCtx:on});S=A.config,me=A.origin,e.send({type:"config:loaded",config:S,origin:me,path:A.path});let T=ye(S.model.path,"llm"),le=ye(S.model.reranker,"reranker");v([T,le])}let p=P;if((yield*yield*Or(function*(){let A=ye(S.model.path,"llm"),T=A.path,le=A.entry?.label??ge.basename(T).replace(/-Q\w+\.gguf$/,""),F=ye(S.model.reranker,"reranker"),J=F.path,K=F.entry?.label??ge.basename(J).replace(/-q\w+\.gguf$/i,""),B=S.model.nCtx??32768,D=null,U=null,Se=p===0;for(;D===null||U===null;){let l="llm";try{Se||v([A,F]),Se=!1,l="llm",yield*w(A),l="reranker",yield*w(F),l="llm",e.send({type:"weights:start",label:`Loading ${le}\u2026`}),D=yield*Fe(()=>Bs({modelPath:T,nCtx:B,nSeqMax:64,typeK:"q4_0",typeV:"q4_0"})),l="reranker",e.send({type:"weights:label",label:`Loading ${K}\u2026`}),U=yield*Fe(()=>Ls(J,{nSeqMax:8,nCtx:16384}))}catch(f){if(D){try{D.dispose?.()}catch{}D=null}U=null,e.send({type:"boot:error",kind:l,message:rn(f)});let y=yield*L();if(y.type==="quit")return"quit";y.type==="set_model_path"?(we({model:{path:y.path}},ie),r=void 0,A=ye(y.path,"llm"),T=A.path,le=A.entry?.label??ge.basename(T)):(we({model:{reranker:y.path}},ie),o=void 0,F=ye(y.path,"reranker"),J=F.path,K=F.entry?.label??ge.basename(J));let I=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le,nCtx:on});S=I.config,me=I.origin}}let Ee=D,Ue=U;yield*kt(()=>{Ue.dispose()}),yield*kt(()=>{try{Ee.dispose?.()}catch{}}),e.send({type:"weights:done"});let ce=new nt,{session:z,events:b}=yield*Ds(Ee,{traceWriter:m});if(yield*Or(function*(){for(let l of yield*Ae(b))ce.handle(l),e.send(l),yield*Ae.next()}),S.sources.corpusPath)try{let l=yield*Br(S.sources.corpusPath,e);e.send({type:"corpus:indexed",corpusPath:S.sources.corpusPath,fileCount:l.resources.length,chunkCount:l.chunks.length})}catch(l){e.send({type:"ui:error",message:`Corpus disabled: ${l.message}. Use /scan to fix.`})}e.send({type:"ui:composer"});let G={maxTurns:Gs,findingsMaxChars:js,reasoningMode:S.defaults.reasoningMode};function x(l,f){let y=S.sources.outputDir??process.cwd();ce.start({outputDir:y,query:l,mode:f})}if(!t){he||(process.stderr.write(`Non-TTY mode requires --query.
635
+ `),process.exit(2));let l=Ne(S);l.length===0&&(process.stderr.write(`No source configured. Set TAVILY_API_KEY, pass --corpus <dir>, or store one in harness.json.
636
+ `),process.exit(2));let f=performance.now(),y=yield*Me(he,z,l,U,{...G,wallStartMs:f,onStart:()=>x(he,S.defaults.reasoningMode)});return y.type==="clarify"&&(process.stderr.write(`Planner asked clarifying questions; non-TTY mode can't answer. Aborting.
637
+ `),process.exit(2)),y.type==="research_plan"&&(x(he,S.defaults.reasoningMode),yield*We(he,y.plan,z,l,U,{...G,wallStartMs:f})),"quit"}let h=null;if(p===0&&he){let l=S.defaults.reasoningMode,f=performance.now(),y=Ne(S),I=yield*Me(he,z,y,U,{...G,reasoningMode:l,wallStartMs:f,onStart:()=>x(he,l)});I.type==="research_plan"?(h={plan:I.plan,query:he,mode:l,wallStartMs:f},yield*b.send({type:"ui:plan_review"})):I.type==="clarify"?h={plan:I.plan,query:he,mode:l,wallStartMs:f}:yield*b.send({type:"ui:composer"})}for(let l of yield*Ae(n))try{if(l.type==="quit")return"quit";if(l.type==="set_model_path")return we({model:{path:l.path}},ie),r=void 0,"restart";if(l.type==="set_reranker_path")return we({model:{reranker:l.path}},ie),o=void 0,"restart";if(l.type==="set_tavily_key"){S={...S,sources:{...S.sources,tavilyKey:l.key}};let f=we({sources:{tavilyKey:l.key}},ie),y=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le});S=y.config,me=y.origin,yield*b.send({type:"config:updated",config:S,origin:me,savedTo:f.path,gitignored:f.gitignored,skipped:f.skipped})}else if(l.type==="set_output_dir"){let f=l.path?ke(l.path):"",y=we({sources:{outputDir:f}},ie),I=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le});S=I.config,me=I.origin,yield*b.send({type:"config:updated",config:S,origin:me,savedTo:y.path,gitignored:y.gitignored,skipped:y.skipped})}else if(l.type==="set_corpus_path"){let f=l.path?ke(l.path):"";if(f){e.send({type:"weights:start",label:"Indexing corpus\u2026"});let te;try{te=yield*Br(f,e)}catch(Ve){e.send({type:"weights:done"}),yield*b.send({type:"ui:error",message:`Cannot use ${f}: ${Ve.message}`});continue}e.send({type:"corpus:indexed",corpusPath:f,fileCount:te.resources.length,chunkCount:te.chunks.length}),e.send({type:"weights:done"})}let y=we({sources:{corpusPath:f}},ie),I=Ce(ie,{modelPath:r,reranker:o,corpusPath:j.corpus,reasoningMode:fe,outputDir:Le});S=I.config,me=I.origin,yield*b.send({type:"config:updated",config:S,origin:me,savedTo:y.path,gitignored:y.gitignored,skipped:y.skipped}),f&&(yield*b.send({type:"ui:composer"}))}else if(l.type==="submit_query"){let f=Ne(S);if(f.length===0){yield*b.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."});continue}let y=performance.now();if(l.skipPlanner){let te=Et(l.query);yield*b.send({type:"plan:start",query:l.query,mode:l.mode}),yield*b.send({type:"query",query:l.query,warm:!!z.trunk}),yield*b.send({type:"plan",intent:te.intent,tasks:te.tasks,clarifyQuestions:te.clarifyQuestions,tokenCount:te.tokenCount,timeMs:te.timeMs}),x(l.query,l.mode),yield*We(l.query,te,z,f,U,{...G,reasoningMode:l.mode,wallStartMs:y}),yield*b.send({type:"ui:composer"});continue}let I=yield*Me(l.query,z,f,U,{...G,reasoningMode:l.mode,context:nn(f),wallStartMs:y,onStart:()=>x(l.query,l.mode)});I.type==="research_plan"?(h={plan:I.plan,query:l.query,mode:l.mode,wallStartMs:y},yield*b.send({type:"ui:plan_review"})):I.type==="clarify"?h={plan:I.plan,query:l.query,mode:l.mode,wallStartMs:y}:yield*b.send({type:"ui:composer"})}else if(l.type==="submit_clarification"&&h){let{query:f,plan:y,mode:I,wallStartMs:te}=h,Ve=Ne(S),Fr=["Prior clarification exchange:",...y.clarifyQuestions.map((Ur,$r)=>`(${$r+1}) ${Ur}`),"",`User response: ${l.answer}`,"","Use this exchange to proceed with research if possible."].join(`
638
+ `),Xe=yield*Me(f,z,Ve,U,{...G,reasoningMode:I,context:[nn(Ve),Fr].filter(Boolean).join(`
639
+
640
+ `),wallStartMs:te,onStart:()=>x(f,I)});Xe.type==="research_plan"?(h={plan:Xe.plan,query:f,mode:I,wallStartMs:te},yield*b.send({type:"ui:plan_review"})):Xe.type==="clarify"?h={plan:Xe.plan,query:f,mode:I,wallStartMs:te}:(h=null,yield*b.send({type:"ui:composer"}))}else if(l.type==="change_mode"&&h){let f=Ne(S),y=yield*Me(h.query,z,f,U,{...G,reasoningMode:l.mode,context:nn(f),wallStartMs:h.wallStartMs,onStart:()=>x(h.query,l.mode)});y.type==="research_plan"?(h={...h,plan:y.plan,mode:l.mode},yield*b.send({type:"ui:plan_review"})):y.type==="clarify"?h={...h,plan:y.plan,mode:l.mode}:(h=null,yield*b.send({type:"ui:composer"}))}else if(l.type==="accept_plan"&&h){if(h.plan.intent==="clarify"){h=null,yield*b.send({type:"ui:composer"});continue}let f=Ne(S);if(f.length===0){yield*b.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."}),h=null;continue}x(h.query,h.mode),yield*We(h.query,h.plan,z,f,U,{...G,reasoningMode:h.mode,wallStartMs:h.wallStartMs}),h=null,yield*b.send({type:"ui:composer"})}else if(l.type==="cancel_plan")h=null,yield*b.send({type:"ui:composer"});else if(l.type==="edit_plan")h=null,yield*b.send({type:"ui:composer",prefill:l.query});else if(l.type==="update_task_description"&&h)h.plan.tasks=h.plan.tasks.map((f,y)=>y===l.index?{...f,description:l.description}:f),yield*b.send({type:"plan:task_updated",index:l.index,description:l.description});else if(l.type==="add_task"&&h){let f=Math.max(0,Math.min(h.plan.tasks.length,l.afterIndex+1));h.plan.tasks=[...h.plan.tasks.slice(0,f),{description:""},...h.plan.tasks.slice(f)],yield*b.send({type:"plan:task_added",afterIndex:l.afterIndex})}else if(l.type==="delete_task"&&h)h.plan.tasks.length>1&&(h.plan.tasks=h.plan.tasks.filter((f,y)=>y!==l.index),yield*b.send({type:"plan:task_deleted",index:l.index}));else if(l.type==="move_task"&&h){let f=h.plan.tasks.length;if(l.from!==l.to&&l.from>=0&&l.from<f&&l.to>=0&&l.to<f){let y=[...h.plan.tasks],[I]=y.splice(l.from,1);y.splice(l.to,0,I),h.plan.tasks=y,yield*b.send({type:"plan:task_moved",from:l.from,to:l.to})}}}catch(f){h=null,yield*b.send({type:"ui:error",message:rn(f)})}finally{yield*Ae.next()}return"quit"}))==="quit")return;P++}}).catch(t=>{process.stderr.write(`Error: ${rn(t)}
641
+ ${Qs(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.0",
4
- "description": "Local deep-research agent composer runs on your machine, zero-config after the first query. Built on @lloyal-labs/*.",
3
+ "version": "0.1.2",
4
+ "description": "A private reasoner for your terminal. Direct conversation or grounded multi-agent research, GPU-native and fully local. No API keys, no inference servers.",
5
5
  "bin": {
6
6
  "reasoning.run": "bin/run.js"
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",
@@ -41,13 +42,20 @@
41
42
  "node": ">=22"
42
43
  },
43
44
  "keywords": [
45
+ "reasoning",
46
+ "private-reasoner",
44
47
  "deep-research",
45
- "local-llm",
48
+ "grounded-reasoning",
49
+ "multi-agent",
46
50
  "agents",
51
+ "rag",
52
+ "local-llm",
53
+ "offline",
54
+ "on-device",
55
+ "gpu",
47
56
  "llama.cpp",
48
57
  "cli",
49
- "tui",
50
- "ink"
58
+ "tui"
51
59
  ],
52
60
  "repository": {
53
61
  "type": "git",