reasoning.run 0.1.1 → 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 +29 -13
  2. package/dist/bundle.mjs +45 -45
  3. package/package.json +12 -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,15 +8,26 @@ npx reasoning.run
8
8
 
9
9
  Then type a research question.
10
10
 
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>
16
+
11
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.
12
18
 
13
- ## What it does
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.
14
29
 
15
- - Downloads a Qwen3.5-4B LLM and Qwen3 reranker on first run (~3 GB, cached in `~/.cache/lloyal/models/`).
16
- - Runs a planner that decomposes your question into research tasks.
17
- - Shows the plan in an Ink-based composer; press Enter to approve or `E` to edit.
18
- - Spawns research agents (parallel for `Fast` mode, chained for `Deep` mode) that query your corpus and/or the web via Tavily.
19
- - Synthesizes findings into a coherent answer, streamed live.
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.
20
31
 
21
32
  ## Configuration
22
33
 
@@ -30,9 +41,11 @@ State lives in `./harness.json` (auto-created, auto-gitignored on first save):
30
41
  "outputDir": "./reasoning-runs" // optional — defaults to cwd
31
42
  },
32
43
  "defaults": {
33
- "reasoningMode": "deep" // or "flat"
44
+ "reasoningMode": "flat" // or "deep"
34
45
  },
35
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)
36
49
  "nCtx": 32768 // LLM context window
37
50
  }
38
51
  }
@@ -54,7 +67,7 @@ Type `/` in the composer to open the command palette. Tab autocompletes; Enter r
54
67
  | `/help` | Show the command list inline. |
55
68
  | `/quit` | Exit. |
56
69
 
57
- Settings persist to `harness.json` the moment you submit. `/model` and `/reranker` also work as a recovery path: if the boot-time download fails (HF outage, no internet, etc.), the BootStatus prompt accepts these commands so you can drop in a pre-downloaded `.gguf` and continue without restarting.
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.)
58
71
 
59
72
  ## Run artifacts
60
73
 
@@ -92,6 +105,7 @@ All optional. Anything you can set in `harness.json` you can also set on the com
92
105
  | `--corpus <path>` | Local file/glob source (same as `/scan`). |
93
106
  | `--output-dir <dir>` | Where run artifacts are written (same as `/output`). |
94
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. |
95
109
  | `--config <path>` | Use a non-default `harness.json`. |
96
110
  | `--jsonl` | Stream events as JSONL to stdout (good for piping). |
97
111
  | `--verbose` | Verbose logs. |
@@ -112,14 +126,16 @@ Standard readline chords (work in every terminal):
112
126
 
113
127
  For Cmd+Backspace / Cmd+arrow to work, turn on "Natural Text Editing" in iTerm2, or use Ghostty.
114
128
 
115
- ## Built with HDK
129
+ ## How it's built
116
130
 
117
- reasoning.run is a working example of [Lloyal's **Harness Development Kit**](https://hdk.lloyal.ai/) — the same primitives ship intelligence directly into desktop and mobile apps, no cloud round-trip required. Specifically:
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:
118
132
 
119
133
  - **`useAgent`** — single agents with tools and a terminal report tool. Powers the planner, the bridge, and synth.
120
- - **`agentPool` + `parallel`/`chain`** — multi-agent orchestration. Drives the research phase: parallel fan-out for `Fast` mode, chained tasks for `Deep` mode.
121
- - **Continuous Context Spine** — agents share GPU KV state instead of re-tokenizing strings, so a 32K-context pipeline runs on a consumer laptop. Why subsequent queries in the same session are warm and instant.
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.
122
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).
123
139
  - **`@lloyal-labs/lloyal.node`** — llama.cpp Node binding for in-process inference.
124
140
 
