mlai-code 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/bin/mlai.mjs +3 -0
- package/package.json +18 -3
- package/src/browser-setup.mjs +77 -0
- package/src/cli-ext.mjs +146 -0
- package/src/cli.mjs +534 -0
- package/src/cloud.mjs +29 -0
- package/src/completion.mjs +159 -0
- package/src/credentials.mjs +54 -0
- package/src/deploy.mjs +134 -0
- package/src/distribution.mjs +373 -0
- package/src/engine-key.mjs +4 -0
- package/src/engine.mjs +167 -0
- package/src/headless.mjs +196 -0
- package/src/home.mjs +22 -0
- package/src/host.mjs +123 -0
- package/src/local-models.mjs +64 -0
- package/src/modes.mjs +38 -0
- package/src/netbox.mjs +97 -0
- package/src/netjail.py +59 -0
- package/src/offline.mjs +98 -0
- package/src/parity.mjs +86 -0
- package/src/project.mjs +68 -0
- package/src/relay.mjs +140 -0
- package/src/render.mjs +73 -0
- package/src/restricted.mjs +47 -0
- package/src/review.mjs +70 -0
- package/src/runner.mjs +127 -0
- package/src/runtime.mjs +75 -0
- package/src/sandbox.mjs +135 -0
- package/src/sdk.mjs +11 -0
- package/src/server.mjs +110 -0
- package/src/session.mjs +290 -0
- package/src/settings.mjs +135 -0
- package/src/shared-data.mjs +3 -0
- package/src/tui/acp.mjs +145 -0
- package/src/tui/agents-cli.mjs +114 -0
- package/src/tui/agents-local.mjs +65 -0
- package/src/tui/ansi.mjs +123 -0
- package/src/tui/app.mjs +710 -0
- package/src/tui/approval.mjs +88 -0
- package/src/tui/bg.mjs +172 -0
- package/src/tui/bgterm.mjs +79 -0
- package/src/tui/chat.mjs +230 -0
- package/src/tui/clipboard.mjs +74 -0
- package/src/tui/cloud-cli.mjs +57 -0
- package/src/tui/cloud-run.mjs +123 -0
- package/src/tui/cmd-agents.mjs +130 -0
- package/src/tui/cmd-auto-review.mjs +94 -0
- package/src/tui/cmd-cloud.mjs +17 -0
- package/src/tui/cmd-config.mjs +104 -0
- package/src/tui/cmd-core.mjs +160 -0
- package/src/tui/cmd-distribution.mjs +15 -0
- package/src/tui/cmd-ecosystem.mjs +169 -0
- package/src/tui/cmd-extensibility.mjs +333 -0
- package/src/tui/cmd-remote.mjs +18 -0
- package/src/tui/cmd-review.mjs +58 -0
- package/src/tui/cmd-session-extra.mjs +152 -0
- package/src/tui/cmd-tui.mjs +200 -0
- package/src/tui/commands.mjs +160 -0
- package/src/tui/custom-commands.mjs +98 -0
- package/src/tui/diff.mjs +60 -0
- package/src/tui/editor.mjs +190 -0
- package/src/tui/ext-state.mjs +16 -0
- package/src/tui/extensions-local.mjs +140 -0
- package/src/tui/files.mjs +72 -0
- package/src/tui/handoff.mjs +110 -0
- package/src/tui/import-setups.mjs +151 -0
- package/src/tui/init.mjs +104 -0
- package/src/tui/keymap.mjs +70 -0
- package/src/tui/keys.mjs +101 -0
- package/src/tui/loop.mjs +75 -0
- package/src/tui/markdown.mjs +118 -0
- package/src/tui/mcp-config.mjs +225 -0
- package/src/tui/mcp-oauth.mjs +162 -0
- package/src/tui/permissions.mjs +189 -0
- package/src/tui/plain.mjs +32 -0
- package/src/tui/plugins-local.mjs +103 -0
- package/src/tui/remote.mjs +125 -0
- package/src/tui/review-cli.mjs +332 -0
- package/src/tui/review-github.mjs +59 -0
- package/src/tui/screen.mjs +60 -0
- package/src/tui/session-ops.mjs +104 -0
- package/src/tui/skills-local.mjs +92 -0
- package/src/tui/snapshots.mjs +87 -0
- package/src/tui/statusline.mjs +98 -0
- package/src/tui/transcript.mjs +116 -0
- package/src/two-words.mjs +36 -0
- package/src/wakeups.mjs +53 -0
- package/src/winenv.mjs +94 -0
- package/src/winsandbox.py +351 -0
- package/src/workspace-api.mjs +621 -0
- package/src/worktree.mjs +128 -0
- package/vendor/client-sdk/controller.cjs +115 -0
- package/vendor/client-sdk/files.cjs +38 -0
- package/vendor/client-sdk/index.cjs +133 -0
- package/vendor/client-sdk/login.cjs +52 -0
- package/vendor/client-sdk/updates.cjs +41 -0
- package/vendor/cloud-cli/mlai.mjs +394 -0
- package/worker/architecture_parse.cjs +23 -0
- package/worker/architecture_worker.py +394 -0
- package/worker/ask_first.py +96 -0
- package/worker/attachment_reader.py +66 -0
- package/worker/background_jobs.py +111 -0
- package/worker/brief_questions.py +56 -0
- package/worker/browser_local.py +49 -0
- package/worker/browser_pane.py +89 -0
- package/worker/browser_tool.py +101 -0
- package/worker/build_planner.py +187 -0
- package/worker/chat_fork.py +277 -0
- package/worker/checkpoints.py +133 -0
- package/worker/cloud_pty.py +351 -0
- package/worker/command_policy.py +39 -0
- package/worker/command_safety.py +717 -0
- package/worker/computer_card.sh +23 -0
- package/worker/computer_setup.sh +86 -0
- package/worker/computer_use.py +221 -0
- package/worker/connector_search.py +43 -0
- package/worker/context_manager.py +60 -0
- package/worker/conversation.py +144 -0
- package/worker/deploy_pack.py +116 -0
- package/worker/design_director.py +240 -0
- package/worker/dev_jobs.py +166 -0
- package/worker/edit_guard.py +99 -0
- package/worker/env_setup.py +129 -0
- package/worker/evidence.py +109 -0
- package/worker/fast_search.py +24 -0
- package/worker/git_sync.py +333 -0
- package/worker/goals.py +156 -0
- package/worker/handover.py +98 -0
- package/worker/harness_memory.py +194 -0
- package/worker/image_generation.py +173 -0
- package/worker/intelligence.py +149 -0
- package/worker/intent_model.py +78 -0
- package/worker/intent_weights.json +1 -0
- package/worker/ios_simulator.py +87 -0
- package/worker/kimi_bridge.py +997 -0
- package/worker/kimi_compact.py +93 -0
- package/worker/kimi_gates.py +304 -0
- package/worker/kimi_hook.py +617 -0
- package/worker/lifecycle.py +95 -0
- package/worker/lsp.py +77 -0
- package/worker/mcp_local.py +293 -0
- package/worker/memory.py +99 -0
- package/worker/mlai_auto_review.py +177 -0
- package/worker/mlai_hooks.py +966 -0
- package/worker/mlai_mcp.py +441 -0
- package/worker/mlai_permissions.py +283 -0
- package/worker/model_stream.py +75 -0
- package/worker/nested_repos.py +76 -0
- package/worker/offline_guard.py +17 -0
- package/worker/preview.py +806 -0
- package/worker/proc_watch.py +124 -0
- package/worker/project_context.py +72 -0
- package/worker/project_rules.py +99 -0
- package/worker/quality.py +180 -0
- package/worker/reply_language.py +56 -0
- package/worker/repo_hygiene.py +132 -0
- package/worker/repo_memory.py +101 -0
- package/worker/repo_policy.py +269 -0
- package/worker/roles.json +3173 -0
- package/worker/roles.py +303 -0
- package/worker/runner.py +1795 -0
- package/worker/runtime_control.py +205 -0
- package/worker/secret_scan.py +168 -0
- package/worker/session_hub.py +80 -0
- package/worker/skill_library.py +129 -0
- package/worker/skill_pack.py +533 -0
- package/worker/subagents.py +91 -0
- package/worker/task_controller.py +139 -0
- package/worker/task_skills.py +159 -0
- package/worker/team_checkpoint.py +33 -0
- package/worker/token_count.py +32 -0
- package/worker/tool_catalog.py +38 -0
- package/worker/upload_storage.py +531 -0
- package/worker/verification.py +725 -0
- package/worker/vision.py +84 -0
- package/worker/wakeups.py +63 -0
- package/worker/web_tools.py +203 -0
- package/worker/winproc.py +135 -0
- package/worker/work_ledger.py +117 -0
- package/worker/worktrees.py +79 -0
package/src/tui/app.mjs
ADDED
|
@@ -0,0 +1,710 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The full terminal interface for `mlai` (CLI v1, owner: TUI). Dependency-free; runs in any VT terminal including
|
|
3
|
+
* Windows Terminal and PowerShell. Without a TTY, with TERM=dumb or MLAI_PLAIN=1, cli.mjs uses the plain loop instead
|
|
4
|
+
* (useTui() decides).
|
|
5
|
+
*
|
|
6
|
+
* runTui({session, settings, cloud, flags, first, images, send, makeCtx, onSessionChange, chat}) -> exit code
|
|
7
|
+
*
|
|
8
|
+
* Layout: the conversation is printed into the terminal's normal scrollback; below it a live footer holds the
|
|
9
|
+
* streaming reply, the activity line, the input box, popups and the status line (screen.mjs).
|
|
10
|
+
*/
|
|
11
|
+
import {readFile} from 'node:fs/promises';
|
|
12
|
+
import {spawn} from 'node:child_process';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import {theme as makeTheme,resolveTheme,colorAllowed,boxChars,width,truncate,wrap,charWidth,strip} from './ansi.mjs';
|
|
15
|
+
import {keyReader} from './keys.mjs';
|
|
16
|
+
import {Editor,loadHistory,saveHistory} from './editor.mjs';
|
|
17
|
+
import {Screen} from './screen.mjs';
|
|
18
|
+
import {Transcript,previewLines} from './transcript.mjs';
|
|
19
|
+
import {approvalLines,ruleFor,ruleMatches,parseApproval} from './approval.mjs';
|
|
20
|
+
import {projectEntries,rankPaths,atToken,droppedImage,clearEntries} from './files.mjs';
|
|
21
|
+
import {statusData,statusLine,customStatus,gitBranch,modeStyle} from './statusline.mjs';
|
|
22
|
+
import * as registry from './commands.mjs';
|
|
23
|
+
import {MODES,modeName,nextMode,applyMode,sessionMode} from '../modes.mjs';
|
|
24
|
+
import {summaryLine} from '../render.mjs';
|
|
25
|
+
import {sandboxKind,SANDBOXES} from '../sandbox.mjs';
|
|
26
|
+
import {sub} from '../home.mjs';
|
|
27
|
+
import {terminals,backgroundCommand,powershellEnv} from './bgterm.mjs';
|
|
28
|
+
import {readClipboardImage} from './clipboard.mjs';
|
|
29
|
+
import {resolveKeymap,actionFor,labelOf,specOf} from './keymap.mjs';
|
|
30
|
+
|
|
31
|
+
/** Whether the full TUI can run here. */
|
|
32
|
+
export function useTui(env=process.env,stdout=process.stdout,stdin=process.stdin,settings={}){
|
|
33
|
+
if(env.MLAI_PLAIN==='1'||env.MLAI_NO_TUI==='1'||env.TERM==='dumb')return false;
|
|
34
|
+
const choice=env.MLAI_TUI||settings?.tui||'auto';
|
|
35
|
+
if(choice==='plain'||choice==='0')return false;
|
|
36
|
+
return Boolean(stdout?.isTTY&&stdin?.isTTY&&typeof stdin.setRawMode==='function');
|
|
37
|
+
}
|
|
38
|
+
const SPIN=['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'],SPIN_ASCII=['-','\\','|','/'];
|
|
39
|
+
const PLACEHOLDER='Type a task. / for commands, @ for files, ! for a shell command';
|
|
40
|
+
const elapsed=ms=>{const s=Math.floor(ms/1000);return s<60?s+'s':Math.floor(s/60)+'m '+String(s%60).padStart(2,'0')+'s'};
|
|
41
|
+
|
|
42
|
+
/** Visual rows of the input: word-wrapped at `cols` (long words are cut), with where the cursor lands. */
|
|
43
|
+
export function layoutInput(text,cursor,cols){
|
|
44
|
+
text=String(text);const rows=[];let cur={row:0,col:0};let base=0;
|
|
45
|
+
for(const line of text.split('\n')){
|
|
46
|
+
// Break the line into [start,end) ranges of code units.
|
|
47
|
+
const ranges=[];let start=0,w=0,lastSpace=-1;
|
|
48
|
+
for(let i=0;i<line.length;){
|
|
49
|
+
const cp=line.codePointAt(i),n=cp>0xffff?2:1,cw=charWidth(String.fromCodePoint(cp));
|
|
50
|
+
if(w+cw>cols&&i>start){
|
|
51
|
+
if(line[i]===' '){ranges.push([start,i+1]);start=i+1;w=0;lastSpace=-1;i+=n;continue}
|
|
52
|
+
if(lastSpace>start){ranges.push([start,lastSpace+1]);start=lastSpace+1;w=width(line.slice(start,i));lastSpace=-1;continue}
|
|
53
|
+
ranges.push([start,i]);start=i;w=0;lastSpace=-1;continue;
|
|
54
|
+
}
|
|
55
|
+
if(line[i]===' ')lastSpace=i;
|
|
56
|
+
w+=cw;i+=n;
|
|
57
|
+
}
|
|
58
|
+
ranges.push([start,line.length]);
|
|
59
|
+
const c=cursor-base;
|
|
60
|
+
ranges.forEach(([a,b],ri)=>{
|
|
61
|
+
const last=ri===ranges.length-1;
|
|
62
|
+
if(c>=a&&(c<b||(last&&c===b)))cur={row:rows.length,col:width(line.slice(a,c))};
|
|
63
|
+
rows.push(line.slice(a,b));
|
|
64
|
+
});
|
|
65
|
+
// A cursor at the very end of a full row goes to the start of the next visual row.
|
|
66
|
+
if(c===line.length&&cur.row===rows.length-1&&cur.col>=cols){rows.push('');cur={row:rows.length-1,col:0}}
|
|
67
|
+
base+=line.length+1;
|
|
68
|
+
}
|
|
69
|
+
return {rows,cursor:cur};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function runTui({session,settings={},cloud=null,flags={},first=null,images=[],send,makeCtx,onSessionChange,chat=null,
|
|
73
|
+
stdin=process.stdin,stdout=process.stdout,env=process.env,historyFile=path.join(sub('state'),'history.jsonl')}={}){
|
|
74
|
+
const color=colorAllowed(stdout,env);
|
|
75
|
+
let themeName=resolveTheme(settings.theme||'auto',env);
|
|
76
|
+
let syntaxName=settings.syntaxTheme||'default';
|
|
77
|
+
let t=makeTheme(themeName,{color,syntax:syntaxName});
|
|
78
|
+
const box=boxChars(env);
|
|
79
|
+
const screen=new Screen(stdout);
|
|
80
|
+
const editor=new Editor({history:await loadHistory(historyFile),vim:Boolean(settings.vim)});
|
|
81
|
+
const tr=new Transcript({t,box,cols:screen.cols,verbose:Boolean(flags.verbose),raw:Boolean(settings.rawScrollback)});
|
|
82
|
+
const sandbox=SANDBOXES.includes(sandboxKind());
|
|
83
|
+
if(chat?.session)session=chat.session;
|
|
84
|
+
const flagImages=[].concat(images||[],flags.images||[],flags.image||[]).filter(x=>typeof x==='string');
|
|
85
|
+
const st={running:false,started:0,activity:'',preview:'',frame:0,modal:null,sel:0,popupKey:'',lastEsc:0,lastCtrlC:0,hint:'',hintUntil:0,
|
|
86
|
+
shellContext:[],images:[],branch:null,context:null,custom:null,customAt:0,approvals:[],rules:new Set(),lastAnswer:'',exiting:false,completions:null,queue:[],cancelled:false,title:null,jobsSeen:new Set()};
|
|
87
|
+
let exitResolve;const exited=new Promise(r=>exitResolve=r);
|
|
88
|
+
let suggestRule=null;import('./permissions.mjs').then(m=>{if(typeof m.suggestRule==='function')suggestRule=m.suggestRule}).catch(()=>{});
|
|
89
|
+
|
|
90
|
+
const ctxUse=()=>{const c=chat?.context;if(c?.used)return {used:c.used,window:c.window||st.window||null};return st.context?{used:st.context.used,window:st.context.window||st.window||null}:null};
|
|
91
|
+
const setModeAll=async m=>{if(chat?.setMode)await chat.setMode(m);else await applyMode(session,m)};
|
|
92
|
+
const curMode=()=>modeName(chat?.mode)||(session?.meta?sessionMode(session.meta):'agent');
|
|
93
|
+
// ---------- output helpers ----------
|
|
94
|
+
const print=lines=>{tr.cols=screen.cols;const l=Array.isArray(lines)?lines:String(lines).split('\n');screen.print(l);st.lastLine=strip(l.at(-1)??'').trim();draw()};
|
|
95
|
+
const flash=(text,ms=2500)=>{st.hint=text;st.hintUntil=Date.now()+ms;draw()};
|
|
96
|
+
const title=s=>{if(stdout.isTTY)stdout.write('\x1b]0;'+s.replace(/[\x00-\x1f]/g,'')+'\x07')};
|
|
97
|
+
const titleMode=()=>{const v=liveSettings?.()?.terminalTitle??settings.terminalTitle;return typeof v==='string'&&v?v:'auto'};
|
|
98
|
+
const setTitle=()=>{
|
|
99
|
+
const mode=titleMode();if(mode==='off'&&!st.title)return;
|
|
100
|
+
const state=st.modal?.type==='approval'?'needs approval':st.running?'working':'';
|
|
101
|
+
const fixed=st.title||(mode!=='auto'&&mode!=='off'?mode:null);
|
|
102
|
+
title(fixed?fixed+(state?' · '+state:''):'mlai'+(state?' · '+state:'')+' · '+(session?.meta?.folder||''));
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// ---------- ui + ctx (the shared command contract) ----------
|
|
106
|
+
const ui={
|
|
107
|
+
get theme(){return themeName},
|
|
108
|
+
print:text=>print(String(text).split('\n')),
|
|
109
|
+
error:text=>print(String(text).split('\n').map(l=>t.warn(l))),
|
|
110
|
+
confirm:(question,{default:d=false}={})=>new Promise(resolve=>{st.modal={type:'confirm',question,default:d,resolve};draw()}),
|
|
111
|
+
pick:(items,{title:ttl='Choose',filter=''}={})=>new Promise(resolve=>{
|
|
112
|
+
const rows=items.map(i=>typeof i==='string'?{label:i,value:i}:i);
|
|
113
|
+
const ed=new Editor();ed.set(filter||'');st.modal={type:'pick',title:ttl,rows,editor:ed,sel:0,resolve};draw();
|
|
114
|
+
}),
|
|
115
|
+
input:(question,{default:d=null}={})=>new Promise(resolve=>{const ed=new Editor();if(d!=null)ed.set(String(d));st.modal={type:'input',question,editor:ed,resolve};draw()}),
|
|
116
|
+
setSession:s=>setSession(s),
|
|
117
|
+
setMode:m=>{const n=modeName(m);if(n&&session?.meta){session.meta.cliMode=n}draw()},
|
|
118
|
+
status:()=>({...statusData({chat,session,settings:liveSettings(),running:st.running,branch:st.branch,context:ctxUse()}),vim:editor.vim,vimMode:editor.vimMode,theme:themeName,syntax:syntaxName,raw:tr.raw,queued:st.queue.length,jobs:terminals.running().length}),
|
|
119
|
+
spinner:text=>{const prev=st.activity;st.activity=String(text||'');st.spinning=true;startTicker();draw();return ()=>{st.spinning=false;st.activity=prev;if(!st.running)stopTicker();draw()}},
|
|
120
|
+
attachImage:async p=>attachImage(p),
|
|
121
|
+
toggleTools:()=>toggleTools(),
|
|
122
|
+
setVim:on=>{editor.vim=Boolean(on);editor.vimMode='insert';draw()},
|
|
123
|
+
setTheme:name=>{themeName=resolveTheme(name,env);t=makeTheme(themeName,{color,syntax:syntaxName});tr.t=t;draw()},
|
|
124
|
+
get syntax(){return syntaxName},
|
|
125
|
+
setSyntax:name=>{syntaxName=name;t=makeTheme(themeName,{color,syntax:syntaxName});tr.t=t;draw()},
|
|
126
|
+
get raw(){return tr.raw},
|
|
127
|
+
setRaw:on=>{tr.raw=Boolean(on);draw()},
|
|
128
|
+
setTitle:text=>{st.title=text==null||text==='auto'||text==='off'?null:String(text).slice(0,200);if(text==='off'&&!st.title)title('');setTitle();draw()},
|
|
129
|
+
pickMany:(items,{title:ttl='Choose',selected=[],preview=null}={})=>new Promise(resolve=>{
|
|
130
|
+
const rows=items.map(i=>typeof i==='string'?{label:i,value:i}:i);
|
|
131
|
+
st.modal={type:'multi',title:ttl,rows,on:new Set(selected),sel:0,resolve,preview:typeof preview==='function'?on=>{try{return preview(on,{t,cols:screen.cols,box})}catch{return ''}}:null};draw();
|
|
132
|
+
}),
|
|
133
|
+
captureKey:(question='Press a key')=>new Promise(resolve=>{st.modal={type:'capture',question,resolve};draw()}),
|
|
134
|
+
keymap:()=>keymap(),
|
|
135
|
+
queued:()=>[...st.queue],
|
|
136
|
+
queue:text=>queueTask(text),
|
|
137
|
+
// Answered from another device (tui/remote.mjs): close the card, show the next one.
|
|
138
|
+
dismissApproval:id=>{st.approvals=st.approvals.filter(a=>a.id!==id);if((st.modal?.type==='approval'||st.modal?.type==='feedback')&&st.modal.a?.id===id){st.modal=null;nextApproval()}else draw()},
|
|
139
|
+
};
|
|
140
|
+
// Shell commands get the full process environment (PATH, SystemRoot on Windows) with the interface's overrides on top.
|
|
141
|
+
const shellEnv=env===process.env?env:{...process.env,...env};
|
|
142
|
+
const exec=(command,{cwd=session?.meta?.root||process.cwd()}={})=>new Promise(resolve=>{
|
|
143
|
+
const win=process.platform==='win32';
|
|
144
|
+
const p=spawn(win?'powershell.exe':(env.SHELL||'/bin/sh'),win?['-NoProfile','-Command',command]:['-c',command],{cwd,env:win?powershellEnv(shellEnv):shellEnv,windowsHide:true});
|
|
145
|
+
let stdout2='',stderr='';p.stdout.on('data',d=>{stdout2+=d;if(stdout2.length>2e6)stdout2=stdout2.slice(-1e6)});p.stderr.on('data',d=>{stderr+=d;if(stderr.length>2e6)stderr=stderr.slice(-1e6)});
|
|
146
|
+
st.shellChild=p;
|
|
147
|
+
p.on('error',e=>resolve({code:127,stdout:stdout2,stderr:stderr+e.message}));
|
|
148
|
+
p.on('close',code=>{st.shellChild=null;resolve({code:code??1,stdout:stdout2,stderr})});
|
|
149
|
+
});
|
|
150
|
+
const ctx=makeCtx?makeCtx(ui):{session,settings,ui,out:ui.print,exec,server:cloud};
|
|
151
|
+
const liveSettings=()=>{const v=ctx?.settings;return v&&typeof v==='object'?v:settings};
|
|
152
|
+
if(!ctx.exec)ctx.exec=exec;
|
|
153
|
+
const keymap=()=>resolveKeymap(liveSettings().keymap);
|
|
154
|
+
const syncCtx=()=>{try{ctx.session=session}catch{}};
|
|
155
|
+
|
|
156
|
+
// ---------- session wiring ----------
|
|
157
|
+
let unsub=()=>{};
|
|
158
|
+
function subscribe(s){
|
|
159
|
+
unsub();if(!s)return;
|
|
160
|
+
const onEvent=e=>handleEvent(e),onStarted=e=>{if(e?.tokensLeft!=null&&!chat)st.tokensLeft=e.tokensLeft;if(e?.sandbox&&e.sandbox!=='none'&&flags.verbose)print(t.dim(' sandbox '+e.sandbox))};
|
|
161
|
+
const onIntake=i=>{const q=Array.isArray(i?.questions)?i.questions:[];print(['',t.accent(box.dot)+' '+t.bold(i?.message||'A few details first'),...q.map((x,n)=>' '+t.accent(String(n+1)+'. ')+(x.question||x.text||String(x)))])};
|
|
162
|
+
s.on('event',onEvent);s.on('started',onStarted);s.on('intake',onIntake);
|
|
163
|
+
unsub=()=>{s.off('event',onEvent);s.off('started',onStarted);s.off('intake',onIntake)};
|
|
164
|
+
}
|
|
165
|
+
function setSession(s){if(!s||s===session)return;session=s;syncCtx();subscribe(s);st.context=null;if(!chat||chat.session!==s)onSessionChange?.(s);refreshBranch();setTitle();draw()}
|
|
166
|
+
chat?.on?.('change',()=>draw());
|
|
167
|
+
chat?.on?.('session',s=>setSession(s));
|
|
168
|
+
|
|
169
|
+
function handleEvent(e){
|
|
170
|
+
if(!e||typeof e!=='object')return;
|
|
171
|
+
if(e.type==='error')st.errorShown=true;
|
|
172
|
+
if(e.type==='approval')return onApproval(e);
|
|
173
|
+
if(e.type==='inference'){const used=(Number(e.prompt_tokens)||0)+(Number(e.completion_tokens)||0);if(used)st.context={used,window:st.window||null};return}
|
|
174
|
+
if(e.type==='assistant'||e.type==='answer'){st.preview='';if(e.type==='answer'||e.content)st.lastAnswer=String(e.content||'')}
|
|
175
|
+
if(e.type==='tool'&&e.name!=='todo')st.activity=tr.tool(e.name,e.target)[0].replace(/^\S+ /,'');
|
|
176
|
+
if(e.type==='command')st.activity='Running '+truncate(String(e.command||'').split('\n')[0],60);
|
|
177
|
+
tr.cols=screen.cols;const lines=tr.lines(e);if(lines.length)print(lines);else draw();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------- approvals ----------
|
|
181
|
+
const ruleOf=a=>{try{const p=parseApproval(a);const r=suggestRule?.({kind:p.kind==='write'?'edit':p.kind,command:p.command,path:p.path,name:p.name});if(typeof r==='string'&&r)return r}catch{}return ruleFor(a)};
|
|
182
|
+
function onApproval(a){
|
|
183
|
+
const rule=[...st.rules].find(r=>ruleMatches(r,a));
|
|
184
|
+
if(rule){session.decide(a.id,'approve').catch(()=>{});print(tr.elbow()+t.dim('Allowed by '+rule));return}
|
|
185
|
+
st.approvals.push(a);if(!st.modal||st.modal.type!=='approval')nextApproval();
|
|
186
|
+
}
|
|
187
|
+
function nextApproval(){
|
|
188
|
+
const a=st.approvals.shift();if(!a){if(st.modal?.type==='approval')st.modal=null;setTitle();draw();return}
|
|
189
|
+
const rule=parseApproval(a).kind==='plan'?null:ruleOf(a);
|
|
190
|
+
const view=approvalLines(a,{t,cols:screen.cols,box,expanded:tr.expanded,rule});
|
|
191
|
+
// The tool row just above usually names the same edit; do not repeat it as the card header.
|
|
192
|
+
const same=strip(view.lines[0]||'').trim()===st.lastLine;
|
|
193
|
+
print(same?view.lines.slice(1):['',...view.lines]);
|
|
194
|
+
st.modal={type:'approval',a,rule,view};setTitle();draw();
|
|
195
|
+
if(stdout.isTTY)stdout.write('\x07');
|
|
196
|
+
}
|
|
197
|
+
async function decide(verdict,{feedback=null,always=false}={}){
|
|
198
|
+
const m=st.modal;if(!m||m.type!=='approval'&&m.type!=='feedback')return;
|
|
199
|
+
const a=m.a;st.modal=null;
|
|
200
|
+
try{await session.decide(a.id,verdict)}catch(e){print(t.bad('Could not answer: '+e.message))}
|
|
201
|
+
const plan=parseApproval(a).kind==='plan';
|
|
202
|
+
if(verdict==='approve'){
|
|
203
|
+
if(always&&m.rule){st.rules.add(m.rule);try{await ctx.settings?.save?.('local','permissions',{allow:[m.rule]});print(tr.elbow()+t.ok('Approved')+t.dim(' · always allowing '+m.rule+' (saved to .mlai/settings.local.json)'))}catch(e){print(tr.elbow()+t.ok('Approved')+t.dim(' · allowing '+m.rule+' for this session ('+e.message+')'))}}
|
|
204
|
+
else print(tr.elbow()+t.ok(plan?'Building it':'Approved'));
|
|
205
|
+
}else{
|
|
206
|
+
print(tr.elbow()+t.warn(plan?'Plan sent back':'Rejected')+(feedback?t.dim(' · '+truncate(feedback,screen.cols-20)):''));
|
|
207
|
+
if(feedback)await session.steer(feedback).catch(()=>{});
|
|
208
|
+
}
|
|
209
|
+
nextApproval();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ---------- tasks ----------
|
|
213
|
+
async function attachImage(p){
|
|
214
|
+
const file=droppedImage(p,session?.meta?.root||process.cwd())||path.resolve(session?.meta?.root||process.cwd(),String(p));
|
|
215
|
+
if(!/\.(png|jpe?g|webp|gif)$/i.test(file))throw new Error('Attach a PNG, JPEG, WebP or GIF image.');
|
|
216
|
+
await readFile(file).then(b=>{if(b.length>5_000_000)throw new Error('Images can be up to 5 MB.')});
|
|
217
|
+
if(st.images.length>=4)throw new Error('Attach up to 4 images per message.');
|
|
218
|
+
st.images.push(file);draw();return {path:file,index:st.images.length};
|
|
219
|
+
}
|
|
220
|
+
async function runTask(text){
|
|
221
|
+
if(st.running){await session.steer(text);print(tr.elbow()+t.accent('Sent to the agent: ')+truncate(text,screen.cols-24));return null}
|
|
222
|
+
let task=text;
|
|
223
|
+
if(st.shellContext.length){task='Output of commands I ran in the terminal:\n\n'+st.shellContext.join('\n\n')+'\n\n'+text;st.shellContext=[]}
|
|
224
|
+
const files=st.images.splice(0);
|
|
225
|
+
print(tr.user(text,{images:files.length}));
|
|
226
|
+
let names=[];
|
|
227
|
+
try{for(const f of files)names.push(await session.addImage(await readFile(f)))}catch(e){print(t.bad('Image not attached: '+e.message))}
|
|
228
|
+
st.running=true;st.cancelled=false;st.errorShown=false;st.started=Date.now();st.activity='Starting';st.preview='';startTicker();setTitle();draw();
|
|
229
|
+
let result=null;
|
|
230
|
+
try{
|
|
231
|
+
try{const req=JSON.parse(await readFile(path.join(session.dir,'request.json'),'utf8'));st.window=req.contextWindow||st.window}catch{}
|
|
232
|
+
result=await send(task,{images:names.length?names:undefined});
|
|
233
|
+
}catch(e){print(['',t.bad((box.dot)+' '+(e?.message||String(e)))])}
|
|
234
|
+
finally{
|
|
235
|
+
st.running=false;st.preview='';st.activity='';stopTicker();
|
|
236
|
+
if(st.modal?.type==='approval'||st.modal?.type==='feedback')st.modal=null;st.approvals=[];
|
|
237
|
+
clearEntries();refreshBranch();setTitle();
|
|
238
|
+
}
|
|
239
|
+
if(result&&!result.intake){
|
|
240
|
+
if(result.state!=='completed'&&result.error&&!st.errorShown)print(t.warn(' '+result.error));
|
|
241
|
+
print(['',' '+summaryLine(result,{dim:t.dim,green:t.ok,yellow:t.warn,red:t.bad,bold:t.bold})+t.dim(' · '+elapsed(Date.now()-st.started))]);
|
|
242
|
+
try{const req=JSON.parse(await readFile(path.join(session.dir,'request.json'),'utf8'));if(req.contextWindow){st.window=req.contextWindow;if(st.context)st.context.window=req.contextWindow}}catch{}
|
|
243
|
+
const mode=curMode();
|
|
244
|
+
if(mode==='plan'&&result.state==='completed'&&!st.exiting&&!st.queue.length){
|
|
245
|
+
st.modal={type:'build'};draw();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
afterTurn();
|
|
249
|
+
draw();
|
|
250
|
+
return result;
|
|
251
|
+
}
|
|
252
|
+
/** Queued messages run one by one after a turn; a stopped turn hands them back to the input instead. */
|
|
253
|
+
function afterTurn(){
|
|
254
|
+
if(!st.queue.length||st.exiting)return;
|
|
255
|
+
if(st.cancelled){
|
|
256
|
+
const back=st.queue.splice(0).join('\n');
|
|
257
|
+
editor.set(editor.text?back+'\n'+editor.text:back);
|
|
258
|
+
flash('Queued messages moved back to the input',3000);return;
|
|
259
|
+
}
|
|
260
|
+
const next=st.queue.shift();
|
|
261
|
+
setTimeout(()=>{if(!st.running&&!st.exiting)runTask(next)},0);
|
|
262
|
+
}
|
|
263
|
+
function queueMessage(text){
|
|
264
|
+
st.queue.push(text);editor.clear();st.sel=0;
|
|
265
|
+
flash('Queued; it runs after this turn ('+st.queue.length+' waiting) · '+labelOf(keymap().editQueued)+' to edit it',2500);
|
|
266
|
+
}
|
|
267
|
+
function editQueued(){
|
|
268
|
+
if(!st.queue.length){flash('Nothing queued');return}
|
|
269
|
+
const last=st.queue.pop();editor.set(editor.text?last+'\n'+editor.text:last);draw();
|
|
270
|
+
}
|
|
271
|
+
const waiters=[];
|
|
272
|
+
async function queueTask(text){
|
|
273
|
+
while(st.running)await new Promise(r=>waiters.push(r));
|
|
274
|
+
const r=await runTask(text);
|
|
275
|
+
return {state:r?.state||'error',answer:st.lastAnswer};
|
|
276
|
+
}
|
|
277
|
+
async function runShell(cmd){
|
|
278
|
+
print(tr.user(cmd,{shell:true}));
|
|
279
|
+
const stop=ui.spinner('Running '+truncate(cmd,50));
|
|
280
|
+
// The interface's own shell (PowerShell on Windows, $SHELL elsewhere), the same one background terminals use.
|
|
281
|
+
const r=await exec(cmd,{cwd:session?.meta?.root});
|
|
282
|
+
stop();
|
|
283
|
+
const out=(String(r.stdout||'')+(r.stderr?String(r.stderr):'')).replace(/\r\n/g,'\n').replace(/\s+$/,'');
|
|
284
|
+
const rows=out?out.split('\n'):[];
|
|
285
|
+
const show=rows.slice(-40);
|
|
286
|
+
print([...(rows.length>show.length?[t.dim(' ⋯ '+(rows.length-show.length)+' earlier lines')]:[]),...show.flatMap(l=>wrap(l,screen.cols-6)).map(l=>' '+l),tr.elbow()+(r.code===0?t.dim('exit 0'):t.bad('exit '+r.code))+t.dim(' · added to the next message')]);
|
|
287
|
+
st.shellContext.push('$ '+cmd+'\n```\n'+(out.length>20000?'...'+out.slice(-20000):out)+'\n```\n(exit '+r.code+')');
|
|
288
|
+
if(st.shellContext.length>8)st.shellContext.shift();
|
|
289
|
+
}
|
|
290
|
+
function startBackground(cmd){
|
|
291
|
+
print(tr.user(cmd+' &',{shell:true}));
|
|
292
|
+
try{
|
|
293
|
+
const job=terminals.start(cmd,{cwd:session?.meta?.root||process.cwd(),env:shellEnv});
|
|
294
|
+
print(tr.elbow()+t.accent2('Background #'+job.id)+t.dim(' · running · /ps to check, /stop '+job.id+' to end'));
|
|
295
|
+
}catch(e){print(tr.elbow()+t.bad(e.message))}
|
|
296
|
+
}
|
|
297
|
+
const onJobExit=job=>{
|
|
298
|
+
if(st.exiting)return;
|
|
299
|
+
const lines=terminals.tail(job,1000).length;
|
|
300
|
+
if(job.stopping){print(tr.elbow()+t.dim('Background #'+job.id+' stopped · '+truncate(job.command,40)));return}
|
|
301
|
+
st.shellContext.push(terminals.contextOf(job));if(st.shellContext.length>8)st.shellContext.shift();
|
|
302
|
+
print(['',t.accent2(box.dot)+' '+t.bold('Background #'+job.id)+' '+t.dim(truncate(job.command,Math.max(10,screen.cols-40))),tr.elbow()+(job.code===0?t.dim('exit 0'):t.bad('exit '+(job.code??job.signal)))+t.dim(' · '+lines+' line'+(lines===1?'':'s')+' · added to the next message')]);
|
|
303
|
+
};
|
|
304
|
+
terminals.on('exit',onJobExit);
|
|
305
|
+
async function submit(raw){
|
|
306
|
+
let line=raw;
|
|
307
|
+
editor.remember(raw);saveHistory(historyFile,editor.history);
|
|
308
|
+
editor.clear();st.sel=0;
|
|
309
|
+
if(typeof registry.rewrite==='function'){try{const r=await registry.rewrite(line,ctx);if(typeof r==='string')line=r;else if(r&&typeof r.line==='string')line=r.line}catch{}}
|
|
310
|
+
const trimmed=line.trim();if(!trimmed){draw();return}
|
|
311
|
+
if(trimmed.startsWith('!')&&trimmed.length>1){
|
|
312
|
+
const bg=backgroundCommand(trimmed.slice(1).trim());
|
|
313
|
+
if(bg){startBackground(bg);return}
|
|
314
|
+
if(!st.running){await runShell(trimmed.slice(1).trim());return}
|
|
315
|
+
}
|
|
316
|
+
if(registry.parse(trimmed)){
|
|
317
|
+
draw();
|
|
318
|
+
const {handled,result}=await registry.dispatch(ctx,trimmed);
|
|
319
|
+
if(handled){
|
|
320
|
+
if(result?.exit)return quit(0);
|
|
321
|
+
if(typeof result?.send==='string'&&result.send.trim())await runTask(result.send);
|
|
322
|
+
draw();return;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
await runTask(trimmed);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ---------- rendering ----------
|
|
329
|
+
function boxLines(ed,{label='',placeholder='',glyph=box.arrow,border=t.border,right=''}){
|
|
330
|
+
const cols=screen.cols,inner=Math.max(10,cols-6);
|
|
331
|
+
const {rows,cursor}=layoutInput(ed.text,ed.cursor,inner);
|
|
332
|
+
const maxRows=Math.max(3,Math.min(12,Math.floor(screen.rows/3)));
|
|
333
|
+
let start=0;if(rows.length>maxRows)start=Math.min(Math.max(0,cursor.row-maxRows+1),rows.length-maxRows);
|
|
334
|
+
const shown=rows.slice(start,start+maxRows);
|
|
335
|
+
const top=label?border(box.tl+box.h+' ')+label+' '+border(box.h.repeat(Math.max(0,cols-6-width(label)))+box.tr):border(box.tl+box.h.repeat(cols-3)+box.tr);
|
|
336
|
+
const body=shown.map((r,i)=>{
|
|
337
|
+
const g=i===0&&start===0?glyph+' ':' ';
|
|
338
|
+
const content=!ed.text&&i===0&&placeholder?t.dim(truncate(placeholder,inner)):r;
|
|
339
|
+
return border(box.v)+' '+g+content+' '.repeat(Math.max(0,inner-width(i===0&&!ed.text&&placeholder?truncate(placeholder,inner):r)))+border(box.v);
|
|
340
|
+
});
|
|
341
|
+
const more=rows.length>maxRows?t.dim(' '+(start+1)+'-'+(start+shown.length)+' of '+rows.length+' lines '):'';
|
|
342
|
+
const rlabel=right||more;
|
|
343
|
+
const bottom=border(box.bl+box.h.repeat(Math.max(0,cols-3-width(rlabel)-1)))+rlabel+border(box.h+box.br);
|
|
344
|
+
return {lines:[top,...body,bottom],cursor:{row:1+cursor.row-start,col:2+2+cursor.col}};
|
|
345
|
+
}
|
|
346
|
+
function popupRows(){
|
|
347
|
+
const ed=editor,text=ed.text;
|
|
348
|
+
if(st.modal)return null;
|
|
349
|
+
const m=/^\/([\w-]*)$/.exec(text);
|
|
350
|
+
if(m&&ed.cursor===text.length){
|
|
351
|
+
const rows=registry.suggest(ctx,m[1]);if(!rows.length)return {kind:'slash',rows:[],empty:'No command matches /'+m[1]};
|
|
352
|
+
return {kind:'slash',rows:rows.map(r=>({value:'/'+r.name,label:'/'+r.name+(r.args?' '+t.dim(r.args):''),detail:r.summary}))};
|
|
353
|
+
}
|
|
354
|
+
const p=/^\/([\w-]+)\s+(.*)$/s.exec(text);
|
|
355
|
+
if(p&&ed.cursor===text.length){
|
|
356
|
+
const c=registry.find(p[1]);if(!c)return null;
|
|
357
|
+
const rows=st.completions&&st.completions.line===text?st.completions.rows:null;
|
|
358
|
+
if(!rows){loadCompletions(text);return c.args&&!p[2]?{kind:'hint',text:'/'+c.name+' '+c.args+' '+c.summary}:null}
|
|
359
|
+
if(!rows.length)return c.args&&!p[2]?{kind:'hint',text:'/'+c.name+' '+c.args+' '+c.summary}:null;
|
|
360
|
+
return {kind:'arg',hint:'/'+c.name+(c.args?' '+c.args:'')+' '+(c.summary||''),rows:rows.map(v=>({value:v,label:v.replace(/^\/[\w-]+\s+/,''),detail:''}))};
|
|
361
|
+
}
|
|
362
|
+
const at=atToken(text,ed.cursor);
|
|
363
|
+
if(at){
|
|
364
|
+
const entries=st.entries;if(!entries){loadEntries();return {kind:'at',rows:[],empty:'Listing files...'}}
|
|
365
|
+
const rows=rankPaths(entries,at.query,40);
|
|
366
|
+
return {kind:'at',at,rows:rows.map(e=>({value:e,label:e.endsWith('/')?t.accent(e):e,detail:''})),empty:'No file matches @'+at.query};
|
|
367
|
+
}
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
let loadingCompl='';
|
|
371
|
+
function loadCompletions(line){if(loadingCompl===line)return;loadingCompl=line;registry.complete(ctx,line).then(rows=>{st.completions={line,rows:rows.slice(0,30)};loadingCompl='';draw()}).catch(()=>{st.completions={line,rows:[]};loadingCompl=''})}
|
|
372
|
+
let loadingEntries=false;
|
|
373
|
+
function loadEntries(){if(loadingEntries)return;loadingEntries=true;projectEntries(session?.meta?.root||process.cwd()).then(e=>{st.entries=e;st.entriesAt=Date.now();loadingEntries=false;draw()}).catch(()=>{st.entries=[];loadingEntries=false;draw()})}
|
|
374
|
+
function listRows(rows,sel,max){
|
|
375
|
+
const cols=screen.cols;const n=Math.min(max,rows.length);
|
|
376
|
+
let start=Math.max(0,Math.min(sel-Math.floor(n/2),rows.length-n));
|
|
377
|
+
const nameW=Math.min(Math.max(...rows.slice(start,start+n).map(r=>width(r.label)),8)+2,Math.floor(cols*0.45));
|
|
378
|
+
const out=rows.slice(start,start+n).map((r,i)=>{
|
|
379
|
+
const on=start+i===sel;
|
|
380
|
+
const name=truncate(r.label,nameW-1);
|
|
381
|
+
const line=(on?t.accent(box.arrow+' '):' ')+(on?t.bold(name):name)+' '.repeat(Math.max(1,nameW-width(name)))+t.dim(truncate(r.detail||'',Math.max(0,cols-nameW-6)));
|
|
382
|
+
return line;
|
|
383
|
+
});
|
|
384
|
+
if(rows.length>n)out.push(t.dim(' '+rows.length+' matches · Up/Down to move'));
|
|
385
|
+
return out;
|
|
386
|
+
}
|
|
387
|
+
function footer(){
|
|
388
|
+
const cols=screen.cols;const lines=[];let cursor=null;
|
|
389
|
+
tr.cols=cols;
|
|
390
|
+
if(st.running&&st.preview){const pv=previewLines(st.preview,{t,cols,box,max:Math.max(2,Math.min(10,Math.floor(screen.rows/3)))});if(pv.length)lines.push('',...pv)}
|
|
391
|
+
if(st.running||st.spinning){
|
|
392
|
+
const frames=box.ascii?SPIN_ASCII:SPIN,f=t.accent(frames[st.frame%frames.length]);
|
|
393
|
+
const left=f+' '+t.bold(st.running?'Working':'Working')+t.dim(' · '+elapsed(Date.now()-(st.started||Date.now())))+(st.activity?t.dim(' · '+truncate(st.activity,Math.max(10,cols-40))):'');
|
|
394
|
+
lines.push('',left+t.dim(st.running?' esc to stop':''));
|
|
395
|
+
}else lines.push('');
|
|
396
|
+
const m=st.modal;
|
|
397
|
+
if(m?.type==='approval'){
|
|
398
|
+
lines.push(m.view.choices);
|
|
399
|
+
const b=boxLines(editor,{label:t.dim('Answer y, a or n'),placeholder:'y / a / n',border:t.warn,glyph:t.warn('?')});
|
|
400
|
+
cursor={row:lines.length+b.cursor.row,col:b.cursor.col};lines.push(...b.lines);
|
|
401
|
+
}else if(m?.type==='feedback'){
|
|
402
|
+
const b=boxLines(m.editor,{label:t.warn(m.plan?'What should change in the plan?':'What should the agent do instead?'),placeholder:'Enter to send, Esc to reject without a note',border:t.warn});
|
|
403
|
+
cursor={row:lines.length+b.cursor.row,col:b.cursor.col};lines.push(...b.lines);
|
|
404
|
+
}else if(m?.type==='confirm'){
|
|
405
|
+
lines.push(t.bold(m.question)+' '+t.dim(m.default?'[Y/n]':'[y/N]'));cursor={row:lines.length-1,col:Math.min(cols-2,width(m.question)+8)};
|
|
406
|
+
}else if(m?.type==='build'){
|
|
407
|
+
lines.push(t.accent(box.dot)+' '+t.bold('Plan ready.')+' '+t.bold('[y]')+' Build it (switches to agent mode) '+t.bold('[n]')+' Keep planning');
|
|
408
|
+
const b=boxLines(editor,{placeholder:'y to build, or type feedback on the plan',border:t.borderPlan,glyph:t.borderPlan(box.arrow)});
|
|
409
|
+
cursor={row:lines.length+b.cursor.row,col:b.cursor.col};lines.push(...b.lines);
|
|
410
|
+
}else if(m?.type==='capture'){
|
|
411
|
+
lines.push(t.bold(m.question)+t.dim(' (Esc to cancel)'));
|
|
412
|
+
const b=boxLines({text:'',cursor:0},{label:t.bold('Press the new key'),placeholder:'for example Ctrl-T, Alt-K or F2',border:t.borderFocus,glyph:t.accent('?')});
|
|
413
|
+
cursor={row:lines.length+b.cursor.row,col:b.cursor.col};lines.push(...b.lines);
|
|
414
|
+
}else if(m?.type==='multi'){
|
|
415
|
+
const n=m.rows.length,max=Math.min(n,Math.max(3,screen.rows-8));
|
|
416
|
+
lines.push(t.bold(m.title)+t.dim(' Space toggles · a all · r none · Enter saves · Esc cancels'));
|
|
417
|
+
let start=Math.max(0,Math.min(m.sel-Math.floor(max/2),n-max));
|
|
418
|
+
const nameW=Math.min(Math.max(...m.rows.map(r=>width(r.label)))+2,Math.floor(cols*0.4));
|
|
419
|
+
for(let i=start;i<start+max;i++){
|
|
420
|
+
const r=m.rows[i],on=m.on.has(r.value),cur=i===m.sel;
|
|
421
|
+
const mark=on?t.ok(box.ascii?'[x]':'[✓]'):t.dim('[ ]');
|
|
422
|
+
const name=truncate(r.label,nameW-1);
|
|
423
|
+
lines.push((cur?t.accent(box.arrow+' '):' ')+mark+' '+(cur?t.bold(name):name)+' '.repeat(Math.max(1,nameW-width(name)))+t.dim(truncate(r.detail||'',Math.max(0,cols-nameW-10))));
|
|
424
|
+
}
|
|
425
|
+
if(m.preview){const pv=m.preview([...m.on]);if(pv)lines.push('',t.dim(' Preview'),pv)}
|
|
426
|
+
}else if(m?.type==='pick'||m?.type==='input'){
|
|
427
|
+
const b=boxLines(m.editor,{label:t.bold(m.type==='pick'?m.title:m.question),placeholder:m.type==='pick'?'Type to filter, Enter to choose, Esc to cancel':'',border:t.borderFocus});
|
|
428
|
+
cursor={row:lines.length+b.cursor.row,col:b.cursor.col};lines.push(...b.lines);
|
|
429
|
+
if(m.type==='pick'){const rows=filterPick(m);m.sel=Math.min(m.sel,Math.max(0,rows.length-1));lines.push(...(rows.length?listRows(rows,m.sel,Math.min(10,screen.rows-8)):[t.dim(' Nothing matches')]))}
|
|
430
|
+
}else{
|
|
431
|
+
const text=editor.text,shell=text.startsWith('!');
|
|
432
|
+
const mode=curMode();
|
|
433
|
+
const border=shell?t.borderShell:editor.search?t.accent:mode==='plan'?t.borderPlan:mode==='auto'?t.warn:t.border;
|
|
434
|
+
const label=editor.search?t.accent('search history: ')+editor.search.query+(editor.search.query&&!editor.search.match?t.bad(' no match'):''):shell?t.borderShell('shell'):'';
|
|
435
|
+
if(st.queue.length){
|
|
436
|
+
const q=st.queue.slice(-3);
|
|
437
|
+
if(st.queue.length>3)lines.push(t.dim(' ⋯ '+(st.queue.length-3)+' more queued'));
|
|
438
|
+
for(const x of q)lines.push(t.dim(' '+(box.ascii?'>':'↳')+' queued: ')+truncate(x.replace(/\n/g,' '),cols-14));
|
|
439
|
+
}
|
|
440
|
+
const right=tr.raw&&!editor.vim&&!st.images.length?t.dim(' raw '):editor.vim?t.dim(' '+(editor.vimMode==='normal'?'NORMAL':'INSERT')+' '):st.images.length?t.accent(' '+st.images.length+' image'+(st.images.length===1?'':'s')+' attached '):st.shellContext.length?t.dim(' shell output queued '):'';
|
|
441
|
+
const glyph=shell?t.borderShell('!'):st.running?t.dim(box.arrow):t.accent(box.arrow);
|
|
442
|
+
const view=editor.search?{text:editor.search.match??editor.search.saved,cursor:(editor.search.match??'').length}:editor;
|
|
443
|
+
const b=boxLines(view,{label,placeholder:st.running?'Enter steers the agent · '+labelOf(keymap().queueMessage)+' queues for after this turn · Esc stops':PLACEHOLDER,border,glyph,right});
|
|
444
|
+
cursor={row:lines.length+b.cursor.row,col:b.cursor.col};lines.push(...b.lines);
|
|
445
|
+
const pop=popupRows();
|
|
446
|
+
if(pop?.kind==='hint')lines.push(t.dim(' '+truncate(pop.text,cols-4)));
|
|
447
|
+
else if(pop){
|
|
448
|
+
const key=pop.kind+':'+(pop.rows.length);if(st.popupKey!==key){st.popupKey=key}
|
|
449
|
+
st.sel=Math.min(st.sel,Math.max(0,pop.rows.length-1));
|
|
450
|
+
if(pop.hint)lines.push(t.dim(' '+truncate(pop.hint,cols-4)));
|
|
451
|
+
if(pop.rows.length)lines.push(...listRows(pop.rows,st.sel,Math.min(8,Math.max(3,screen.rows-lines.length-3))));
|
|
452
|
+
else lines.push(t.dim(' '+pop.empty));
|
|
453
|
+
st.popup=pop;
|
|
454
|
+
}else st.popup=null;
|
|
455
|
+
if(!pop){
|
|
456
|
+
const hint=Date.now()<st.hintUntil?st.hint:'';
|
|
457
|
+
const d=ui.status();
|
|
458
|
+
const custom=liveSettings().statusLine&&typeof liveSettings().statusLine==='object'&&liveSettings().statusLine.command?st.custom:null;
|
|
459
|
+
if(liveSettings().statusLine===false||liveSettings().statusLine?.enabled===false)lines.push(hint?t.dim(' '+hint):'');
|
|
460
|
+
else lines.push(custom&&!hint?' '+truncate(custom,cols-2):statusLine(d,{t,cols,box,hint}));
|
|
461
|
+
if(custom!==undefined)refreshCustom(d);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
return {lines,cursor};
|
|
465
|
+
}
|
|
466
|
+
function filterPick(m){
|
|
467
|
+
const q=m.editor.text.trim();
|
|
468
|
+
if(!q)return m.rows.map(r=>({...r,label:r.label,detail:r.detail||''}));
|
|
469
|
+
return m.rows.map(r=>({r,s:registry.fuzzy(q,r.label+' '+(r.detail||''))})).filter(x=>x.s!=null).sort((a,b)=>b.s-a.s).map(x=>x.r);
|
|
470
|
+
}
|
|
471
|
+
function refreshCustom(d){
|
|
472
|
+
const cmd=liveSettings().statusLine?.command;if(!cmd||Date.now()-st.customAt<3000)return;st.customAt=Date.now();
|
|
473
|
+
customStatus(cmd,d,{cwd:session?.meta?.root}).then(v=>{if(v!==st.custom){st.custom=v;draw()}});
|
|
474
|
+
}
|
|
475
|
+
let drawing=false,pendingDraw=false;
|
|
476
|
+
function draw(){
|
|
477
|
+
if(st.exiting)return;
|
|
478
|
+
if(drawing){pendingDraw=true;return}
|
|
479
|
+
drawing=true;try{screen.draw(footer())}finally{drawing=false}
|
|
480
|
+
if(pendingDraw){pendingDraw=false;draw()}
|
|
481
|
+
}
|
|
482
|
+
let ticker=null;
|
|
483
|
+
function startTicker(){
|
|
484
|
+
if(ticker)return;
|
|
485
|
+
ticker=setInterval(async()=>{
|
|
486
|
+
st.frame++;
|
|
487
|
+
if(st.running&&session?.dir){
|
|
488
|
+
try{const p=JSON.parse(await readFile(path.join(session.dir,'inference-progress.json'),'utf8'));const next=p.state==='running'&&p.content?String(p.content):'';if(next!==st.preview)st.preview=next}catch{}
|
|
489
|
+
}
|
|
490
|
+
draw();
|
|
491
|
+
},120);
|
|
492
|
+
ticker.unref?.();
|
|
493
|
+
}
|
|
494
|
+
function stopTicker(){if(ticker&&!st.spinning){clearInterval(ticker);ticker=null}while(waiters.length)waiters.shift()()}
|
|
495
|
+
async function refreshBranch(){st.branch=session?.meta?.git===false?null:await gitBranch(session?.meta?.root||process.cwd());draw()}
|
|
496
|
+
function toggleTools(){
|
|
497
|
+
tr.expanded=!tr.expanded;
|
|
498
|
+
const more=tr.expanded?tr.expandLast():[];
|
|
499
|
+
print([...more,t.dim(' Tool output '+(tr.expanded?'expanded':'collapsed')+' (Ctrl-O)')]);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// ---------- keys ----------
|
|
503
|
+
async function quit(code=0){
|
|
504
|
+
if(st.exiting)return;st.exiting=true;
|
|
505
|
+
if(st.running)await session.cancel().catch(()=>{});
|
|
506
|
+
const n=terminals.running().length;if(n){st.exiting=false;print(t.dim(' Stopping '+n+' background terminal'+(n===1?'':'s')+'...'));st.exiting=true;await terminals.stopAll()}
|
|
507
|
+
exitResolve(code);
|
|
508
|
+
}
|
|
509
|
+
function onKey(k){
|
|
510
|
+
Promise.resolve(handleKey(k)).catch(e=>print(t.bad('error: '+(e?.message||e))));
|
|
511
|
+
}
|
|
512
|
+
async function handleKey(k){
|
|
513
|
+
const m=st.modal;
|
|
514
|
+
// Ctrl-C: stop the agent, close a popup, clear the line, or (twice) exit.
|
|
515
|
+
if(k.ctrl&&k.name==='c'){
|
|
516
|
+
if(st.shellChild){try{st.shellChild.kill('SIGINT')}catch{}return}
|
|
517
|
+
if(m){closeModal();return}
|
|
518
|
+
if(st.running){st.cancelled=true;print(t.warn(' Stopping...'));session.cancel().catch(()=>{});return}
|
|
519
|
+
if(editor.text){editor.clear();draw();return}
|
|
520
|
+
if(Date.now()-st.lastCtrlC<1500)return quit(0);
|
|
521
|
+
st.lastCtrlC=Date.now();flash('Press Ctrl-C again to exit',1500);return;
|
|
522
|
+
}
|
|
523
|
+
if(m?.type==='confirm'){
|
|
524
|
+
if(k.name==='char'&&/^[yn]$/i.test(k.ch)){st.modal=null;m.resolve(/y/i.test(k.ch));draw()}
|
|
525
|
+
else if(k.name==='enter'){st.modal=null;m.resolve(m.default);draw()}
|
|
526
|
+
else if(k.name==='escape'){st.modal=null;m.resolve(false);draw()}
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if(m?.type==='capture'){
|
|
530
|
+
if(k.name==='escape'){st.modal=null;m.resolve(null);draw();return}
|
|
531
|
+
if(k.name==='paste')return;
|
|
532
|
+
st.modal=null;m.resolve(specOf(k));draw();return;
|
|
533
|
+
}
|
|
534
|
+
if(m?.type==='multi'){
|
|
535
|
+
const n=m.rows.length;
|
|
536
|
+
if(k.name==='escape'){st.modal=null;m.resolve(null);draw();return}
|
|
537
|
+
if(k.name==='up'||(k.ctrl&&k.name==='p')){m.sel=(m.sel-1+n)%n;draw();return}
|
|
538
|
+
if(k.name==='down'||(k.ctrl&&k.name==='n')||k.name==='tab'){m.sel=(m.sel+1)%n;draw();return}
|
|
539
|
+
if(k.name==='char'&&k.ch===' '){const v=m.rows[m.sel].value;m.on.has(v)?m.on.delete(v):m.on.add(v);draw();return}
|
|
540
|
+
if(k.name==='char'&&/^[ar]$/i.test(k.ch)){if(/a/i.test(k.ch))m.rows.forEach(r=>m.on.add(r.value));else m.on.clear();draw();return}
|
|
541
|
+
if(k.name==='enter'){st.modal=null;m.resolve(m.rows.map(r=>r.value).filter(v=>m.on.has(v)));draw();return}
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
if(m?.type==='pick'||m?.type==='input'){
|
|
545
|
+
if(k.name==='escape'){st.modal=null;m.resolve(null);draw();return}
|
|
546
|
+
if(m.type==='pick'){
|
|
547
|
+
const rows=filterPick(m);
|
|
548
|
+
if(k.name==='up'||(k.ctrl&&k.name==='p')){m.sel=(m.sel-1+rows.length)%Math.max(1,rows.length);draw();return}
|
|
549
|
+
if(k.name==='down'||(k.ctrl&&k.name==='n')||k.name==='tab'){m.sel=(m.sel+1)%Math.max(1,rows.length);draw();return}
|
|
550
|
+
if(k.name==='enter'){st.modal=null;m.resolve(rows[m.sel]||null);draw();return}
|
|
551
|
+
}else if(k.name==='enter'&&!k.shift&&!k.alt){st.modal=null;m.resolve(m.editor.text);draw();return}
|
|
552
|
+
const r=m.editor.handle(k);if(r==='changed'&&m.type==='pick')m.sel=0;draw();return;
|
|
553
|
+
}
|
|
554
|
+
if(m?.type==='approval'){
|
|
555
|
+
if(k.name==='char'){
|
|
556
|
+
const c=k.ch.toLowerCase();
|
|
557
|
+
if(c==='y')return decide('approve');
|
|
558
|
+
if(c==='a'){if(m.rule)return decide('approve',{always:true});flash('No narrow rule for this one; answer y or n');return}
|
|
559
|
+
if(c==='n'){st.modal={type:'feedback',a:m.a,rule:m.rule,plan:parseApproval(m.a).kind==='plan',editor:new Editor()};draw();return}
|
|
560
|
+
}
|
|
561
|
+
if(k.name==='escape')return decide('reject');
|
|
562
|
+
if(k.ctrl&&k.name==='o'){toggleTools();const v=approvalLines(m.a,{t,cols:screen.cols,box,expanded:tr.expanded,rule:m.rule});if(tr.expanded)print(['',...v.lines]);return}
|
|
563
|
+
flash('Answer y, a or n');return;
|
|
564
|
+
}
|
|
565
|
+
if(m?.type==='feedback'){
|
|
566
|
+
if(k.name==='escape')return decide('reject');
|
|
567
|
+
if(k.name==='enter'&&!k.shift&&!k.alt){const fb=m.editor.text.trim();st.modal={...m,type:'feedback'};return decide('reject',{feedback:fb||null})}
|
|
568
|
+
m.editor.handle(k);draw();return;
|
|
569
|
+
}
|
|
570
|
+
if(m?.type==='build'){
|
|
571
|
+
if(!editor.text&&k.name==='char'&&/^[yn]$/i.test(k.ch)){
|
|
572
|
+
st.modal=null;
|
|
573
|
+
if(/y/i.test(k.ch)){await setModeAll('agent').catch(()=>{});print(tr.elbow()+t.dim('Mode: agent'));await runTask('Build the plan you proposed above.')}
|
|
574
|
+
else draw();
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
if(k.name==='escape'){st.modal=null;draw();return}
|
|
578
|
+
if(k.name==='enter'&&editor.text.trim()){st.modal=null;const txt=editor.text;editor.clear();editor.remember(txt);await runTask(txt);return}
|
|
579
|
+
editor.handle(k);draw();return;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Global keys: remappable actions first (/keymap), then the fixed ones.
|
|
583
|
+
const action=editor.search?null:actionFor(k,keymap());
|
|
584
|
+
if(action==='cycleMode'){
|
|
585
|
+
const cur=curMode();
|
|
586
|
+
const next=nextMode(cur,{sandbox});
|
|
587
|
+
try{await setModeAll(next);flash(MODES[next].summary,2500)}catch(e){flash(e.message)}
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if(action==='toggleTools'){toggleTools();return}
|
|
591
|
+
if(action==='redraw'){screen.reset();draw();return}
|
|
592
|
+
if(action==='historySearch'){editor.startSearch();draw();return}
|
|
593
|
+
if(action==='toggleRaw'){tr.raw=!tr.raw;flash('Raw scrollback '+(tr.raw?'on: replies print as plain text':'off'));return}
|
|
594
|
+
if(action==='showJobs'){print(jobsLines());return}
|
|
595
|
+
if(action==='editQueued'&&st.queue.length){editQueued();return}
|
|
596
|
+
if(action==='pasteImage'){await pasteImage();return}
|
|
597
|
+
if(action==='queueMessage'&&st.running&&editor.text.trim()&&!(st.popup?.rows?.length)){queueMessage(editor.text.trim());return}
|
|
598
|
+
if(k.ctrl&&k.name==='d'&&!editor.text){return quit(0)}
|
|
599
|
+
if(k.ctrl&&k.name==='z'&&process.platform!=='win32'){suspend();return}
|
|
600
|
+
if(k.name==='escape'&&!editor.search&&!(editor.vim&&editor.vimMode==='insert'&&editor.text)){
|
|
601
|
+
if(st.popup){editor.text.startsWith('/')&&!editor.text.includes(' ')?editor.clear():null;st.popup=null;st.sel=0;draw();if(!editor.text)return}
|
|
602
|
+
if(st.running){st.cancelled=true;print(t.warn(' Stopping...'));session.cancel().catch(()=>{});return}
|
|
603
|
+
const now=Date.now(),dbl=now-st.lastEsc<600;st.lastEsc=now;
|
|
604
|
+
if(dbl){st.lastEsc=0;if(editor.text){editor.clear();draw();return}
|
|
605
|
+
if(registry.find('rewind')){const {result}=await registry.dispatch(ctx,'/rewind');if(typeof result?.send==='string')await runTask(result.send);draw()}else flash('Rewind is not available');return}
|
|
606
|
+
if(!editor.vim){if(editor.text)flash('Esc again clears the input',1200);else flash('Esc again to rewind to an earlier message',1500)}
|
|
607
|
+
if(!editor.vim)return;
|
|
608
|
+
}
|
|
609
|
+
// Popups: move, complete, accept.
|
|
610
|
+
const pop=st.popup;
|
|
611
|
+
if(pop&&pop.rows?.length&&!editor.search){
|
|
612
|
+
if(k.name==='up'||(k.ctrl&&k.name==='p')){st.sel=(st.sel-1+pop.rows.length)%pop.rows.length;st.navigated=true;draw();return}
|
|
613
|
+
if(k.name==='down'||(k.ctrl&&k.name==='n')){st.sel=(st.sel+1)%pop.rows.length;st.navigated=true;draw();return}
|
|
614
|
+
// In an argument popup Enter sends what was typed unless a row was chosen with the arrows; Tab completes.
|
|
615
|
+
if(pop.kind==='arg'&&k.name==='enter'&&!k.shift&&!k.alt&&!st.navigated){
|
|
616
|
+
const typed=editor.text.trim(),row=pop.rows[st.sel]?.value?.trim()||'';
|
|
617
|
+
if(pop.rows.some(r=>r.value.trim()===typed)||!row.startsWith(typed)){st.sel=0;return submit(editor.text)}
|
|
618
|
+
}
|
|
619
|
+
if(k.name==='tab'||(k.name==='enter'&&!k.shift&&!k.alt&&pop.kind!=='slash')||(k.name==='enter'&&pop.kind==='slash'&&!k.shift)){
|
|
620
|
+
const row=pop.rows[st.sel];
|
|
621
|
+
if(pop.kind==='slash'){
|
|
622
|
+
const c=registry.find(row.value.slice(1));
|
|
623
|
+
if(k.name==='enter'&&(!c?.args||/^\[/.test(c.args))){editor.set(row.value);st.sel=0;return submit(row.value)}
|
|
624
|
+
editor.set(row.value+' ');st.sel=0;st.completions=null;draw();return;
|
|
625
|
+
}
|
|
626
|
+
if(pop.kind==='arg'){editor.set(row.value);st.sel=0;if(k.name==='enter')return submit(row.value);draw();return}
|
|
627
|
+
if(pop.kind==='at'){
|
|
628
|
+
const ins=row.value.includes(' ')?'"'+row.value+'"':row.value;
|
|
629
|
+
editor.text=editor.text.slice(0,pop.at.start)+'@'+ins+(row.value.endsWith('/')?'':' ')+editor.text.slice(editor.cursor);
|
|
630
|
+
editor.cursor=pop.at.start+1+ins.length+(row.value.endsWith('/')?0:1);st.sel=0;draw();return;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
if(k.name==='tab'&&!pop){
|
|
635
|
+
if(editor.text.startsWith('/')){const c=await registry.complete(ctx,editor.text);if(c.length===1)editor.set(c[0]);else if(c.length>1)flash(c.slice(0,6).map(x=>x.trim()).join(' '));draw()}
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
if(k.name==='paste'){
|
|
639
|
+
const img=droppedImage(k.text,session?.meta?.root||process.cwd());
|
|
640
|
+
if(img){try{const r=await attachImage(img);editor.insert('[Image #'+r.index+'] ');flash('Attached '+path.basename(img))}catch(e){flash(e.message)}draw();return}
|
|
641
|
+
}
|
|
642
|
+
const r=editor.handle(k);
|
|
643
|
+
if(r==='submit'){
|
|
644
|
+
if(!editor.text.trim()){draw();return}
|
|
645
|
+
return submit(editor.text);
|
|
646
|
+
}
|
|
647
|
+
if(r==='changed'){st.sel=st.sel&&editor.text?st.sel:0;st.navigated=false;draw()}
|
|
648
|
+
}
|
|
649
|
+
async function pasteImage(){
|
|
650
|
+
const stop=ui.spinner('Reading the clipboard');
|
|
651
|
+
let r;try{r=await readClipboardImage()}finally{stop()}
|
|
652
|
+
if(r?.error){flash(r.error,4000);return}
|
|
653
|
+
try{const a=await attachImage(r.path);editor.insert('[Image #'+a.index+'] ');flash('Pasted image attached')}catch(e){flash(e.message)}
|
|
654
|
+
draw();
|
|
655
|
+
}
|
|
656
|
+
function jobsLines(){
|
|
657
|
+
const rows=terminals.rows();
|
|
658
|
+
if(!rows.length)return [t.dim(' No background terminals. Start one with !<command> & or /bg <command>.')];
|
|
659
|
+
return ['',t.bold(' Background terminals'),...rows.map(r=>' '+t.accent2('#'+r.id)+' '+(r.running?t.ok(r.status):t.dim(r.status))+' '+truncate(r.command,Math.max(10,screen.cols-36))+(r.last?t.dim(' '+truncate(r.last,Math.max(0,screen.cols-60))):''))];
|
|
660
|
+
}
|
|
661
|
+
function closeModal(){
|
|
662
|
+
const m=st.modal;st.modal=null;
|
|
663
|
+
if(m?.type==='approval'||m?.type==='feedback'){st.modal=m;decide('reject');return}
|
|
664
|
+
m?.resolve?.(m.type==='confirm'?false:null);draw();
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// ---------- terminal setup ----------
|
|
668
|
+
const keys=keyReader(onKey);
|
|
669
|
+
const onData=d=>keys.feed(d);
|
|
670
|
+
const onResize=()=>{tr.cols=screen.cols;draw()};
|
|
671
|
+
const setup=()=>{
|
|
672
|
+
stdin.setRawMode?.(true);stdin.setEncoding?.('utf8');stdin.resume();
|
|
673
|
+
// Bracketed paste; kitty keyboard "disambiguate" so Shift+Enter is its own key where supported; push the title.
|
|
674
|
+
stdout.write('\x1b[?2004h\x1b[>1u\x1b[22;0t');
|
|
675
|
+
};
|
|
676
|
+
const teardown=()=>{
|
|
677
|
+
stdout.write('\x1b[<u\x1b[?2004l\x1b[23;0t\x1b[?25h');
|
|
678
|
+
stdin.setRawMode?.(false);
|
|
679
|
+
};
|
|
680
|
+
function suspend(){
|
|
681
|
+
screen.clear();teardown();stdin.pause();
|
|
682
|
+
process.once('SIGCONT',()=>{setup();draw()});
|
|
683
|
+
process.kill(process.pid,'SIGTSTP');
|
|
684
|
+
}
|
|
685
|
+
const onSignal=()=>quit(130);
|
|
686
|
+
stdin.on('data',onData);stdout.on('resize',onResize);
|
|
687
|
+
process.on('SIGTERM',onSignal);process.on('SIGHUP',onSignal);
|
|
688
|
+
setup();
|
|
689
|
+
subscribe(session);syncCtx();
|
|
690
|
+
|
|
691
|
+
// Header, then the first draw.
|
|
692
|
+
const mode=curMode();
|
|
693
|
+
stdout.write('\r\n');
|
|
694
|
+
print([
|
|
695
|
+
t.accent(box.dot)+' '+t.bold('ML AI Code')+t.dim(' · '+(session?.meta?.folder||'')+' · ')+modeStyle(t,mode)(MODES[mode]?.label||mode)+t.dim(' mode · sandbox '+(sandbox?sandboxKind():'none')),
|
|
696
|
+
...wrap('/help for commands · @ to add files · ! for a shell command · Shift+Tab switches mode · Esc stops',screen.cols-3).map(l=>t.dim(' '+l)),
|
|
697
|
+
].flatMap(l=>width(l)>screen.cols-1?wrap(l,screen.cols-1):[l]));
|
|
698
|
+
setTitle();refreshBranch();loadEntries();
|
|
699
|
+
for(const f of flagImages){try{await attachImage(f)}catch(e){print(t.warn(' '+f+': '+e.message))}}
|
|
700
|
+
if(first)runTask(first);
|
|
701
|
+
const code=await exited;
|
|
702
|
+
|
|
703
|
+
// Cleanup.
|
|
704
|
+
st.exiting=true;stopTicker();if(ticker)clearInterval(ticker);keys.close();unsub();terminals.off('exit',onJobExit);
|
|
705
|
+
stdin.off('data',onData);stdout.off('resize',onResize);process.off('SIGTERM',onSignal);process.off('SIGHUP',onSignal);
|
|
706
|
+
screen.clear();teardown();stdin.pause();
|
|
707
|
+
await saveHistory(historyFile,editor.history);
|
|
708
|
+
title('');
|
|
709
|
+
return code;
|
|
710
|
+
}
|