125
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`.
package/dist/bundle.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- var qr=Object.defineProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var Nr=(t,e)=>{for(var n in e)qr(t,n,{get:e[n],enumerable:!0})};var Je,Rt=D(()=>{"use strict";Je={query:"",warm:!1,uiPhase:"boot",phase:"idle",mode:null,plan:null,agents:new Map,researchAgentIds:[],sourceCount:0,synth:{open:!1,buffer:"",done:!1,stats:null},answer:null,pressure:null,timings:[],startedAt:Date.now(),pipelineElapsedMs:0,pipelineResumedAt:null,nextTimelineId:0,nextLabelIdx:0,pendingTaskIndex:null,pendingTaskDescription:null,researchSpawnCount:0,config:null,configOrigin:null,toast:null,composerPrefill:"",clarifyContext:null,downloads:[],loadingLabel:null,nextToastId:0,scrollback:[],corpusStatus:null,bootError:null}});function At(t){let e=process.env.HOME;return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Co(t){let e=t.replace(/^\s*\n/,"").replace(/\*\*/g,"").replace(/^#+\s*/,"").trim();if(!e)return"Thinking\u2026";let n=e.split(`
3
- `)[0].trim();return n.length>72?n.slice(0,72).trimEnd()+"\u2026":n}function Ze(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function vo(t,e){let n;try{n=JSON.parse(e)}catch{n={}}let r=typeof n.query=="string"?n.query:typeof n.pattern=="string"?n.pattern:typeof n.url=="string"?n.url:typeof n.filename=="string"?n.filename:"";return r?`"${r.length>48?r.slice(0,48)+"\u2026":r}"`:""}function Ro(t,e){try{let r=JSON.parse(e);if(t==="web_search"&&Array.isArray(r)){let o=r,s=Array.from(new Set(o.map(l=>l.url?Ze(l.url):"").filter(Boolean))).slice(0,3);return{summary:`${o.length} results`,hosts:s,resultCount:o.length,preview:o[0]?.title??null}}if(t==="search"&&Array.isArray(r)){let o=r;return{summary:`${o.length} results`,hosts:[],resultCount:o.length,preview:o[0]?.heading??null}}if(t==="grep"&&typeof r=="object"&&r!==null){let o=r;return{summary:`${o.totalMatches??0} matches`,hosts:[],resultCount:o.totalMatches??null,preview:null}}if(t==="fetch_page"&&typeof r=="object"&&r!==null){let o=r;if(o.error)return{summary:o.error,hosts:[],resultCount:null,preview:null};let s=o.url?[Ze(o.url)]:[];return{summary:`${e.length}b`,hosts:s,resultCount:null,preview:o.title??null}}if(t==="web_fetch"&&typeof r=="object"&&r!==null){let o=r,s=o.url?[Ze(o.url)]:[];return{summary:`${e.length}b`,hosts:s,resultCount:null,preview:o.title??null}}}catch{}let n=Array.from(e.matchAll(/https?:\/\/[^\s\])>"]+/g)).map(r=>r[0]);if(n.length>0){let r=Array.from(new Set(n.map(Ze))).slice(0,3);return{summary:`${n.length} links`,hosts:r,resultCount:n.length,preview:null}}return{summary:`${e.length}b`,hosts:[],resultCount:null,preview:null}}function se(t,e,n){let r=t.agents.get(e);if(!r)return t;let o=new Map(t.agents);return o.set(e,n(r)),{...t,agents:o}}function Mn(t,e,n={}){if(t.agents.has(e))return t;let r={id:e,label:`A${t.nextLabelIdx}`,phase:"idle",tokenCount:0,toolCallCount:0,taskIndex:null,taskDescription:null,dependencyHint:null,currentThinkId:null,pendingToolCallId:null,contentBuffer:"",timeline:[],...n},o=new Map(t.agents);return o.set(e,r),{...t,agents:o,nextLabelIdx:t.nextLabelIdx+1}}function tt(t,e){return{...t,timeline:[...t.timeline,e]}}function Bn(t,e,n){return{...t,timeline:t.timeline.map(r=>r.id===e?n(r):r)}}function On(t,e){let n=t.nextTimelineId;return{...se(t,e,o=>tt({...o,currentThinkId:n,phase:"thinking"},{kind:"think",id:n,title:"Thinking\u2026",body:"",live:!0,openedAt:Date.now(),closedAt:null})),nextTimelineId:t.nextTimelineId+1}}function et(t,e,n){let r=t.agents.get(e);if(!r||r.currentThinkId===null)return t;let o=r.currentThinkId,s=Co(n);return se(t,e,l=>Bn({...l,currentThinkId:null,phase:"content"},o,a=>a.kind==="think"?{...a,body:n,title:s,live:!1,closedAt:Date.now()}:a))}function Pt(t,e){switch(e.type){case"query":return{...Je,config:t.config,configOrigin:t.configOrigin,uiPhase:t.uiPhase,mode:t.mode,nextToastId:t.nextToastId,toast:t.toast,scrollback:t.scrollback,query:e.query,warm:e.warm,phase:"plan",startedAt:Date.now()};case"plan":return{...t,uiPhase:e.intent==="clarify"?"clarifying":t.uiPhase,phase:e.intent==="research"?"plan":"done",plan:{intent:e.intent,tasks:e.tasks,clarifyQuestions:e.clarifyQuestions,tokenCount:e.tokenCount,timeMs:e.timeMs},clarifyContext:e.intent==="clarify"?{originalQuery:t.query,questions:e.clarifyQuestions}:null};case"plan:task_updated":{if(!t.plan||e.index<0||e.index>=t.plan.tasks.length)return t;let n=t.plan.tasks.map((r,o)=>o===e.index?{...r,description:e.description}:r);return{...t,plan:{...t.plan,tasks:n}}}case"plan:task_added":{if(!t.plan)return t;let n=Math.max(0,Math.min(t.plan.tasks.length,e.afterIndex+1)),r=[...t.plan.tasks.slice(0,n),{description:""},...t.plan.tasks.slice(n)];return{...t,plan:{...t.plan,tasks:r}}}case"plan:task_deleted":{if(!t.plan||t.plan.tasks.length<=1||e.index<0||e.index>=t.plan.tasks.length)return t;let n=t.plan.tasks.filter((r,o)=>o!==e.index);return{...t,plan:{...t.plan,tasks:n}}}case"plan:task_moved":{if(!t.plan)return t;let n=t.plan.tasks.length;if(e.from===e.to||e.from<0||e.from>=n||e.to<0||e.to>=n)return t;let r=[...t.plan.tasks],[o]=r.splice(e.from,1);return r.splice(e.to,0,o),{...t,plan:{...t.plan,tasks:r}}}case"research:start":return{...t,uiPhase:"research",phase:"research",mode:e.mode==="flat"?"flat":"deep",pipelineResumedAt:Date.now()};case"research:done":return{...t,phase:"synth"};case"fanout:tasks":return t;case"spine:task":return{...t,pendingTaskIndex:e.taskIndex,pendingTaskDescription:e.description};case"spine:source":case"spine:task:done":return t;case"synthesize:start":return{...t,phase:"synth",synth:{open:!0,buffer:"",done:!1,stats:null}};case"synthesize:done":{let n=t.synth.buffer.trim(),r=n?[...t.scrollback,{key:`synth-${t.scrollback.length}-${Date.now()}`,kind:"synth",body:n}]:t.scrollback;return{...t,scrollback:r,synth:{...t.synth,open:!1,done:!0,stats:{tokens:e.tokenCount,toolCalls:e.toolCallCount,ppl:e.ppl,timeMs:e.timeMs}}}}case"answer":return{...t,answer:e.text};case"stats":return{...t,timings:e.timings,pressure:{pct:e.ctxPct,cellsUsed:e.ctxPos,nCtx:e.ctxTotal}};case"complete":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,phase:"done",uiPhase:"done",pipelineElapsedMs:n,pipelineResumedAt:null}}case"config:loaded":return{...t,config:e.config,configOrigin:e.origin};case"config:updated":{let n=t.nextToastId+1,r=e.skipped.length>0?`saved \u2192 ${At(e.savedTo)} (skipped: ${e.skipped.join(", ")} \u2014 env active)`:e.gitignored?`saved \u2192 ${At(e.savedTo)} (added to .gitignore)`:`saved \u2192 ${At(e.savedTo)}`;return{...t,config:e.config,configOrigin:e.origin,toast:{id:n,message:r,tone:e.skipped.length>0?"warn":"success"},nextToastId:n}}case"plan:start":{let r=t.uiPhase==="composer"||t.uiPhase==="done"||t.uiPhase==="boot"?{pipelineElapsedMs:0,startedAt:Date.now()}:{};return{...t,...r,uiPhase:"planning",phase:"plan",plan:null,query:e.query,mode:e.mode==="flat"?"flat":"deep",pipelineResumedAt:Date.now()}}case"ui:composer":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,uiPhase:"composer",composerPrefill:e.prefill??"",clarifyContext:null,pipelineElapsedMs:n,pipelineResumedAt:null}}case"ui:plan_review":{let n=t.pipelineResumedAt?t.pipelineElapsedMs+(Date.now()-t.pipelineResumedAt):t.pipelineElapsedMs;return{...t,uiPhase:"plan_review",pipelineElapsedMs:n,pipelineResumedAt:null}}case"ui:error":{let n=t.nextToastId+1;return{...t,uiPhase:"composer",toast:{id:n,message:e.message,tone:"error"},nextToastId:n}}case"download:plan":return{...t,uiPhase:"downloading",downloads:e.entries.map(n=>({id:n.id,label:n.label,got:0,total:n.sizeBytes,done:!1,started:!1}))};case"download:start":return{...t,uiPhase:"downloading",downloads:t.downloads.map(n=>n.id===e.id?{...n,started:!0}:n)};case"download:progress":return{...t,downloads:t.downloads.map(n=>n.id===e.id?{...n,started:!0,got:e.got,total:e.total,url:e.url??n.url}:n)};case"download:complete":return{...t,downloads:t.downloads.map(n=>n.id===e.id?{...n,got:n.total||n.got,done:!0}:n)};case"weights:start":return{...t,uiPhase:"loading",loadingLabel:e.label};case"weights:label":return{...t,loadingLabel:e.label};case"weights:done":return{...t,loadingLabel:null};case"corpus:indexed":return{...t,corpusStatus:{fileCount:e.fileCount,chunkCount:e.chunkCount}};case"boot:error":return{...t,uiPhase:"boot_error",bootError:{kind:e.kind,message:e.message}};case"agent:spawn":{if(t.phase!=="research")return Mn(t,e.agentId,{phase:"idle",taskIndex:null});let n,r,o=t.pendingTaskIndex,s=t.pendingTaskDescription;t.mode==="deep"?(n=o??t.researchSpawnCount,r=s??t.plan?.tasks[n]?.description??null,o=null,s=null):(n=t.researchSpawnCount,r=t.plan?.tasks[n]?.description??null);let l=t.mode==="deep"&&n>0?`builds on Task ${n}`:null,a=Mn(t,e.agentId,{phase:"thinking",taskIndex:n,taskDescription:r,dependencyHint:l});return a={...a,researchAgentIds:[...a.researchAgentIds,e.agentId],researchSpawnCount:t.researchSpawnCount+1,pendingTaskIndex:o,pendingTaskDescription:s},On(a,e.agentId)}case"agent:produce":{if(t.phase==="synth"&&t.synth.open)return{...t,synth:{...t.synth,buffer:t.synth.buffer+e.text}};if(t.phase!=="research")return t;let n=t.agents.get(e.agentId);if(!n||n.taskIndex===null)return t;let r=t,o=n;if(o.phase==="content")return se(r,o.id,w=>({...w,tokenCount:e.tokenCount,contentBuffer:w.contentBuffer+e.text}));if(o.phase!=="thinking"||o.currentThinkId===null)if(o.phase==="tool"||o.phase==="idle")r=On(r,o.id),o=r.agents.get(o.id);else return se(r,o.id,w=>({...w,tokenCount:e.tokenCount}));let s=o.currentThinkId,l=o.timeline.find(w=>w.id===s);if(!l||l.kind!=="think")return r;let a=l.body+e.text,d=a.indexOf(_n);if(d===-1)return se(r,o.id,w=>Bn({...w,tokenCount:e.tokenCount},s,S=>S.kind==="think"?{...S,body:a}:S));let c=a.slice(0,d),u=a.slice(d+_n.length),m=et(r,o.id,c);return se(m,o.id,w=>({...w,tokenCount:e.tokenCount,contentBuffer:u}))}case"agent:tool_call":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let l=n.timeline.find(d=>d.id===n.currentThinkId),a=l&&l.kind==="think"?l.body:"";r=et(r,e.agentId,a)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,l=>({...l,phase:"tool",toolCallCount:l.toolCallCount+1}));let o=r.nextTimelineId;return{...se(r,e.agentId,l=>tt({...l,phase:"tool",toolCallCount:l.toolCallCount+1,pendingToolCallId:o,contentBuffer:""},{kind:"tool_call",id:o,tool:e.tool,argsSummary:vo(e.tool,e.args)})),nextTimelineId:r.nextTimelineId+1}}case"agent:tool_result":{let n=t.agents.get(e.agentId);if(!n)return t;if(n.taskIndex==null)return se(t,e.agentId,a=>({...a,phase:"idle"}));let r=Ro(e.tool,e.result),o=t.nextTimelineId,s=Array.from(new Set(r.hosts));return{...se(t,e.agentId,a=>tt({...a,phase:"idle",pendingToolCallId:null},{kind:"tool_result",id:o,tool:e.tool,callId:n.pendingToolCallId,byteLength:e.result.length,preview:r.preview,hosts:s,resultCount:r.resultCount})),nextTimelineId:t.nextTimelineId+1,sourceCount:t.sourceCount+s.length}}case"agent:tool_progress":return t;case"agent:report":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let u=n.timeline.find(w=>w.id===n.currentThinkId),m=u&&u.kind==="think"?u.body:"";r=et(r,e.agentId,m)}if(r.agents.get(e.agentId)?.taskIndex==null)return se(r,e.agentId,u=>({...u,phase:"done",contentBuffer:""}));let o=r.nextTimelineId,s=se(r,e.agentId,u=>tt({...u,phase:"done",contentBuffer:""},{kind:"report",id:o,body:e.result,tokenCount:u.tokenCount})),l=s.agents.get(e.agentId),a=s.researchAgentIds.includes(e.agentId),d=a&&l?[...s.scrollback,{key:`agent-${e.agentId}-${s.scrollback.length}`,kind:"agent",agent:l}]:s.scrollback,c=a?s.researchAgentIds.filter(u=>u!==e.agentId):s.researchAgentIds;return{...s,nextTimelineId:r.nextTimelineId+1,scrollback:d,researchAgentIds:c}}case"agent:done":{let n=t.agents.get(e.agentId);if(!n)return t;let r=t;if(n.currentThinkId!==null){let o=n.timeline.find(l=>l.id===n.currentThinkId),s=o&&o.kind==="think"?o.body:"";r=et(r,e.agentId,s)}return se(r,e.agentId,o=>({...o,phase:"idle"}))}case"agent:tick":return{...t,pressure:{pct:e.nCtx>0?Math.round(100*e.cellsUsed/e.nCtx):0,cellsUsed:e.cellsUsed,nCtx:e.nCtx}};default:return t}}var _n,Dn=D(()=>{"use strict";Rt();_n="</think>"});import{useEffect as Ao,useReducer as Po}from"react";function qn(t,e=[]){let[n,r]=Po(Pt,e,o=>o.reduce(Pt,Je));return Ao(()=>t.subscribe(r),[t]),n}var Nn=D(()=>{"use strict";Rt();Dn()});import{createContext as Eo,useContext as Io}from"react";function nt(){return Io(Et)}var _o,Et,rt=D(()=>{"use strict";_o=()=>{},Et=Eo(_o)});import{memo as Mo}from"react";import{Box as Oo,Text as Ln}from"ink";import{jsx as Un,jsxs as Bo}from"react/jsx-runtime";var Fn,$n=D(()=>{"use strict";Fn=Mo(function({query:e,warm:n}){return e?Bo(Oo,{flexDirection:"column",marginBottom:1,children:[Un(Ln,{bold:!0,children:e}),n?Un(Ln,{dimColor:!0,children:"follow-up \xB7 warm session"}):null]}):null})});function ot(t){let e=Number.parseInt(t.slice(1),10);return!Number.isFinite(e)||e<0?It[0]:It[e%It.length]}var It,_t=D(()=>{"use strict";It=["cyan","yellow","green","magenta","red","blue"]});var le,st=D(()=>{"use strict";le=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});import{memo as Pe,useEffect as Do,useState as qo}from"react";import{Box as F,Text as _}from"ink";import{jsx as v,jsxs as U}from"react/jsx-runtime";function Lo(t){return No.includes(t.phase)}function Uo(t){let e=t.indexOf(`
4
- `);if(e<=0)return"Thinking\u2026";let n=t.slice(0,e).trim();return n?n.length>72?n.slice(0,72).trimEnd()+"\u2026":n:"Thinking\u2026"}function Wn(t){let e=t.indexOf(`
5
- `);return e<=0?"":t.slice(e+1).trimStart()}var No,Mt,Ot,Bt,Dt,Fo,$o,it,qt=D(()=>{"use strict";_t();st();No=["thinking","content","tool"];Mt=Pe(function({item:e,color:n}){let r=e.live?e.body.includes(`
6
- `)?Uo(e.body):"Thinking\u2026":e.title,o=e.live?Wn(e.body):Wn(e.body).trim();return U(F,{flexDirection:"column",marginBottom:1,flexShrink:0,children:[U(F,{children:[v(_,{color:n,children:"\u2726 "}),v(_,{bold:!0,children:r})]}),o?v(F,{paddingLeft:2,children:U(_,{children:[o,e.live?"\u258E":""]})}):e.live?v(F,{paddingLeft:2,children:v(_,{dimColor:!0,children:"\u258E"})}):null]})});Ot=Pe(function({item:e,pending:n=!1}){let[r,o]=qo(0);return Do(()=>{if(!n)return;let s=setInterval(()=>o(l=>(l+1)%le.length),80);return()=>clearInterval(s)},[n]),U(F,{flexShrink:0,children:[n?U(_,{color:"cyan",children:[le[r]," "]}):v(_,{dimColor:!0,children:"\u203A "}),v(_,{color:"cyan",children:e.tool}),e.argsSummary?U(_,{dimColor:!0,children:[" ",e.argsSummary]}):null]})}),Bt=Pe(function({item:e}){let n=e.hosts.length>0?e.hosts.join(" \xB7 "):null;return U(F,{flexDirection:"column",flexShrink:0,children:[U(F,{paddingLeft:2,children:[v(_,{color:"green",children:"\u2713 "}),v(_,{children:e.resultCount??e.byteLength+"b"}),typeof e.resultCount=="number"?v(_,{children:" results"}):null]}),n?v(F,{paddingLeft:4,children:v(_,{dimColor:!0,children:n})}):e.preview?v(F,{paddingLeft:4,children:v(_,{dimColor:!0,children:e.preview.length>60?e.preview.slice(0,60)+"\u2026":e.preview})}):null]})}),Dt=Pe(function({item:e,color:n}){let r=e.body.trim();return U(F,{flexDirection:"column",marginTop:1,flexShrink:0,children:[U(F,{children:[v(_,{color:n,children:"\u2713 "}),v(_,{bold:!0,children:"report"}),U(_,{dimColor:!0,children:[" \xB7 ",e.tokenCount," tok"]})]}),r?v(F,{paddingLeft:2,children:v(_,{children:r})}):null]})}),Fo=Pe(function({buffer:e,color:n}){return U(F,{flexDirection:"column",marginTop:1,flexShrink:0,children:[U(F,{children:[v(_,{color:n,children:"\u25B8 "}),v(_,{dimColor:!0,bold:!0,children:"streaming"})]}),v(F,{paddingLeft:2,children:U(_,{dimColor:!0,children:[e,"\u258E"]})})]})}),$o=3,it=Pe(function({agent:e,headerPrefix:n,bodyHeight:r,width:o}){let s=ot(e.label),l=Lo(e),a=e.taskDescription??null,d=r+$o;return U(F,{flexDirection:"column",width:o,height:d,paddingX:1,marginRight:1,flexShrink:0,overflow:"hidden",children:[U(F,{flexShrink:0,children:[n?U(_,{dimColor:!0,children:[n," \xB7 "]}):null,v(_,{color:s,bold:!0,children:e.label}),v(F,{flexGrow:1}),v(_,{color:l?s:"green",children:l?"\u25CF":"\u2713"})]}),a?v(_,{dimColor:!0,children:a}):null,e.dependencyHint?U(_,{dimColor:!0,children:["\u2191 ",e.dependencyHint]}):null,U(F,{flexDirection:"column",flexGrow:1,justifyContent:"flex-end",overflow:"hidden",children:[e.timeline.map(c=>c.kind==="think"?v(Mt,{item:c,color:s},c.id):c.kind==="tool_call"?v(Ot,{item:c,pending:e.pendingToolCallId===c.id},c.id):c.kind==="tool_result"?v(Bt,{item:c},c.id):c.kind==="report"?v(Dt,{item:c,color:s},c.id):null),e.contentBuffer?v(Fo,{buffer:e.contentBuffer,color:s}):null]})]})})});import{Box as at,Text as lt}from"ink";import{jsx as he,jsxs as Nt}from"react/jsx-runtime";function zn({agent:t}){let e=ot(t.label),n=t.taskDescription?t.taskDescription.length>80?t.taskDescription.slice(0,80)+"\u2026":t.taskDescription:null;return Nt(at,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,marginBottom:1,children:[Nt(at,{flexShrink:0,children:[he(lt,{color:e,bold:!0,children:t.label}),he(at,{flexGrow:1}),he(lt,{color:"green",children:"\u2713"})]}),n?he(lt,{dimColor:!0,children:n}):null,t.dependencyHint?Nt(lt,{dimColor:!0,children:["\u2191 ",t.dependencyHint]}):null,he(at,{flexDirection:"column",children:t.timeline.map(r=>r.kind==="think"?he(Mt,{item:r,color:e},r.id):r.kind==="tool_call"?he(Ot,{item:r},r.id):r.kind==="tool_result"?he(Bt,{item:r},r.id):r.kind==="report"?he(Dt,{item:r,color:e},r.id):null)})]})}var Hn=D(()=>{"use strict";_t();qt()});import{useEffect as Wo,useState as zo}from"react";import{useStdout as Ho}from"ink";function Yn(){let{stdout:t}=Ho(),[e,n]=zo(()=>[t?.columns??120,t?.rows??40]);return Wo(()=>{if(!t)return;let r=()=>{n([t.columns??120,t.rows??40])};return t.on("resize",r),()=>{t.off("resize",r)}},[t]),e}function jn(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),r=e%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}var Lt=D(()=>{"use strict"});import{Box as Ut}from"ink";import{jsx as Ee}from"react/jsx-runtime";function Gn({state:t}){let[e,n]=Yn(),r=t.researchAgentIds.map(l=>t.agents.get(l)).filter(l=>!!l);if(r.length===0)return null;let o=Math.max(Ft,n-Yo);if(t.mode==="flat"){let l=r.length,a=Math.max(Kn*l,e-4),d=Math.max(Kn,Math.floor(a/l)-1);return d*l+l<=e?Ee(Ut,{flexDirection:"row",marginBottom:1,children:r.map(u=>Ee(it,{agent:u,headerPrefix:null,bodyHeight:o,width:d},u.id))}):Ee(Ut,{flexDirection:"column",marginBottom:1,children:r.map(u=>Ee(it,{agent:u,headerPrefix:null,bodyHeight:Math.max(Ft,Math.floor(o/l))},u.id))})}let s=Math.max(Ft,Math.floor(o/Math.max(1,r.length)));return Ee(Ut,{flexDirection:"column",marginBottom:1,children:r.map(l=>Ee(it,{agent:l,headerPrefix:`Task ${(l.taskIndex??0)+1}`,bodyHeight:s},l.id))})}var Yo,Kn,Ft,Qn=D(()=>{"use strict";qt();Lt();Yo=18,Kn=26,Ft=10});import{Box as $e,Text as ke}from"ink";import{jsx as we,jsxs as We}from"react/jsx-runtime";function Vn({state:t}){let{synth:e}=t;if(!e.open&&!e.done)return null;let n=e.done?We($e,{children:[we(ke,{bold:!0,children:"Synthesis "}),we(ke,{color:"green",children:"\u2713"}),e.stats?We(ke,{dimColor:!0,children:[" ","\xB7 ",e.stats.tokens," tok \xB7 ",e.stats.toolCalls," tools \xB7"," ",Number.isFinite(e.stats.ppl)?`ppl ${e.stats.ppl.toFixed(2)} \xB7 `:"",jo(e.stats.timeMs)]}):null]}):We($e,{children:[we(ke,{bold:!0,children:"Synthesis"}),we(ke,{color:"cyan",children:" \u25CF"})]}),r=e.buffer.trim();return We($e,{flexDirection:"column",marginBottom:1,children:[n,e.open&&r?we($e,{paddingLeft:2,marginTop:0,children:We(ke,{children:[r,"\u258E"]})}):e.open?we($e,{paddingLeft:2,children:we(ke,{dimColor:!0,children:"\u258E"})}):null]})}var jo,Xn=D(()=>{"use strict";jo=t=>`${(t/1e3).toFixed(1)}s`});import{Box as Jn,Text as Zn}from"ink";import{jsx as $t,jsxs as Ko}from"react/jsx-runtime";function er({state:t}){return!t.answer||t.synth.done&&t.synth.buffer.trim().length>0?null:Ko(Jn,{flexDirection:"column",marginBottom:1,children:[$t(Zn,{dimColor:!0,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"}),$t(Jn,{marginTop:1,paddingLeft:2,children:$t(Zn,{children:t.answer.trim()})})]})}var tr=D(()=>{"use strict"});import{useEffect as Go,useState as Qo}from"react";import{Box as nr,Text as ie}from"ink";import{Fragment as es,jsx as ce,jsxs as ze}from"react/jsx-runtime";function Vo(t,e=12){let n=Math.min(e,Math.max(0,Math.round(t/100*e)));return"\u2588".repeat(n)+"\u2591".repeat(e-n)}function Xo(t){return t>=90?"red":t>=70?"yellow":"green"}function Jo(t){let e=0;for(let n of t.agents.values())n.phase!=="done"&&n.phase!=="idle"&&e++;return e}function Zo(t){let e=t.pipelineResumedAt,[,n]=Qo(0);return Go(()=>{if(e===null)return;let r=setInterval(()=>n(o=>o+1),250);return()=>clearInterval(r)},[e]),e===null?t.pipelineElapsedMs:t.pipelineElapsedMs+(Date.now()-e)}function rr({state:t}){let e=Zo(t),n=t.pressure?.pct??0,r=Jo(t),o=Xo(n);return ce(nr,{borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,paddingTop:0,children:ze(nr,{flexDirection:"row",children:[ce(ie,{dimColor:!0,children:"KV "}),ce(ie,{color:o,children:Vo(n)}),ze(ie,{children:[" ",String(n).padStart(2," "),"%"]}),ce(ie,{dimColor:!0,children:" \xB7 "}),ce(ie,{children:t.phase}),ce(ie,{dimColor:!0,children:" \xB7 \u23F1 "}),ce(ie,{children:jn(e)}),ce(ie,{dimColor:!0,children:" \xB7 "}),ze(ie,{children:[r," active"]}),t.sourceCount>0?ze(es,{children:[ce(ie,{dimColor:!0,children:" \xB7 "}),ce(ie,{dimColor:!0,children:"\u2315 "}),ze(ie,{children:[t.sourceCount," sources"]})]}):null]})})}var or=D(()=>{"use strict";Lt()});import{useState as ts}from"react";import{Text as Ie,useInput as ns}from"ink";import{jsx as ct,jsxs as ir}from"react/jsx-runtime";function me({value:t,onChange:e,onSubmit:n,onCancel:r,placeholder:o="",focused:s=!0,mask:l=!1,color:a}){let[d,c]=ts(t.length),u=Math.min(d,t.length);ns((y,g)=>{if(g.return){n?.(t);return}if(g.escape){r?.();return}if(g.leftArrow){g.meta||g.ctrl?c(sr(t,u)):c(Math.max(0,u-1));return}if(g.rightArrow){g.meta||g.ctrl?c(rs(t,u)):c(Math.min(t.length,u+1));return}if(y==="\x1B[H"||y==="\x1BOH"){c(0);return}if(y==="\x1B[F"||y==="\x1BOF"){c(t.length);return}if(g.backspace||g.delete){if(u===0)return;if(g.meta||g.ctrl){let W=sr(t,u);e(t.slice(0,W)+t.slice(u)),c(W);return}let I=t.slice(0,u-1)+t.slice(u);c(u-1),e(I);return}if(g.ctrl&&y==="a"){c(0);return}if(g.ctrl&&y==="e"){c(t.length);return}if(g.ctrl&&y==="u"){e(t.slice(u)),c(0);return}if(g.ctrl&&y==="k"){e(t.slice(0,u));return}if(g.ctrl&&y==="w"){let I=t.slice(0,u),W=/\S+\s*$/.exec(I),R=W?W.index:0;e(t.slice(0,R)+t.slice(u)),c(R);return}if(!(g.ctrl||g.meta||g.tab||g.upArrow||g.downArrow)&&y.length>0){let I=t.slice(0,u)+y+t.slice(u);c(u+y.length),e(I)}},{isActive:s});let m=l?"*".repeat(t.length):t;if(t.length===0)return ir(Ie,{children:[ct(Ie,{color:a,children:s?"\u258E":""}),ct(Ie,{dimColor:!0,children:o})]});if(!s)return ct(Ie,{color:a,children:m});let S=m.slice(0,u),q=m.slice(u,u+1),E=m.slice(u+1);return ir(Ie,{color:a,children:[S,ct(Ie,{inverse:!0,children:q||" "}),E]})}function sr(t,e){if(e<=0)return 0;let n=e;for(;n>0&&/\s/.test(t[n-1]);)n--;for(;n>0&&!/\s/.test(t[n-1]);)n--;return n}function rs(t,e){let n=t.length;if(e>=n)return n;let r=e;for(;r<n&&/\s/.test(t[r]);)r++;for(;r<n&&!/\s/.test(t[r]);)r++;return r}var Wt=D(()=>{"use strict"});import{memo as Me,useEffect as zt,useState as _e}from"react";import{Box as J,Text as B,useInput as os}from"ink";import{jsx as k,jsxs as te}from"react/jsx-runtime";function ar(t){if(!t.startsWith("/"))return null;let e=t.slice(1).trimStart();if(!e)return{name:"",value:""};let n=e.search(/\s/),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1).trim();return{name:r,value:o}}function ss(t){if(!t)return[];if(!t.name)return ut;let e=t.name.toLowerCase();return ut.filter(n=>n.name.startsWith(e))}var ut,ur,lr,Ht,is,as,cr,dr=D(()=>{"use strict";rt();Wt();ut=[{name:"scan",desc:"Set local file source (path or glob)",kind:"value"},{name:"web",desc:"Set web search key",kind:"value"},{name:"model",desc:"Set local LLM .gguf path",kind:"value"},{name:"reranker",desc:"Set local reranker .gguf path",kind:"value"},{name:"output",desc:"Set output directory",kind:"value"},{name:"deep",desc:"Use deep (chain) reasoning",kind:"instant"},{name:"flat",desc:"Use flat (parallel) reasoning",kind:"instant"},{name:"help",desc:"Show this list",kind:"instant"},{name:"quit",desc:"Quit",kind:"instant"}];ur=Me(function({state:e}){let n=nt(),r=e.config?.defaults.reasoningMode??"flat",[o,s]=_e(r),[l,a]=_e("query"),[d,c]=_e(""),[u,m]=_e(""),[w,S]=_e(!1),q=e.scrollback.length>0,[E,y]=_e(q?"start":"plan");zt(()=>{q&&y("start")},[q]),zt(()=>{e.composerPrefill&&e.composerPrefill!==d&&c(e.composerPrefill)},[e.composerPrefill]),zt(()=>{s(r)},[r]);let g=e.configOrigin?.tavilyKey??"unset",I=e.configOrigin?.corpusPath??"unset",W=e.configOrigin?.outputDir??"default",R=g!=="unset",Z=R||I!=="unset",re=g==="env",Y=e.clarifyContext!==null,C=ar(d),b=C!==null,Q=ss(C);os((T,L)=>{if(L.ctrl&&T==="c"){n({type:"quit"});return}if(L.tab&&L.shift){!b&&!Y&&y(V=>V==="plan"?"start":"plan");return}if(L.tab){if(b&&C&&C.name&&Q.length===1){let V=Q[0];c("/"+V.name+(V.kind==="value"?" ":""));return}return}if(L.escape){if(Y){n({type:"cancel_plan"}),c("");return}c(""),S(!1);return}},{isActive:l==="query"});let oe=T=>{let L=T.trim();if(L){if(!Y){let V=ar(L);if(V){f(V);return}}if(Y){n({type:"submit_clarification",answer:L}),c("");return}Z&&(n({type:"submit_query",query:L,mode:o,skipPlanner:E==="start"}),c(""))}},f=({name:T,value:L})=>{if(!T)return;let V=ut.find(ft=>ft.name===T);if(V){if(c(""),S(!1),V.kind==="instant"){T==="deep"?s("deep"):T==="flat"?s("flat"):T==="quit"?n({type:"quit"}):T==="help"&&S(!0);return}if(L){T==="web"?n({type:"set_tavily_key",key:L}):T==="scan"?n({type:"set_corpus_path",path:L}):T==="output"?n({type:"set_output_dir",path:L}):T==="model"?n({type:"set_model_path",path:L}):T==="reranker"&&n({type:"set_reranker_path",path:L});return}if(T==="web"){if(re)return;m(e.config?.sources.tavilyKey??""),a("web")}else T==="scan"?(m(e.config?.sources.corpusPath??""),a("scan")):T==="output"?(m(e.config?.sources.outputDir??""),a("output")):T==="model"?(m(e.config?.model.path??""),a("model")):T==="reranker"&&(m(e.config?.model.reranker??""),a("reranker"))}};return te(J,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[l==="query"?te(J,{children:[k(B,{children:"\u203A "}),k(me,{value:d,onChange:c,onSubmit:oe,focused:!0,placeholder:Y?"Answer the questions above, or Esc to cancel\u2026":Z?"Ask a research question, or / for commands\u2026":"Type / for commands (e.g. /web, /scan) to add a source"})]}):l==="web"?te(J,{children:[k(B,{color:"yellow",children:"Web search key \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_tavily_key",key:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,mask:!0,placeholder:"tvly-..."})]}):l==="scan"?te(J,{children:[k(B,{color:"yellow",children:"Scan path \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_corpus_path",path:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,placeholder:"/path/to/docs or /path/**/*.md"})]}):l==="output"?te(J,{children:[k(B,{color:"yellow",children:"Output dir \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_output_dir",path:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,placeholder:`${process.cwd()} (default)`})]}):l==="model"?te(J,{children:[k(B,{color:"yellow",children:"Model path \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_model_path",path:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,placeholder:"/path/to/qwen3.5-4b.gguf"})]}):te(J,{children:[k(B,{color:"yellow",children:"Reranker path \u203A "}),k(me,{value:u,onChange:m,onSubmit:()=>{n({type:"set_reranker_path",path:u.trim()}),a("query"),m("")},onCancel:()=>{a("query"),m("")},focused:!0,placeholder:"/path/to/qwen3-reranker.gguf"})]}),l==="query"&&!Y&&b?k(J,{flexDirection:"column",marginTop:0,children:Q.length===0?k(B,{color:"red",children:"no matching command"}):Q.map(T=>k(lr,{cmd:T},T.name))}):null,l==="query"&&!b&&w?k(J,{flexDirection:"column",marginTop:0,children:ut.map(T=>k(lr,{cmd:T},T.name))}):null,te(J,{marginTop:0,children:[k(Ht,{label:"Web",origin:g,value:R?"set":null,disabled:re}),k(B,{children:" "}),k(Ht,{label:"Scan",origin:I,value:e.config?.sources.corpusPath?e.corpusStatus?`${e.corpusStatus.fileCount} files`:e.config.sources.corpusPath:null}),k(B,{children:" "}),k(Ht,{label:"Output",origin:W,value:e.config?.sources.outputDir??null}),k(J,{flexGrow:1}),l==="query"&&!Y&&!b?k(as,{submitMode:E}):null]}),k(J,{marginTop:0,children:k(is,{field:l,hasSource:Z,inSlash:b,clarifying:Y})}),e.toast?k(J,{marginTop:0,children:k(B,{color:e.toast.tone==="error"?"red":e.toast.tone==="warn"?"yellow":"green",children:e.toast.message})}):null]})}),lr=Me(function({cmd:e}){return te(J,{children:[te(B,{color:"cyan",children:["/",e.name]}),te(B,{dimColor:!0,children:[" \xB7 ",e.desc]}),e.kind==="value"?k(B,{dimColor:!0,children:" <value>"}):null]})}),Ht=Me(function({label:e,origin:n,value:r,disabled:o=!1}){let s=n!=="unset";return te(B,{children:[te(B,{color:s?"green":"gray",dimColor:o,children:[e," ",s?e==="Scan"&&r?r:"\u2713":"\u2014"]}),k(B,{dimColor:!0,children:n==="env"?" (env)":n==="cli"?" (cli)":""})]})}),is=Me(function({field:e,hasSource:n,inSlash:r,clarifying:o}){return e==="web"||e==="scan"||e==="output"||e==="model"||e==="reranker"?k(B,{dimColor:!0,children:"\u23CE save (empty to clear) \xB7 Ctrl+U clear \xB7 Esc cancel"}):o?k(B,{color:"yellow",children:"\u23CE submit answer \xB7 Esc cancel"}):r?k(B,{dimColor:!0,children:"Tab complete \xB7 \u23CE run \xB7 Esc clear"}):n?k(B,{dimColor:!0,children:"\u21E7Tab Plan/Start \xB7 / commands"}):k(B,{color:"yellow",children:"\u26A0 Add a source via /web or /scan"})}),as=Me(function({submitMode:e}){return te(J,{children:[k(cr,{label:"PLAN",focused:e==="plan",hue:"cyan"}),k(B,{children:" "}),k(cr,{label:"START",focused:e==="start",hue:"green"})]})}),cr=Me(function({label:e,focused:n,hue:r}){let s=` ${n?"\u25C9":"\u25CB"} ${e} `;return n?k(B,{backgroundColor:r,color:"black",bold:!0,children:s}):k(B,{dimColor:!0,children:s})})});import{memo as Yt,useEffect as pr,useRef as ls,useState as dt}from"react";import{Box as H,Text as M,useInput as cs}from"ink";import{jsx as A,jsxs as j}from"react/jsx-runtime";var hr,us,ds,mr=D(()=>{"use strict";rt();Wt();hr=Yt(function({state:e}){let n=nt(),r=e.plan,[o,s]=dt(e.mode??"flat"),[l,a]=dt(()=>r?.tasks.length??0),[d,c]=dt(null),[u,m]=dt("");pr(()=>{e.mode&&e.mode!==o&&s(e.mode),c(null),a(r?.tasks.length??0)},[e.mode]),pr(()=>{r&&l>r.tasks.length&&a(r.tasks.length)},[r?.tasks.length]);let w=ls({focusedIndex:l,editingIndex:d,mode:o,plan:r,query:e.query});if(w.current={focusedIndex:l,editingIndex:d,mode:o,plan:r,query:e.query},cs((E,y)=>{let g=w.current,I=g.plan,W=g.editingIndex,R=g.focusedIndex,ge=g.mode;if(!I||W!==null)return;if(I.intent!=="research"){if(y.return){I.intent==="clarify"&&n({type:"edit_plan",query:g.query});return}y.escape&&n({type:"cancel_plan"}),y.ctrl&&E==="c"&&n({type:"quit"});return}if(y.ctrl&&E==="c"){n({type:"quit"});return}if(y.escape){n({type:"cancel_plan"});return}let Z=R>=I.tasks.length;if(y.shift&&y.upArrow){!Z&&R>0&&(n({type:"move_task",from:R,to:R-1}),a(R-1));return}if(y.shift&&y.downArrow){!Z&&R<I.tasks.length-1&&(n({type:"move_task",from:R,to:R+1}),a(R+1));return}if(y.upArrow){a(Math.max(0,R-1));return}if(y.downArrow){a(Math.min(I.tasks.length,R+1));return}if(y.return){Z?n({type:"accept_plan"}):(m(I.tasks[R]?.description??""),c(R));return}if(E==="a"||E==="A"||E==="+"){let re=Z?I.tasks.length-1:R,Y=re+1;n({type:"add_task",afterIndex:re}),a(Y),m(""),c(Y);return}if(E==="d"||E==="D"||y.delete){!Z&&I.tasks.length>1&&n({type:"delete_task",index:R});return}if(E==="t"||E==="T"){let re=ge==="deep"?"flat":"deep";s(re),n({type:"change_mode",mode:re});return}}),!r)return null;if(r.intent==="clarify")return j(H,{flexDirection:"column",marginBottom:1,children:[A(H,{marginBottom:1,children:A(M,{bold:!0,children:e.query})}),A(M,{dimColor:!0,children:"A few questions to narrow this down."}),A(H,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.clarifyQuestions.map((E,y)=>j(M,{children:[j(M,{dimColor:!0,children:["(",y+1,")"]})," ",E]},y))}),A(H,{marginTop:1,children:A(M,{dimColor:!0,children:"\u23CE answer \xB7 Esc cancel"})})]});if(r.intent==="passthrough")return j(H,{flexDirection:"column",marginBottom:1,children:[A(M,{bold:!0,children:e.query}),A(M,{dimColor:!0,children:"Answering directly \u2014 no research needed."})]});let S=o==="flat"?"parallel":"chained",q=d!==null;return j(H,{flexDirection:"column",marginBottom:1,children:[A(H,{marginBottom:1,children:A(M,{bold:!0,children:e.query})}),j(H,{marginBottom:1,children:[A(M,{dimColor:!0,children:"Research plan"}),j(M,{dimColor:!0,children:[" \xB7 ",r.tasks.length," ",S," tasks"]}),q?j(M,{color:"yellow",children:[" \xB7 editing row ",d+1]}):null]}),j(H,{flexDirection:"column",children:[r.tasks.map((E,y)=>A(ds,{index:y,description:E.description,focused:y===l,editing:y===d,draft:u,onDraftChange:m,onSubmit:g=>{n({type:"update_task_description",index:y,description:g.trim()}),c(null)},onCancel:()=>c(null)},y)),A(us,{focused:l>=r.tasks.length&&!q})]}),j(H,{marginTop:1,children:[j(M,{color:o==="deep"?"cyan":void 0,bold:o==="deep",children:[o==="deep"?"\u25C6":"\u25CB"," Deep"]}),A(M,{children:" "}),j(M,{color:o==="flat"?"cyan":void 0,bold:o==="flat",children:[o==="flat"?"\u25C6":"\u25CB"," Flat"]}),A(M,{dimColor:!0,children:" T toggle mode (re-plans, discards edits)"})]}),A(H,{marginTop:1,children:q?A(M,{dimColor:!0,children:"\u23CE save \xB7 Esc revert"}):j(M,{dimColor:!0,children:["\u2191\u2193 select \xB7 \u23CE ",l>=r.tasks.length?"start research":"edit"," \xB7 A add \xB7 D delete \xB7 \u21E7\u2191\u2193 reorder \xB7 Esc cancel"]})})]})}),us=Yt(function({focused:e}){return e?A(H,{paddingLeft:2,marginTop:1,children:A(M,{backgroundColor:"green",color:"black",bold:!0,children:" \u25B6 START research "})}):A(H,{paddingLeft:2,marginTop:1,children:A(M,{dimColor:!0,children:" \u25B6 START research"})})}),ds=Yt(function({index:e,description:n,focused:r,editing:o,draft:s,onDraftChange:l,onSubmit:a,onCancel:d}){return o?j(H,{paddingLeft:2,children:[A(M,{color:"yellow",bold:!0,children:`\u25B6 ${e+1}. `}),A(H,{flexGrow:1,children:A(me,{value:s,onChange:l,onSubmit:a,onCancel:d,focused:!0,placeholder:"(empty \u2014 type a task description)"})})]}):r?j(H,{paddingLeft:2,children:[A(M,{color:"cyan",bold:!0,children:`\u203A ${e+1}. `}),A(M,{bold:!0,children:n||A(M,{dimColor:!0,children:"(empty)"})})]}):j(H,{paddingLeft:2,children:[A(M,{dimColor:!0,children:` ${e+1}. `}),A(M,{dimColor:!0,children:n||"(empty)"})]})})});import{memo as ps,useEffect as hs,useState as ms}from"react";import{Box as fr,Text as jt}from"ink";import{jsx as gr,jsxs as Kt}from"react/jsx-runtime";var yr,br=D(()=>{"use strict";st();yr=ps(function({state:e}){let[n,r]=ms(0);return hs(()=>{let o=setInterval(()=>r(s=>(s+1)%le.length),80);return()=>clearInterval(o)},[]),Kt(fr,{flexDirection:"column",marginBottom:1,children:[gr(jt,{bold:!0,children:e.query}),Kt(fr,{marginTop:1,children:[Kt(jt,{color:"cyan",children:[le[n]," "]}),gr(jt,{dimColor:!0,children:"Planning\u2026"})]})]})})});import{memo as fs}from"react";import{Box as xr,Text as pt}from"ink";import{jsx as Gt,jsxs as Qt}from"react/jsx-runtime";var kr,wr=D(()=>{"use strict";kr=fs(function({state:e}){if(!e.clarifyContext)return null;let{originalQuery:n,questions:r}=e.clarifyContext;return Qt(xr,{flexDirection:"column",marginBottom:1,children:[Gt(pt,{bold:!0,children:n}),Gt(pt,{dimColor:!0,children:"A few questions to narrow this down."}),Gt(xr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,children:r.map((o,s)=>Qt(pt,{children:[Qt(pt,{dimColor:!0,children:["(",s+1,")"]})," ",o]},s))})]})})});import{memo as Tr,useEffect as gs,useState as ys}from"react";import{Box as Te,Text as N}from"ink";import{Fragment as ks,jsx as ne,jsxs as K}from"react/jsx-runtime";function xs(t){try{return new URL(t).host}catch{return null}}function ht(t){return t>=1e9?(t/1e9).toFixed(1)+" GB":t>=1e6?(t/1e6).toFixed(0)+" MB":t>=1e3?(t/1e3).toFixed(0)+" KB":`${t} B`}var Sr,bs,Cr=D(()=>{"use strict";st();Sr=Tr(function({state:e}){let[n,r]=ys(0);if(gs(()=>{let o=setInterval(()=>r(s=>(s+1)%le.length),80);return()=>clearInterval(o)},[]),e.uiPhase==="boot_error"){let o=e.bootError,s=o?.kind??"llm",l=s==="llm"?"LLM":"reranker",a=s==="llm"?"/model":"/reranker",d=s==="llm"?"/reranker":"/model";return K(Te,{flexDirection:"column",marginBottom:1,children:[K(N,{color:"red",bold:!0,children:["\u2717 Boot failed (",l,")"]}),ne(Te,{paddingLeft:2,children:ne(N,{children:o?.message??"Unknown error"})}),ne(Te,{paddingLeft:2,marginTop:1,children:K(N,{dimColor:!0,children:["Type ",K(N,{color:"cyan",children:[a," "]}),ne(N,{dimColor:!0,children:"<path-to-gguf>"}),K(N,{dimColor:!0,children:[" to use a local ",l,", or "]}),ne(N,{color:"cyan",children:d}),ne(N,{dimColor:!0,children:" for the other, or "}),ne(N,{color:"cyan",children:"/quit"}),ne(N,{dimColor:!0,children:" to exit."})]})})]})}return e.uiPhase==="downloading"?K(Te,{flexDirection:"column",marginBottom:1,children:[K(Te,{children:[K(N,{color:"cyan",children:[le[n]," "]}),ne(N,{bold:!0,children:"Downloading models"})]}),e.downloads.map(o=>ne(bs,{item:o},o.id))]}):K(Te,{marginBottom:1,children:[K(N,{color:"cyan",children:[le[n]," "]}),ne(N,{bold:!0,children:e.loadingLabel??"Loading\u2026"})]})}),bs=Tr(function({item:e}){let n=e.total>0?Math.min(100,Math.floor(e.got/e.total*100)):0,r=16,o=Math.floor(n/100*r),s="\u2588".repeat(o)+"\u2591".repeat(r-o),l=e.url?xs(e.url):null,a=e.started&&l!==null,d=e.done?"\u2713 ":a?"\u25CF ":"\u25CB ",c=e.done?"green":a?"cyan":void 0,u=!a&&!e.done;return K(Te,{paddingLeft:2,children:[ne(N,{color:c,dimColor:u,children:d}),K(N,{dimColor:u,children:[e.label.padEnd(28)," "]}),e.done?ne(N,{dimColor:!0,children:ht(e.got)}):a?K(ks,{children:[ne(N,{color:"cyan",children:s}),K(N,{children:[" ",String(n).padStart(2),"% \xB7 ",ht(e.got)," / ",ht(e.total)]}),K(N,{dimColor:!0,children:[" \xB7 ",l]})]}):K(N,{dimColor:!0,children:["queued \xB7 ",ht(e.total)]})]})})});import{Box as mt,Static as ws,Text as vr}from"ink";import{jsx as G,jsxs as Vt}from"react/jsx-runtime";function Rr({bus:t,dispatch:e,bootstrap:n}){let r=qn(t,n),o=r.uiPhase!=="composer"&&r.uiPhase!=="boot"&&r.uiPhase!=="downloading"&&r.uiPhase!=="loading"&&r.uiPhase!=="planning"&&r.uiPhase!=="plan_review"&&r.uiPhase!=="clarifying",s=r.uiPhase==="research"||r.uiPhase==="done",l=r.uiPhase==="composer"||r.uiPhase==="done"||r.uiPhase==="clarifying"||r.uiPhase==="boot_error";return Vt(Et.Provider,{value:e,children:[G(ws,{items:r.scrollback,children:a=>a.kind==="agent"?G(mt,{paddingX:2,children:G(zn,{agent:a.agent})},a.key):Vt(mt,{flexDirection:"column",paddingX:2,marginBottom:1,children:[G(vr,{dimColor:!0,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"}),G(mt,{paddingLeft:2,marginTop:1,children:G(vr,{children:a.body})})]},a.key)}),Vt(mt,{flexDirection:"column",paddingX:2,paddingY:1,children:[o&&G(Fn,{query:r.query,warm:r.warm}),(r.uiPhase==="downloading"||r.uiPhase==="loading"||r.uiPhase==="boot_error")&&G(Sr,{state:r}),r.uiPhase==="planning"&&G(yr,{state:r}),r.uiPhase==="plan_review"&&G(hr,{state:r}),r.uiPhase==="clarifying"&&G(kr,{state:r}),s&&G(Gn,{state:r}),s&&G(Vn,{state:r}),r.uiPhase==="done"&&G(er,{state:r}),l&&G(ur,{state:r}),G(rr,{state:r})]})]})}var Ar=D(()=>{"use strict";Nn();rt();$n();Hn();Qn();Xn();tr();or();dr();mr();br();wr();Cr()});var Pr={};Nr(Pr,{render:()=>Cs});import Ts from"react";import{render as Ss}from"ink";function Cs(t,e,n=[]){return Ss(Ts.createElement(Rr,{bus:t,dispatch:e,bootstrap:n}),{incrementalRendering:!0})}var Er=D(()=>{"use strict";Ar()});import*as z from"node:fs";import*as pe from"node:path";import{parseArgs as vs}from"node:util";import{main as Rs,ensure as Xt,createSignal as As,spawn as Ps,each as Se,call as Be}from"effection";import{createContext as Es}from"@lloyal-labs/lloyal.node";import{initAgents as Is,JsonlTraceWriter as _s}from"@lloyal-labs/lloyal-agents";var gt=!1,Lr=!1;function an(t){gt=t}function ln(t){Lr=t}var yt=!!process.stdout.isTTY,bt=yt?{bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m",green:"\x1B[32m",cyan:"\x1B[36m",yellow:"\x1B[33m",red:"\x1B[31m"}:{bold:"",dim:"",reset:"",green:"",cyan:"",yellow:"",red:""},sn="";function Ur(){sn&&(sn="",process.stdout.write("\r\x1B[K"))}var Ke=(...t)=>{gt||(Ur(),console.log(...t))};function cn(t,e){gt&&console.log(JSON.stringify({event:t,...e}))}import*as ee from"node:fs";import*as X from"node:path";import*as xt from"node:os";import*as Ge from"node:path";function ye(t){if(!t)return"";let e=t==="~"?xt.homedir():t.startsWith("~/")?Ge.join(xt.homedir(),t.slice(2)):t;return Ge.resolve(e)}function kt(){return{version:1,sources:{},defaults:{reasoningMode:"flat",maxTurns:10},model:{}}}function dn(t){try{let e=ee.readFileSync(t,"utf8"),n=JSON.parse(e);if(n.version!==1)return null;let r=kt();return{version:1,sources:{...r.sources,...n.sources??{}},defaults:{...r.defaults,...n.defaults??{}},model:{...r.model,...n.model??{}}}}catch{return null}}function Ce(t,e,n=process.env){let r=X.resolve(t),o=dn(r),s=o??kt(),l=n.TAVILY_API_KEY?.trim()||void 0,a=n.LLAMA_CTX_SIZE?.trim(),d=a&&/^\d+$/.test(a)?parseInt(a,10):void 0,c=e.tavilyKey??l??s.sources.tavilyKey,u=e.corpusPath??s.sources.corpusPath,m=u?ye(u):void 0,w=e.outputDir??s.sources.outputDir,S=w?ye(w):void 0,q=e.reasoningMode??s.defaults.reasoningMode??"flat",E=e.modelPath??s.model.path,y=E?ye(E):void 0,g=e.reranker??s.model.reranker,I=e.nCtx??d??s.model.nCtx,W={version:1,sources:{tavilyKey:c,corpusPath:m,outputDir:S},defaults:{reasoningMode:q,maxTurns:s.defaults.maxTurns},model:{path:y,reranker:g,nCtx:I}},R={tavilyKey:e.tavilyKey?"cli":l?"env":s.sources.tavilyKey?"file":"unset",corpusPath:e.corpusPath?"cli":s.sources.corpusPath?"file":"unset",reasoningMode:e.reasoningMode?"cli":o?.defaults.reasoningMode?"file":"default",modelPath:e.modelPath?"cli":o?.model.path?"file":"default",reranker:e.reranker?"cli":o?.model.reranker?"file":"default",nCtx:e.nCtx!==void 0?"cli":d!==void 0?"env":o?.model.nCtx!==void 0?"file":"default",outputDir:e.outputDir?"cli":o?.sources.outputDir?"file":"default"};return{config:W,origin:R,path:r,loadedFromFile:!!o}}function ve(t,e,n=process.env){let r=X.resolve(e),o=dn(r)??kt(),s=[],l={...o.sources,...t.sources??{}};t.sources?.tavilyKey===""&&delete l.tavilyKey,t.sources?.corpusPath===""&&delete l.corpusPath,t.sources?.outputDir===""&&delete l.outputDir,n.TAVILY_API_KEY&&t.sources&&"tavilyKey"in t.sources&&(delete l.tavilyKey,s.push("sources.tavilyKey"));let a={version:1,sources:l,defaults:{...o.defaults,...t.defaults??{}},model:{...o.model,...t.model??{}}},d=X.dirname(r);ee.mkdirSync(d,{recursive:!0});let c=r+".tmp-"+process.pid;ee.writeFileSync(c,JSON.stringify(a,null,2)+`
7
- `,"utf8"),ee.renameSync(c,r);let u=Fr(r);return{path:r,gitignored:u,skipped:s}}function Fr(t){try{let e=$r(X.dirname(t));if(!e)return!1;let n=X.join(e,".gitignore"),r=X.relative(e,t).replace(/\\/g,"/"),o=ee.existsSync(n)?ee.readFileSync(n,"utf8"):"",s=X.basename(t);if(new RegExp(`(^|\\n)\\s*(${un(r)}|${un(s)})\\s*(\\n|$)`).test(o))return!1;let a=o.length===0||o.endsWith(`
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 ee.appendFileSync(n,a+r+`
10
- `),!0}catch{return!1}}function un(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $r(t){let e=X.resolve(t);for(;;){if(ee.existsSync(X.join(e,".git")))return e;let n=X.dirname(e);if(n===e)return null;e=n}}function pn(){let t=[],e=new Set;return{send(n){if(t!==null){t.push(n);return}for(let r of e)r(n)},subscribe(n){if(e.add(n),t!==null){let r=t;t=null;for(let o of r)n(o)}return()=>{e.delete(n)}}}}import{TavilyProvider as Ms}from"@lloyal-labs/rig";import{createReranker as Os,WebSource as Bs,CorpusSource as Ds,chunkResources as qs,resolveCorpusInput as Ns}from"@lloyal-labs/rig/node";import Ls from"ignore";import{call as wt}from"effection";import{Ctx as St,Events as Qe,agentPool as Xr,createToolkit as Jr,useAgent as Zr,chain as eo,parallel as to,renderTemplate as De,withSharedRoot as no,DefaultAgentPolicy as Rn}from"@lloyal-labs/lloyal-agents";import{reportTool as Tn,PlanTool as ro}from"@lloyal-labs/rig";import{taskToContent as Sn}from"@lloyal-labs/rig";var hn=`You're a research planner. You analyze a user query and pick ONE of three dispositions, producing a JSON plan. Output JSON only.
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 mn=`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,7 +180,7 @@ BAD \u2014 individual task issues (for research intent):
180
180
 
181
181
  <%= it.context %>
182
182
  <% } -%>
183
- `;var fn="You are a research assistant.";var gn=`You are a research reporter. The agent has been terminated due to budget constraints and must deliver findings now.
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.
184
184
 
185
185
  Call the report tool with the most important findings from the research above. Prioritize in this order:
186
186
  1. Direct quotes and specific evidence that answer the task
@@ -190,7 +190,7 @@ Call the report tool with the most important findings from the research above. P
190
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.
191
191
  ---
192
192
  Report your findings.
193
- `;var yn=`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.
194
194
 
195
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.
196
196
 
@@ -301,7 +301,7 @@ OUTPUT FORMAT: emit the markdown report directly as your reply. Do NOT wrap it i
301
301
  Research question: "<%= it.query %>"
302
302
 
303
303
  Write the markdown report now.
304
- `;var bn=`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.
305
305
 
306
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.
307
307
 
@@ -416,7 +416,7 @@ Findings from <%= it.agentCount %> parallel research agents:
416
416
  <%= it.findings %>
417
417
 
418
418
  Write the markdown report now.
419
- `;var xn=`Apply the **corpus_research** skill.
419
+ `;var Tn=`Apply the **corpus_research** playbook.
420
420
 
421
421
  You are a thorough research assistant analyzing a knowledge base to complete your task.
422
422
  <% if (it.agentCount > 1) { -%>
@@ -444,7 +444,7 @@ PROCESS:
444
444
  3. Based on what you read, identify specific claims to verify or details that are missing, then grep/search for those.
445
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.
446
446
 
447
- `;var kn=`Apply the **web_research** skill.
447
+ `;var Sn=`Apply the **web_research** playbook.
448
448
 
449
449
  You are a thorough research assistant investigating with your tools to complete your task.
450
450
  <% if (it.agentCount > 1) { -%>
@@ -477,9 +477,9 @@ PROCESS:
477
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.
478
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.
479
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.
480
- `;var wn=`You are an assistant working as part of a multi-agent workflow. You have access to the tools below, grouped by skill. You should only use the tools for a given skill when that particular skill is requested explicitly in your task instructions.
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.
481
481
 
482
- # Skills
482
+ # Playbooks
483
483
 
484
484
  <% if (it.hasWeb) { -%>
485
485
  ## web_research
@@ -495,7 +495,7 @@ Use when: investigating a local document corpus \u2014 finding occurrences of te
495
495
  <% } -%>
496
496
  # Tool selection rule
497
497
 
498
- 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.
499
499
 
500
500
  # Examples
501
501
 
@@ -503,7 +503,7 @@ The agent system message will tell you which skill to apply. Use only that skill
503
503
  ## GOOD: web_research applied correctly
504
504
 
505
505
  SYSTEM:
506
- Apply the **web_research** skill.
506
+ Apply the **web_research** playbook.
507
507
  You are a thorough research assistant. PROCESS: 1) broad web_search; 2) fetch_page on top 2\u20133 results; 3) report.
508
508
 
509
509
  USER:
@@ -524,7 +524,7 @@ ASSISTANT calls: report({"summary": "Project Alpha findings: \u2026"})
524
524
  ## GOOD: corpus_research applied correctly
525
525
 
526
526
  SYSTEM:
527
- Apply the **corpus_research** skill.
527
+ Apply the **corpus_research** playbook.
528
528
  You are analyzing a local knowledge base. PROCESS: 1) grep or search; 2) read_file on matches; 3) report.
529
529
 
530
530
  USER:
@@ -545,7 +545,7 @@ ASSISTANT calls: report({"summary": "Project Beta findings: \u2026"})
545
545
  ## BAD: corpus_research requested, web_research tool used
546
546
 
547
547
  SYSTEM:
548
- Apply the **corpus_research** skill.
548
+ Apply the **corpus_research** playbook.
549
549
  You are analyzing a local knowledge base. PROCESS: grep/search \u2192 read_file \u2192 report.
550
550
 
551
551
  USER:
@@ -558,7 +558,7 @@ ASSISTANT calls: web_search({"query": "Project Beta"})
558
558
  ## BAD: web_research requested, corpus_research tool used
559
559
 
560
560
  SYSTEM:
561
- Apply the **web_research** skill.
561
+ Apply the **web_research** playbook.
562
562
  PROCESS: search \u2192 fetch \u2192 report.
563
563
 
564
564
  USER:
@@ -573,7 +573,7 @@ ASSISTANT calls: grep({"pattern": "Project Alpha"})
573
573
  ## BAD: web_research requested, report called without prior retrieval
574
574
 
575
575
  SYSTEM:
576
- Apply the **web_research** skill.
576
+ Apply the **web_research** playbook.
577
577
  PROCESS: search \u2192 fetch \u2192 report.
578
578
 
579
579
  USER:
@@ -581,14 +581,14 @@ Research task: Project Alpha
581
581
 
582
582
  ASSISTANT calls: report({"summary": "(no findings \u2014 no research performed)"})
583
583
 
584
- \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.
585
585
 
586
586
  <% } -%>
587
587
  <% if (it.hasCorpus) { -%>
588
588
  ## BAD: corpus_research requested, report called without prior retrieval
589
589
 
590
590
  SYSTEM:
591
- Apply the **corpus_research** skill.
591
+ Apply the **corpus_research** playbook.
592
592
  PROCESS: grep/search \u2192 read_file \u2192 report.
593
593
 
594
594
  USER:
@@ -596,47 +596,47 @@ Research task: Project Beta
596
596
 
597
597
  ASSISTANT calls: report({"summary": "(no findings \u2014 no corpus inspection performed)"})
598
598
 
599
- \u2717 WRONG. Research skills require gathering evidence before reporting. report is the terminal \u2014 calling it without prior grep/search/read_file produces an empty finding.
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.
600
600
 
601
601
  <% } -%>
602
- `;function Re(t){let e=t.trim(),n=e.indexOf(`
602
+ `;function Ie(t){let e=t.trim(),n=e.indexOf(`
603
603
  ---
604
- `);return n===-1?{system:e,user:""}:{system:e.slice(0,n).trim(),user:e.slice(n+5).trim()}}var oo=Re(hn),so=Re(mn),io=Re(fn),ao=Re(gn),lo=Re(yn),co=Re(bn),uo=xn,po=kn,ho=wn;function mo(){return new Rn({budget:{context:{softLimit:2048,hardLimit:1024},time:{softLimit:24e4,hardLimit:36e4}},recovery:{prompt:ao},terminalTool:"report"})}var Tt=class extends Rn{onProduced(...e){let[,n]=e;return!n.toolCalls[0]&&n.content?{type:"free_text_report",content:n.content}:super.onProduced(...e)}};function Cn(t,e){return t.promptData?De(uo,{...t.promptData(),...e}):t.name==="web"?De(po,e):io.system}function An(){return new Date().toISOString().slice(0,10)}function vn(){let t=performance.now();return()=>performance.now()-t}function Ct(t){return{intent:"research",tasks:[{description:t}],clarifyQuestions:[],tokenCount:0,timeMs:0}}function*fo(t,e){let n=e.trunk;if(!n)throw new Error("runPassthrough: session has no trunk");let r=yield*St.expect(),o=r.getTurnSeparator(),{prompt:s}=r.formatChatSync(JSON.stringify([{role:"user",content:t}]),{addGenerationPrompt:!0,enableThinking:!1}),l=[...o,...r.tokenizeSync(s,!1)];yield*wt(()=>n.prefill(l));let a=performance.now(),d=0,c=[];for(;;){let{token:u,text:m,isStop:w}=n.produceSync();if(w)break;yield*wt(()=>n.commit(u)),d++,c.push(m)}return{answer:c.join(""),tokenCount:d,timeMs:performance.now()-a}}function*go(t,e,n){let r=yield*Qe.expect(),o=u=>r.send(u);yield*o({type:"query",query:t,warm:!!e.trunk});let s=An(),l=n.reasoningMode==="flat"?so:oo,a=new ro({prompt:l,session:e,maxQuestions:10}),d=n.context?`Today's date: ${s}
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}
605
605
 
606
- ${n.context}`:`Today's date: ${s}`,c=yield*a.execute({query:t,context:d});return yield*o({type:"plan",intent:c.intent,tasks:c.tasks,clarifyQuestions:c.clarifyQuestions,tokenCount:c.tokenCount,timeMs:c.timeMs}),c}function*Ae(t,e,n,r,o){let s=yield*Qe.expect(),l=d=>s.send(d);yield*l({type:"plan:start",query:t,mode:o.reasoningMode});let a=yield*go(t,e,{reasoningMode:o.reasoningMode,context:o.context});if(a.intent==="clarify")return{type:"clarify",plan:a};if(a.intent==="passthrough"){if(!e.trunk){let c=Ct(t);return o.onStart?.(),yield*qe(t,c,e,n,r,{...o}),{type:"done"}}o.onStart?.();let d=yield*fo(t,e);return yield*l({type:"answer",text:d.answer}),yield*yo(a,d,o.wallStartMs),{type:"done"}}return{type:"research_plan",plan:a}}function*qe(t,e,n,r,o,s){if(e.intent!=="research")throw new Error(`runResearchPlan: expected plan.intent=research, got ${e.intent}`);let l=yield*Qe.expect(),a=C=>l.send(C),d=e.tasks,c=An();yield*a({type:"research:start",agentCount:d.length,mode:s.reasoningMode});let u=vn();for(let C of r)yield*C.bind({reranker:o});let m=new Map(r.map(C=>[C,C.createScorer(t)])),w=r.flatMap(C=>C.tools),S=r[0],q=m.get(S),E=r.some(C=>C.name==="web"),y=r.some(C=>typeof C.promptData=="function"),g=De(ho,{hasWeb:E,hasCorpus:y}),I=Jr([...w,Tn]),W=0,R=0,{answer:ge,totalTokens:Z,totalToolCalls:re,synthTokens:Y}=yield*no({parent:n.trunk??void 0,systemPrompt:g,toolsJson:I.toolsJson},function*(C){s.reasoningMode==="flat"&&(yield*a({type:"fanout:tasks",tasks:d}));let b=yield*Xr({tools:[...w,Tn],parent:C,terminalTool:"report",maxTurns:s.maxTurns,pruneOnReport:!0,policy:mo(),scorer:q,enableThinking:!0,orchestrate:s.reasoningMode==="flat"?to(d.map((h,x)=>({content:Sn(h),systemPrompt:Cn(S,{maxTurns:s.maxTurns,agentCount:d.length,siblingTasks:d.filter((O,T)=>T!==x).map(O=>O.description),date:c,taskIndex:0}),seed:1e3+x}))):eo(d,(h,x)=>({task:{content:Sn(h),systemPrompt:Cn(S,{maxTurns:s.maxTurns,agentCount:1,siblingTasks:[],date:c,taskIndex:x})},userContent:`Research task: ${h.description}`,beforeSpawn:function*(){yield*a({type:"spine:task",taskIndex:x,taskCount:d.length,description:h.description}),yield*a({type:"spine:source",taskIndex:x,source:S.name})},afterExtend:function*(O,T){yield*a({type:"spine:task:done",taskIndex:x,stageFindings:O,accumulated:T})}}))});if(R=u(),yield*a({type:"research:done",totalTokens:b.totalTokens,totalToolCalls:b.totalToolCalls,timeMs:R}),d.length===1)return{answer:b.agents[0]?.result?.trim()??"",totalTokens:b.totalTokens,totalToolCalls:b.totalToolCalls,synthTokens:0};yield*a({type:"synthesize:start"});let Q=vn(),oe=s.reasoningMode==="flat"?co:lo,f=s.reasoningMode==="flat"?b.agents.map((h,x)=>{let O=d[x]?.description??`task ${x+1}`,T=h.result?.trim()||"(no findings)";return`### Agent ${x+1}: ${O}
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}
607
607
 
608
- ${T}`}).join(`
608
+ ${x}`}).join(`
609
609
 
610
- `):void 0,i={query:t,findings:f,agentCount:d.length},p=yield*Zr({systemPrompt:De(oe.system,i),task:De(oe.user,i),parent:C,policy:new Tt,maxTurns:s.maxTurns});return W=Q(),yield*a({type:"synthesize:done",agentId:p.id,ppl:p.branch.disposed?0:p.branch.perplexity,tokenCount:p.tokenCount,toolCallCount:p.toolCallCount,timeMs:W}),{answer:p.result||"",totalTokens:b.totalTokens,totalToolCalls:b.totalToolCalls,synthTokens:p.tokenCount}});yield*a({type:"answer",text:ge}),ge&&(yield*wt(()=>n.commitTurn(t,ge))),yield*bo({plan:e,researchTokens:Z,researchToolCalls:re,researchTimeMs:R,synthTokens:Y,synthTimeMs:W,wallStartMs:s.wallStartMs,send:a})}function*yo(t,e,n){let r=yield*Qe.expect(),o=c=>r.send(c),l=(yield*St.expect())._storeKvPressure(),a=l.nCtx||1,d=[{label:"Plan",tokens:t.tokenCount,detail:t.intent,timeMs:t.timeMs},{label:"Passthrough",tokens:e.tokenCount,detail:"trunk stream",timeMs:e.timeMs}];yield*o({type:"stats",timings:d,ctxPct:Math.round(100*l.cellsUsed/a),ctxPos:l.cellsUsed,ctxTotal:a}),yield*o({type:"complete",data:{intent:t.intent,planTokens:t.tokenCount,passthroughTokens:e.tokenCount,wallTimeMs:Math.round(performance.now()-n),planMs:Math.round(t.timeMs),passthroughMs:Math.round(e.timeMs)}})}function*bo(t){let n=(yield*St.expect())._storeKvPressure(),r=n.nCtx||1,o=[{label:"Plan",tokens:t.plan.tokenCount,detail:t.plan.intent,timeMs:t.plan.timeMs},{label:"Research",tokens:t.researchTokens,detail:`${t.researchToolCalls} tools`,timeMs:t.researchTimeMs},{label:"Synthesize",tokens:t.synthTokens,detail:t.synthTokens>0?"spine fork":"skipped (single task)",timeMs:t.synthTimeMs}];yield*t.send({type:"stats",timings:o,ctxPct:Math.round(100*n.cellsUsed/r),ctxPos:n.cellsUsed,ctxTotal:r}),yield*t.send({type:"complete",data:{intent:t.plan.intent,planTokens:t.plan.tokenCount,agentTokens:t.researchTokens,synthTokens:t.synthTokens,totalToolCalls:t.researchToolCalls,agentCount:t.plan.tasks.length,wallTimeMs:Math.round(performance.now()-t.wallStartMs),planMs:Math.round(t.plan.timeMs),researchMs:Math.round(t.researchTimeMs),synthMs:Math.round(t.synthTimeMs)}})}import*as ae from"node:fs";import*as En from"node:os";import*as be from"node:path";var Pn={name:"reasoning.run",version:"0.1.1",description:"Local deep-research agent composer \u2014 runs on your machine, zero-config after the first query. Built with Lloyal HDK.",bin:{"reasoning.run":"bin/run.js"},files:["bin","dist","LICENSE","README.md"],scripts:{build:"esbuild src/main.ts --bundle --platform=node --target=node22 --format=esm --packages=external --loader:.eta=text --outfile=dist/bundle.mjs --minify --legal-comments=none","build:watch":"esbuild src/main.ts --bundle --platform=node --target=node22 --format=esm --packages=external --loader:.eta=text --outfile=dist/bundle.mjs --watch",start:"npm run build && node bin/run.js",smoke:"tsx src/tui-ink/__bus-smoke.ts && tsx src/tui-ink/__reducer-smoke.ts && tsx src/tui-ink/__config-smoke.ts && tsx src/__download-smoke.ts && tsx src/__rundir-smoke.ts","smoke:visual":"tsx src/tui-ink/__visual-smoke.tsx",prepublishOnly:"npm run build"},dependencies:{"@inkjs/ui":"^2.0.0","@lloyal-labs/lloyal-agents":"^2.0.0","@lloyal-labs/lloyal.node":"^2.1.0","@lloyal-labs/rig":"^2.0.1","@lloyal-labs/sdk":"^2.0.0",effection:"^4.0.2",eta:"^4.5.1",ignore:"^7.0.5",ink:"^7.0.1",react:"^19.2.5"},devDependencies:{"@types/node":"^25.3.0","@types/react":"^19.2.14",esbuild:"^0.28.0",tsx:"^4.21.0",typescript:"^5.9.3"},engines:{node:">=22"},keywords:["deep-research","local-llm","agents","llama.cpp","cli","tui","ink"],repository:{type:"git",url:"git+https://github.com/lloyal-ai/reasoning-run.git"},license:"SEE LICENSE IN LICENSE"};var ko=`reasoning.run/${Pn.version}`,vt=[{id:"qwen3.5-4b-q4",label:"Qwen3.5-4B Q4_K_M",kind:"llm",urls:["https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/resolve/main/Qwen3.5-4B-Q4_K_M.gguf","https://models.lloyal.ai/Qwen3.5-4B-Q4_K_M.gguf"],filename:"Qwen3.5-4B-Q4_K_M.gguf",sizeBytes:26e8,recommendedNCtx:32768},{id:"qwen3-reranker-0.6b-q8",label:"Qwen3-Reranker 0.6B Q8_0",kind:"reranker",urls:["https://huggingface.co/ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/resolve/main/qwen3-reranker-0.6b-q8_0.gguf","https://models.lloyal.ai/qwen3-reranker-0.6b-q8_0.gguf"],filename:"qwen3-reranker-0.6b-q8_0.gguf",sizeBytes:63e7}],wo=vt.find(t=>t.kind==="llm"),To=vt.find(t=>t.kind==="reranker");function Ve(){let t=process.env.XDG_CACHE_HOME||be.join(En.homedir(),".cache");return be.join(t,"lloyal","models")}function Ne(t,e){if(!t){let r=e==="llm"?wo:To;return{path:be.join(Ve(),r.filename),entry:r}}let n=vt.find(r=>r.id===t);return n?{path:be.join(Ve(),n.filename),entry:n}:{path:be.resolve(t),entry:null}}async function In(t,e={}){let n=be.join(Ve(),t.filename);if(ae.existsSync(n))return n;ae.mkdirSync(Ve(),{recursive:!0});let r=n+".partial";try{ae.unlinkSync(r)}catch{}let o=[];for(let s of t.urls)try{return await So(s,r,n,t.sizeBytes,e)}catch(l){o.push(` ${s}: ${l.message}`);try{ae.unlinkSync(r)}catch{}}throw new Error(`Failed to download ${t.label} from any source:
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:
611
611
  ${o.join(`
612
- `)}`)}async function So(t,e,n,r,o){let s=await fetch(t,{redirect:"follow",headers:{"User-Agent":ko}});if(!s.ok||!s.body)throw new Error(`HTTP ${s.status} ${s.statusText}`);let l=Number(s.headers.get("content-length")??r),a=ae.createWriteStream(e),d=0,c=0,u=(m=!1)=>{if(!o.onProgress)return;let w=Date.now();!m&&w-c<200||(c=w,o.onProgress(d,l,t))};try{for await(let m of s.body)a.write(m),d+=m.byteLength,u()}catch(m){throw a.destroy(),m}return await new Promise((m,w)=>{a.end(S=>S?w(S):m())}),ae.renameSync(e,n),u(!0),n}import*as Le from"node:fs";import*as Ue from"node:path";var Xe=class{currentDir=null;inResearch=!1;spawnOrdinal=0;agentToOrdinal=new Map;taskByOrdinal=new Map;lastAnswer=null;query=null;mode=null;startedAt=null;synthStats=null;start(e){let n=new Date().toISOString().replace(/[:.]/g,"-").replace("Z","");return this.currentDir=Ue.resolve(e.outputDir,n),Le.mkdirSync(this.currentDir,{recursive:!0}),this.inResearch=!1,this.spawnOrdinal=0,this.agentToOrdinal.clear(),this.taskByOrdinal.clear(),this.lastAnswer=null,this.query=e.query,this.mode=e.mode,this.startedAt=Date.now(),this.synthStats=null,this.currentDir}handle(e){if(this.currentDir)switch(e.type){case"research:start":this.inResearch=!0;break;case"research:done":this.inResearch=!1;break;case"fanout:tasks":e.tasks.forEach((n,r)=>this.taskByOrdinal.set(r+1,n.description));break;case"spine:task":this.taskByOrdinal.set(e.taskIndex+1,e.description);break;case"agent:spawn":this.inResearch&&!this.agentToOrdinal.has(e.agentId)&&(this.spawnOrdinal+=1,this.agentToOrdinal.set(e.agentId,this.spawnOrdinal));break;case"agent:report":{let n=this.agentToOrdinal.get(e.agentId);n!==void 0&&this.writeAnnexure(n,e.result);break}case"answer":this.lastAnswer=e.text;break;case"synthesize:done":this.synthStats={tokens:e.tokenCount,ppl:e.ppl,timeMs:e.timeMs};break;case"complete":this.finish();break;case"ui:error":this.reset();break}}writeAnnexure(e,n){if(!this.currentDir)return;let r=this.taskByOrdinal.get(e)??"",o=`# Annexure ${e}
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}
613
613
 
614
614
  ${r?`**Task:** ${r}
615
615
 
616
616
  `:""}---
617
617
 
618
- `;Le.writeFileSync(Ue.join(this.currentDir,`annexure-${e}.md`),o+n.trimEnd()+`
618
+ `;ze.writeFileSync(He.join(this.currentDir,`annexure-${e}.md`),o+n.trimEnd()+`
619
619
  `,"utf8")}finish(){if(this.currentDir&&this.lastAnswer&&this.query){let e=this.startedAt?Date.now()-this.startedAt:0,r=[...this.agentToOrdinal.values()].sort((d,c)=>d-c).map(d=>{let c=this.taskByOrdinal.get(d);return`- [Annexure ${d}](./annexure-${d}.md)${c?` \u2014 ${c}`:""}`}).join(`
620
- `),o=this.synthStats?` \xB7 ${this.synthStats.tokens} synth tokens \xB7 ppl ${this.synthStats.ppl.toFixed(2)}`:"",s=`> ${new Date().toISOString()} \xB7 ${this.mode}${o} \xB7 ${(e/1e3).toFixed(1)}s`,l=r?`
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?`
621
621
  ---
622
622
 
623
623
  ## Annexures
624
624
 
625
625
  ${r}
626
- `:"",a=`# ${this.query}
626
+ `:"",i=`# ${this.query}
627
627
 
628
628
  ${s}
629
629
 
630
630
  ${this.lastAnswer.trim()}
631
- ${l}`;Le.writeFileSync(Ue.join(this.currentDir,"report.md"),a,"utf8")}this.reset()}reset(){this.currentDir=null,this.inResearch=!1,this.spawnOrdinal=0,this.agentToOrdinal.clear(),this.taskByOrdinal.clear(),this.lastAnswer=null,this.query=null,this.mode=null,this.startedAt=null,this.synthStats=null}};var Us=pe.join(process.cwd(),"harness.json"),{values:$,positionals:Fs}=vs({args:process.argv.slice(2),options:{query:{type:"string"},reranker:{type:"string"},corpus:{type:"string"},config:{type:"string"},"findings-budget":{type:"string"},"reasoning-mode":{type:"string"},"n-ctx":{type:"string"},"output-dir":{type:"string"},jsonl:{type:"boolean",default:!1},verbose:{type:"boolean",default:!1}},allowPositionals:!0}),fe=$["reasoning-mode"];fe!==void 0&&fe!=="flat"&&fe!=="deep"&&(process.stderr.write(`Invalid --reasoning-mode: ${fe}. Expected "flat" or "deep".
632
- `),process.exit(1));var He=Fs[0]||void 0,rn=$.jsonl,Or=$.verbose,Ye=$["output-dir"],ue=$.query,de=$.config??Us,je=$["n-ctx"];je!==void 0&&!/^\d+$/.test(je)&&(process.stderr.write(`Invalid --n-ctx: ${je}. Expected a positive integer.
633
- `),process.exit(1));var Br=je!==void 0?parseInt(je,10):void 0,on=Ce(de,{modelPath:He,reranker:$.reranker,corpusPath:$.corpus,reasoningMode:fe,nCtx:Br,outputDir:Ye}),P=on.config,xe=on.origin,$s=$["findings-budget"]?parseInt($["findings-budget"],10):void 0,en=Ne(P.model.path,"llm"),tn=Ne(P.model.reranker,"reranker"),Ir=en.path,_r=tn.path,Ws=P.model.nCtx??32768;rn&&an(!0);Or&&ln(!0);var zs=!Or&&!rn;if(zs)try{z.closeSync(2),z.openSync(process.platform==="win32"?"\\\\.\\NUL":"/dev/null","w")}catch{}var Hs=10,nn=new Map;function*Mr(t,e){let n=nn.get(t);if(n)return n;let{cwd:r,pattern:o}=Ns(t),s=o??"**/*.{md,mdx}",l=pe.join(r,".gitignore"),a=z.existsSync(l)?Ls().add(z.readFileSync(l,"utf8")):null,d=z.globSync(s,{cwd:r}),c=(a?d.filter(S=>!a.ignores(S)):d).sort();if(c.length===0)throw new Error(`No .md(x) files at ${r}${o?` matching ${o}`:""}`);e.send({type:"weights:label",label:`Indexing corpus (${c.length} files)\u2026`});let u=[];for(let S=0;S<c.length;S++){let q=c[S];e.send({type:"weights:label",label:`Indexing: ${q} (${S+1}/${c.length})`}),yield*Be(()=>new Promise(E=>{setImmediate(()=>{try{u.push({name:q,content:z.readFileSync(pe.join(r,q),"utf8")})}catch{}E()})}))}e.send({type:"weights:label",label:"Chunking corpus\u2026"}),yield*Be(()=>new Promise(S=>setImmediate(S)));let m=qs(u),w={resources:u,chunks:m};return nn.set(t,w),w}function Oe(t){let e=[];if(t.sources.corpusPath){let n=nn.get(t.sources.corpusPath);n&&e.push(new Ds(n.resources,n.chunks,{grep:{maxResults:50,lineMaxChars:200},readFile:{defaultMaxLines:100}}))}return t.sources.tavilyKey&&e.push(new Bs(new Ms(t.sources.tavilyKey),{topN:5,fetch:{maxChars:3e3,topK:5,timeout:1e4,tokenBudget:1200}})),e}function Jt(t){if(t.length===0)return"";let e=["Available research sources:"],n=!1;for(let r of t){let o=r;if(typeof o.promptData=="function"){let s=o.promptData();e.push("","## Local corpus"),e.push("Files and top-level topics (full-text searchable via grep/read/search tools):"),s.toc&&e.push(s.toc)}else r.name==="web"&&(n=!0)}return n&&(e.push("","## Web search"),e.push("web search is available for live web queries (web_search + fetch_page tools).")),e.join(`
634
- `)}var Zt=t=>t instanceof Error?t.message:String(t),Ys=t=>t instanceof Error?t.stack??t.message:String(t);Rs(function*(){let t=pe.basename(Ir).replace(/-Q\w+\.gguf$/,""),e=pe.basename(_r).replace(/-q\w+\.gguf$/i,""),n=yt&&!rn;n||(Ke(),Ke(`${bt.bold} Deep Research${bt.reset}`),Ke());let r=pn(),o=As(),s=[en,tn].filter(i=>i.entry!==null&&!z.existsSync(i.path)).map(i=>({id:i.entry.id,label:i.entry.label,sizeBytes:i.entry.sizeBytes})),l=null;if(n){let i=yield*Be(()=>Promise.resolve().then(()=>(Er(),Pr))),p=[{type:"config:loaded",config:P,origin:xe,path:on.path}];s.length>0&&p.push({type:"download:plan",entries:s}),l=i.render(r,h=>o.send(h),p),yield*Xt(()=>{l?.unmount()})}else r.subscribe(i=>{cn(i.type,i)});function*a(i){if(z.existsSync(i.path))return i.path;if(!i.entry)throw new Error(`Model not found: ${i.path}. Pass --model <path> or use /model <path> to set a local .gguf file.`);let p=i.entry;return r.send({type:"download:start",id:p.id,label:p.label,sizeBytes:p.sizeBytes}),yield*Be(()=>In(p,{onProgress:(h,x,O)=>{r.send({type:"download:progress",id:p.id,got:h,total:x,url:O})}})),r.send({type:"download:complete",id:p.id}),i.path}function d(i){let p=i.filter(h=>h.entry!==null&&!z.existsSync(h.path)).map(h=>({id:h.entry.id,label:h.entry.label,sizeBytes:h.entry.sizeBytes}));p.length>0&&r.send({type:"download:plan",entries:p})}function*c(){for(let i of yield*Se(o)){if(i.type==="quit"||i.type==="set_model_path"||i.type==="set_reranker_path")return yield*Se.next(),i;yield*Se.next()}return{type:"quit"}}let u=en,m=Ir,w=t,S=tn,q=_r,E=e,y=null,g=null,I=!0;for(;y===null||g===null;){let i="llm";try{I||d([u,S]),I=!1,i="llm",yield*a(u),i="reranker",yield*a(S),i="llm",r.send({type:"weights:start",label:`Loading ${w}\u2026`}),y=yield*Be(()=>Es({modelPath:m,nCtx:Ws,nSeqMax:64,typeK:"q4_0",typeV:"q4_0"})),i="reranker",r.send({type:"weights:label",label:`Loading ${E}\u2026`}),g=yield*Be(()=>Os(q,{nSeqMax:8,nCtx:16384}))}catch(p){if(y){try{y.dispose?.()}catch{}y=null}g=null,r.send({type:"boot:error",kind:i,message:Zt(p)});let h=yield*c();h.type==="quit"&&(l?.unmount(),process.exit(0)),h.type==="set_model_path"?(ve({model:{path:h.path}},de),u=Ne(h.path,"llm"),m=u.path,w=u.entry?.label??pe.basename(m)):(ve({model:{reranker:h.path}},de),S=Ne(h.path,"reranker"),q=S.path,E=S.entry?.label??pe.basename(q));let x=Ce(de,{modelPath:h.type==="set_model_path"?h.path:He,reranker:h.type==="set_reranker_path"?h.path:$.reranker,corpusPath:$.corpus,reasoningMode:fe,outputDir:Ye,nCtx:Br});P=x.config,xe=x.origin}}yield*Xt(()=>{g.dispose()}),r.send({type:"weights:done"});let W=ye(P.sources.outputDir||process.cwd());z.mkdirSync(W,{recursive:!0});let R=new Date().toISOString().replace(/[:.]/g,"-").replace("Z",""),ge=pe.join(W,`trace-${R}.jsonl`),Z=z.openSync(ge,"w"),re=new _s(Z);yield*Xt(()=>{re.flush();try{z.closeSync(Z)}catch{}});let Y=new Xe,{session:C,events:b}=yield*Is(y,{traceWriter:re});if(yield*Ps(function*(){for(let i of yield*Se(b))Y.handle(i),r.send(i),yield*Se.next()}),P.sources.corpusPath)try{let i=yield*Mr(P.sources.corpusPath,r);r.send({type:"corpus:indexed",corpusPath:P.sources.corpusPath,fileCount:i.resources.length,chunkCount:i.chunks.length})}catch(i){r.send({type:"ui:error",message:`Corpus disabled: ${i.message}. Use /scan to fix.`})}r.send({type:"ui:composer"});let Q={maxTurns:Hs,findingsMaxChars:$s,reasoningMode:P.defaults.reasoningMode};function oe(i,p){let h=P.sources.outputDir??process.cwd();Y.start({outputDir:h,query:i,mode:p})}if(!n){ue||(process.stderr.write(`Non-TTY mode requires --query.
635
- `),process.exit(2));let i=Oe(P);i.length===0&&(process.stderr.write(`No source configured. Set TAVILY_API_KEY, pass --corpus <dir>, or store one in harness.json.
636
- `),process.exit(2));let p=performance.now(),h=yield*Ae(ue,C,i,g,{...Q,wallStartMs:p,onStart:()=>oe(ue,P.defaults.reasoningMode)});h.type==="clarify"&&(process.stderr.write(`Planner asked clarifying questions; non-TTY mode can't answer. Aborting.
637
- `),process.exit(2)),h.type==="research_plan"&&(oe(ue,P.defaults.reasoningMode),yield*qe(ue,h.plan,C,i,g,{...Q,wallStartMs:p}));return}let f=null;if(ue){let i=P.defaults.reasoningMode,p=performance.now(),h=Oe(P),x=yield*Ae(ue,C,h,g,{...Q,reasoningMode:i,wallStartMs:p,onStart:()=>oe(ue,i)});x.type==="research_plan"?(f={plan:x.plan,query:ue,mode:i,wallStartMs:p},yield*b.send({type:"ui:plan_review"})):x.type==="clarify"?f={plan:x.plan,query:ue,mode:i,wallStartMs:p}:yield*b.send({type:"ui:composer"})}for(let i of yield*Se(o))try{if(i.type==="quit")break;if(i.type==="set_tavily_key"){P={...P,sources:{...P.sources,tavilyKey:i.key}};let p=ve({sources:{tavilyKey:i.key}},de),h=Ce(de,{modelPath:He,reranker:$.reranker,corpusPath:$.corpus,reasoningMode:fe,outputDir:Ye});P=h.config,xe=h.origin,yield*b.send({type:"config:updated",config:P,origin:xe,savedTo:p.path,gitignored:p.gitignored,skipped:p.skipped})}else if(i.type==="set_output_dir"){let p=i.path?ye(i.path):"",h=ve({sources:{outputDir:p}},de),x=Ce(de,{modelPath:He,reranker:$.reranker,corpusPath:$.corpus,reasoningMode:fe,outputDir:Ye});P=x.config,xe=x.origin,yield*b.send({type:"config:updated",config:P,origin:xe,savedTo:h.path,gitignored:h.gitignored,skipped:h.skipped})}else if(i.type==="set_corpus_path"){let p=i.path?ye(i.path):"";if(p){r.send({type:"weights:start",label:"Indexing corpus\u2026"});let O;try{O=yield*Mr(p,r)}catch(T){r.send({type:"weights:done"}),yield*b.send({type:"ui:error",message:`Cannot use ${p}: ${T.message}`});continue}r.send({type:"corpus:indexed",corpusPath:p,fileCount:O.resources.length,chunkCount:O.chunks.length}),r.send({type:"weights:done"})}let h=ve({sources:{corpusPath:p}},de),x=Ce(de,{modelPath:He,reranker:$.reranker,corpusPath:$.corpus,reasoningMode:fe,outputDir:Ye});P=x.config,xe=x.origin,yield*b.send({type:"config:updated",config:P,origin:xe,savedTo:h.path,gitignored:h.gitignored,skipped:h.skipped}),p&&(yield*b.send({type:"ui:composer"}))}else if(i.type==="submit_query"){let p=Oe(P);if(p.length===0){yield*b.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."});continue}let h=performance.now();if(i.skipPlanner){let O=Ct(i.query);yield*b.send({type:"plan:start",query:i.query,mode:i.mode}),yield*b.send({type:"query",query:i.query,warm:!!C.trunk}),yield*b.send({type:"plan",intent:O.intent,tasks:O.tasks,clarifyQuestions:O.clarifyQuestions,tokenCount:O.tokenCount,timeMs:O.timeMs}),oe(i.query,i.mode),yield*qe(i.query,O,C,p,g,{...Q,reasoningMode:i.mode,wallStartMs:h}),yield*b.send({type:"ui:composer"});continue}let x=yield*Ae(i.query,C,p,g,{...Q,reasoningMode:i.mode,context:Jt(p),wallStartMs:h,onStart:()=>oe(i.query,i.mode)});x.type==="research_plan"?(f={plan:x.plan,query:i.query,mode:i.mode,wallStartMs:h},yield*b.send({type:"ui:plan_review"})):x.type==="clarify"?f={plan:x.plan,query:i.query,mode:i.mode,wallStartMs:h}:yield*b.send({type:"ui:composer"})}else if(i.type==="submit_clarification"&&f){let{query:p,plan:h,mode:x,wallStartMs:O}=f,T=Oe(P),L=["Prior clarification exchange:",...h.clarifyQuestions.map((ft,Dr)=>`(${Dr+1}) ${ft}`),"",`User response: ${i.answer}`,"","Use this exchange to proceed with research if possible."].join(`
638
- `),V=yield*Ae(p,C,T,g,{...Q,reasoningMode:x,context:[Jt(T),L].filter(Boolean).join(`
639
-
640
- `),wallStartMs:O,onStart:()=>oe(p,x)});V.type==="research_plan"?(f={plan:V.plan,query:p,mode:x,wallStartMs:O},yield*b.send({type:"ui:plan_review"})):V.type==="clarify"?f={plan:V.plan,query:p,mode:x,wallStartMs:O}:(f=null,yield*b.send({type:"ui:composer"}))}else if(i.type==="change_mode"&&f){let p=Oe(P),h=yield*Ae(f.query,C,p,g,{...Q,reasoningMode:i.mode,context:Jt(p),wallStartMs:f.wallStartMs,onStart:()=>oe(f.query,i.mode)});h.type==="research_plan"?(f={...f,plan:h.plan,mode:i.mode},yield*b.send({type:"ui:plan_review"})):h.type==="clarify"?f={...f,plan:h.plan,mode:i.mode}:(f=null,yield*b.send({type:"ui:composer"}))}else if(i.type==="accept_plan"&&f){if(f.plan.intent==="clarify"){f=null,yield*b.send({type:"ui:composer"});continue}let p=Oe(P);if(p.length===0){yield*b.send({type:"ui:error",message:"No source configured. Add Tavily key or corpus path."}),f=null;continue}oe(f.query,f.mode),yield*qe(f.query,f.plan,C,p,g,{...Q,reasoningMode:f.mode,wallStartMs:f.wallStartMs}),f=null,yield*b.send({type:"ui:composer"})}else if(i.type==="cancel_plan")f=null,yield*b.send({type:"ui:composer"});else if(i.type==="edit_plan")f=null,yield*b.send({type:"ui:composer",prefill:i.query});else if(i.type==="update_task_description"&&f)f.plan.tasks=f.plan.tasks.map((p,h)=>h===i.index?{...p,description:i.description}:p),yield*b.send({type:"plan:task_updated",index:i.index,description:i.description});else if(i.type==="add_task"&&f){let p=Math.max(0,Math.min(f.plan.tasks.length,i.afterIndex+1));f.plan.tasks=[...f.plan.tasks.slice(0,p),{description:""},...f.plan.tasks.slice(p)],yield*b.send({type:"plan:task_added",afterIndex:i.afterIndex})}else if(i.type==="delete_task"&&f)f.plan.tasks.length>1&&(f.plan.tasks=f.plan.tasks.filter((p,h)=>h!==i.index),yield*b.send({type:"plan:task_deleted",index:i.index}));else if(i.type==="move_task"&&f){let p=f.plan.tasks.length;if(i.from!==i.to&&i.from>=0&&i.from<p&&i.to>=0&&i.to<p){let h=[...f.plan.tasks],[x]=h.splice(i.from,1);h.splice(i.to,0,x),f.plan.tasks=h,yield*b.send({type:"plan:task_moved",from:i.from,to:i.to})}}}catch(p){f=null,yield*b.send({type:"ui:error",message:Zt(p)})}finally{yield*Se.next()}}).catch(t=>{process.stderr.write(`Error: ${Zt(t)}
641
- ${Ys(t)}
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)}
642
642
  `),process.exit(1)});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "reasoning.run",
3
- "version": "0.1.1",
4
- "description": "Local deep-research agent composer runs on your machine, zero-config after the first query. Built with Lloyal HDK.",
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
  },
@@ -42,13 +42,20 @@
42
42
  "node": ">=22"
43
43
  },
44
44
  "keywords": [
45
+ "reasoning",
46
+ "private-reasoner",
45
47
  "deep-research",
46
- "local-llm",
48
+ "grounded-reasoning",
49
+ "multi-agent",
47
50
  "agents",
51
+ "rag",
52
+ "local-llm",
53
+ "offline",
54
+ "on-device",
55
+ "gpu",
48
56
  "llama.cpp",
49
57
  "cli",
50
- "tui",
51
- "ink"
58
+ "tui"
52
59
  ],
53
60
  "repository": {
54
61
  "type": "git",