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
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Approvals in the TUI: what the agent wants to do (an edit as a colored diff, a new file, a command, a plan),
|
|
3
|
+
* the permission rule that "always" would save, and a matcher for rules approved in this session.
|
|
4
|
+
*
|
|
5
|
+
* Rule syntax is the engine's (permissions owner, tui/permissions.mjs): Bash(<cmd>), Bash(<prefix>:*), Edit(<glob>),
|
|
6
|
+
* Read(<glob>), WebFetch(domain:<host>), mcp__<server>[__<tool>], Connector(<name>). When that module is present its
|
|
7
|
+
* suggestRule() wins; ruleFor() here is the fallback with the same output.
|
|
8
|
+
*/
|
|
9
|
+
import {renderDiff} from './diff.mjs';
|
|
10
|
+
import {render as markdown} from './markdown.mjs';
|
|
11
|
+
import {wrap,truncate} from './ansi.mjs';
|
|
12
|
+
|
|
13
|
+
/** Parses an approval into {kind:'edit'|'write'|'command'|'plan'|'other', path?, old?, new?, content?, command?, items?}. */
|
|
14
|
+
export function parseApproval(a){
|
|
15
|
+
const text=String(a?.command||'');let m;
|
|
16
|
+
if(a?.kind==='plan')return {kind:'plan',items:Array.isArray(a.items)?a.items.map(String):text.split('\n').slice(1).map(l=>l.replace(/^- /,'')).filter(Boolean),brief:Boolean(a.brief),questions:a.questions||[]};
|
|
17
|
+
if((m=/^Edit (.+?)\nREMOVE:\n([\s\S]*?)\nREPLACE WITH:\n([\s\S]*)$/.exec(text)))return {kind:'edit',path:m[1].trim(),old:m[2],new:m[3]};
|
|
18
|
+
if((m=/^Write (.+?)(?: \((\d+) characters\))?\n([\s\S]*)$/.exec(text)))return {kind:'write',path:m[1].trim(),content:m[3],size:m[2]?Number(m[2]):m[3].length};
|
|
19
|
+
if((m=/^Edit (\S.*)$/.exec(text)))return {kind:'edit',path:m[1].trim(),old:'',new:''};
|
|
20
|
+
if(a?.kind==='image'||a?.kind==='computer'||a?.kind==='connector'||a?.kind==='mcp')return {kind:'other',sub:a.kind,command:text,name:a.name||a.tool||null};
|
|
21
|
+
return {kind:'command',command:text.replace(/^Run(?: command)?:?\s*/,'')};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const RUNNERS=new Set(['npm','pnpm','yarn','npx','bun','bunx','git','cargo','go','pip','uv','poetry','make','docker','kubectl','gh','dotnet','mvn','gradle','./gradlew']);
|
|
25
|
+
const TWO_WORD=new Set(['npm','pnpm','yarn','npx','bun','bunx','git','cargo','go','gh','docker','kubectl','dotnet','uv','poetry']);
|
|
26
|
+
/** The rule [a]lways saves for this approval, or null when there is no safe narrow rule (compound commands, sudo). */
|
|
27
|
+
export function ruleFor(a){
|
|
28
|
+
const p=parseApproval(a);
|
|
29
|
+
if(p.kind==='edit'||p.kind==='write'){
|
|
30
|
+
const rel=String(p.path||'').replace(/^\.\//,'').replace(/\\/g,'/');if(!rel||rel.startsWith('/')||rel.includes('..'))return null;
|
|
31
|
+
const dir=rel.includes('/')?rel.slice(0,rel.lastIndexOf('/')):'';
|
|
32
|
+
return dir?'Edit('+dir+'/**)':'Edit('+rel+')';
|
|
33
|
+
}
|
|
34
|
+
if(p.kind==='command'){
|
|
35
|
+
const cmd=String(p.command||'').trim().split('\n')[0];
|
|
36
|
+
if(!cmd||/[;&|`$<>]|\$\(/.test(cmd))return null;
|
|
37
|
+
const words=cmd.split(/\s+/).filter(w=>!/^[A-Z_][A-Z0-9_]*=/.test(w));
|
|
38
|
+
if(!words.length||['sudo','rm','su','chmod','chown','curl','wget','dd','mkfs'].includes(words[0]))return null;
|
|
39
|
+
if(words[0]==='python'||words[0]==='python3'){if(words[1]==='-m'&&words[2])return 'Bash('+words.slice(0,3).join(' ')+':*)';return null}
|
|
40
|
+
if(TWO_WORD.has(words[0])&&words[1]&&!words[1].startsWith('-')){
|
|
41
|
+
// npm run build -> "npm run build"; npm test -> "npm test"
|
|
42
|
+
const n=(words[1]==='run'||words[1]==='exec'||words[1]==='x')&&words[2]?3:2;
|
|
43
|
+
return 'Bash('+words.slice(0,n).join(' ')+':*)';
|
|
44
|
+
}
|
|
45
|
+
return RUNNERS.has(words[0])||/^[\w./-]+$/.test(words[0])?'Bash('+words[0]+':*)':null;
|
|
46
|
+
}
|
|
47
|
+
if(p.kind==='other'&&p.sub==='mcp'&&p.name)return 'mcp__'+p.name;
|
|
48
|
+
if(p.kind==='other'&&p.sub==='connector'&&p.name)return 'Connector('+p.name+')';
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
/** Minimal matcher for rules approved in this session (the engine enforces saved rules on later runs). */
|
|
52
|
+
export function ruleMatches(rule,a){
|
|
53
|
+
const p=parseApproval(a);let m;
|
|
54
|
+
if((m=/^Bash\((.*)\)$/.exec(rule))&&p.kind==='command'){
|
|
55
|
+
const cmd=p.command.trim(),r=m[1];
|
|
56
|
+
if(/[;&|`]/.test(cmd))return false;
|
|
57
|
+
if(r.endsWith(':*')){const pre=r.slice(0,-2);return cmd===pre||cmd.startsWith(pre+' ')}
|
|
58
|
+
return cmd===r;
|
|
59
|
+
}
|
|
60
|
+
if((m=/^(?:Edit|Write)\((.*)\)$/.exec(rule))&&(p.kind==='edit'||p.kind==='write')){
|
|
61
|
+
const rel=String(p.path).replace(/^\.\//,'').replace(/\\/g,'/'),g=m[1];
|
|
62
|
+
if(g.endsWith('/**'))return rel.startsWith(g.slice(0,-2));
|
|
63
|
+
return rel===g;
|
|
64
|
+
}
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Lines for the approval card, and the choices line. Edits show a unified diff; writes show the new file's first
|
|
70
|
+
* lines; commands show the command; plans show the numbered steps.
|
|
71
|
+
*/
|
|
72
|
+
export function approvalLines(a,{t,cols=80,box,expanded=false,rule=null}={}){
|
|
73
|
+
const p=parseApproval(a);const lines=[];const max=expanded?400:40;
|
|
74
|
+
const head=s=>lines.push(t.warn(box?.dot||'●')+' '+t.bold(s));
|
|
75
|
+
if(p.kind==='edit'){head('Edit '+p.path);lines.push(...renderDiff(p.old,p.new,{t,cols:cols-2,maxLines:max}).map(l=>' '+l))}
|
|
76
|
+
else if(p.kind==='write'){
|
|
77
|
+
head('Create or overwrite '+p.path+t.dim(' ('+p.size+' characters)'));
|
|
78
|
+
const body=p.content.split('\n');for(const l of body.slice(0,max))lines.push(' '+t.add('+ ')+t.add(truncate(l.replace(/\t/g,' '),cols-6)));
|
|
79
|
+
if(body.length>max)lines.push(' '+t.dim('⋯ '+(body.length-max)+' more lines (Ctrl-O shows all)'));
|
|
80
|
+
}
|
|
81
|
+
else if(p.kind==='command'){head('Run a command');for(const w of wrap(p.command,cols-6))lines.push(' '+t.accent('$ ')+w)}
|
|
82
|
+
else if(p.kind==='plan'){head(p.brief?'Review the brief':'Review the plan');p.items.forEach((it,i)=>{const w=wrap(it,cols-8);w.forEach((x,j)=>lines.push((j?' ':' '+t.accent(String(i+1).padStart(2)+'. '))+x))})}
|
|
83
|
+
else{head(p.sub==='image'?'Generate an image':p.sub==='computer'?'Use this computer':'Allow this action');for(const l of markdown(p.command,{t,cols:cols-2,box}).slice(0,max))lines.push(' '+l)}
|
|
84
|
+
const choices=p.kind==='plan'
|
|
85
|
+
?t.bold('[y]')+' Build it '+t.bold('[n]')+' No, and tell the agent what to change '+t.dim('Esc rejects')
|
|
86
|
+
:t.bold('[y]')+'es '+(rule?t.bold('[a]')+'lways allow '+t.accent(rule)+' ':'')+t.bold('[n]')+'o, and tell the agent what to do instead';
|
|
87
|
+
return {kind:p.kind,parsed:p,lines,choices};
|
|
88
|
+
}
|
package/src/tui/bg.mjs
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Background agents: `mlai --bg "task"` runs a session in a detached process; `mlai agents` lists, follows and stops
|
|
2
|
+
// them; `mlai attach <id>` follows one live, answers its approvals and steers it. Everything goes through the
|
|
3
|
+
// session's files in ~/.mlai/sessions/<id> (events.jsonl, pending.json, decision-*, steering/, cancel), so attaching
|
|
4
|
+
// also works for a session running in another terminal. A finished background session is an ordinary session:
|
|
5
|
+
// continue it with mlai -c or mlai -r <id>.
|
|
6
|
+
import {spawn} from 'node:child_process';
|
|
7
|
+
import {openSync,closeSync,existsSync} from 'node:fs';
|
|
8
|
+
import {readFile,writeFile,rename,stat,open} from 'node:fs/promises';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import {fileURLToPath} from 'node:url';
|
|
11
|
+
|
|
12
|
+
export const FINAL=new Set(['completed','failed','error','stopped','interrupted','limited','lost']);
|
|
13
|
+
const here=path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
async function readJson(file,fallback){try{return JSON.parse(await readFile(file,'utf8'))}catch{return fallback}}
|
|
15
|
+
async function writeJson(file,data){const tmp=file+'.'+process.pid+'.tmp';await writeFile(tmp,JSON.stringify(data));await rename(tmp,file)}
|
|
16
|
+
export const alive=pid=>{if(!(pid>0))return false;try{process.kill(pid,0);return true}catch(e){return e.code==='EPERM'}};
|
|
17
|
+
const clip=(s,n)=>{const t=String(s||'').replace(/\s+/g,' ').trim();return t.length>n?t.slice(0,n-1)+'\u2026':t};
|
|
18
|
+
const ago=t=>{const s=Math.max(0,(Date.now()-Date.parse(t))/1000);return !Number.isFinite(s)?'':s<90?Math.round(s)+'s':s<5400?Math.round(s/60)+'m':s<129600?Math.round(s/3600)+'h':Math.round(s/86400)+'d'};
|
|
19
|
+
|
|
20
|
+
/** The mlai entry point to re-run for a background child. */
|
|
21
|
+
export function mlaiBin(){
|
|
22
|
+
const a=process.argv[1]||'';
|
|
23
|
+
if(/mlai(\.m?js|\.cjs)?$/.test(a)&&existsSync(a))return a;
|
|
24
|
+
return path.join(here,'..','..','bin','mlai.mjs');
|
|
25
|
+
}
|
|
26
|
+
/** Flags for the detached child: the same session (-r), the task, stream-json to the log, and the run's options. */
|
|
27
|
+
export function childArgs(o,id,task){
|
|
28
|
+
const a=['--resume='+id,'--print='+task,'--output-format=stream-json','--bg-child'];
|
|
29
|
+
if(o.mode)a.push('--mode='+o.mode);if(o.model)a.push('--model='+o.model);if(o.effort)a.push('--effort='+o.effort);
|
|
30
|
+
if(o.maxStepsSet)a.push('--max-steps='+o.steps);for(const d of o.addDirs||[])a.push('--add-dir='+d);
|
|
31
|
+
if(o.fallbackModel)a.push('--fallback-model='+[].concat(o.fallbackModel).join(','));for(const r of o.allowedTools||[])a.push('--allowedTools='+r);for(const r of o.disallowedTools||[])a.push('--disallowedTools='+r);
|
|
32
|
+
if(o.tools!=null)a.push('--tools='+o.tools);if(o.appendSystemPrompt)a.push('--append-system-prompt='+o.appendSystemPrompt);
|
|
33
|
+
if(o.yes)a.push('--yes');if(o.sandbox===false)a.push('--no-sandbox');if(o.server)a.push('--server='+o.server);if(o.verbose)a.push('--verbose');
|
|
34
|
+
return a;
|
|
35
|
+
}
|
|
36
|
+
/** Starts `task` in `session` in a detached process. Returns {id, pid, log}. spawnImpl is injectable for tests. */
|
|
37
|
+
export async function startBackground(session,task,o={},{spawnImpl=spawn,bin=mlaiBin(),env=process.env}={}){
|
|
38
|
+
if(!String(task||'').trim())throw new Error('Give a task: mlai --bg "what to do"');
|
|
39
|
+
const prior=await readJson(path.join(session.dir,'bg.json'),null);
|
|
40
|
+
if(prior?.state==='running'&&alive(prior.pid))throw new Error('This session is already working in the background. mlai attach '+session.meta.id.slice(0,8));
|
|
41
|
+
const log=path.join(session.dir,'bg.log'),file=path.join(session.dir,'bg.json');
|
|
42
|
+
// bg.json exists before the child starts, so a fast child's finishBackground is never overwritten.
|
|
43
|
+
const info={pid:null,task:String(task).slice(0,2000),started:new Date().toISOString(),state:'running',log};
|
|
44
|
+
await writeJson(file,info);
|
|
45
|
+
session.meta.background=true;await session.save?.();
|
|
46
|
+
const fd=openSync(log,'a',0o600);
|
|
47
|
+
let child;
|
|
48
|
+
try{child=spawnImpl(process.execPath,[bin,...childArgs(o,session.meta.id,task)],{cwd:session.meta.root,env:{...env,MLAI_BG:'1'},detached:true,stdio:['ignore',fd,fd],windowsHide:true})}
|
|
49
|
+
catch(e){await writeJson(file,{...info,state:'error',ended:new Date().toISOString()});throw e}
|
|
50
|
+
finally{closeSync(fd)}
|
|
51
|
+
child.unref?.();
|
|
52
|
+
info.pid=child.pid;
|
|
53
|
+
const now=await readJson(file,info);await writeJson(file,{...now,pid:child.pid});
|
|
54
|
+
return {id:session.meta.id,...info};
|
|
55
|
+
}
|
|
56
|
+
/** Called by the child when its run ends (cli.mjs headless with --bg-child). */
|
|
57
|
+
export async function finishBackground(dir,{state,exitCode}){
|
|
58
|
+
const cur=await readJson(path.join(dir,'bg.json'),{});
|
|
59
|
+
await writeJson(path.join(dir,'bg.json'),{...cur,state:state||'error',exitCode,ended:new Date().toISOString()});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** State of one session for `mlai agents`: running, waiting (an approval), done states, or lost. */
|
|
63
|
+
export async function agentInfo(meta,dir){
|
|
64
|
+
const bg=await readJson(path.join(dir,'bg.json'),null);
|
|
65
|
+
const lockPid=Number(await readFile(path.join(dir,'running.lock'),'utf8').catch(()=>''))||0;
|
|
66
|
+
const pending=await readJson(path.join(dir,'pending.json'),null),status=await readJson(path.join(dir,'status.json'),{});
|
|
67
|
+
const starting=bg?.state==='running'&&!bg.pid&&Date.now()-Date.parse(bg.started)<15000;
|
|
68
|
+
const running=bg?.state==='running'?(starting||alive(bg.pid)):alive(lockPid);
|
|
69
|
+
let state;
|
|
70
|
+
if(bg?.state==='running')state=running?(pending?.id?'waiting':'running'):(FINAL.has(status.state)?status.state:'lost');
|
|
71
|
+
else if(bg)state=bg.state;
|
|
72
|
+
else state=running?(pending?.id?'waiting':'running'):null;
|
|
73
|
+
if(!state)return null;
|
|
74
|
+
return {id:meta.id,title:meta.title||'',folder:meta.folder,root:meta.root,background:Boolean(bg),state,pid:bg?.pid||lockPid||null,
|
|
75
|
+
task:bg?.task||meta.turns?.at(-1)?.task||'',started:bg?.started||meta.turns?.at(-1)?.started||null,ended:bg?.ended||null,exitCode:bg?.exitCode??null,
|
|
76
|
+
waiting:pending?.id?{id:pending.id,kind:pending.kind||'command',command:clip(pending.command||pending.description||'',200)}:null,log:bg?.log||null};
|
|
77
|
+
}
|
|
78
|
+
/** Background sessions (and sessions running in other terminals), running first, newest first. */
|
|
79
|
+
export async function listAgents({Session,sessionsDir,limit=30}){
|
|
80
|
+
const out=[];
|
|
81
|
+
for(const m of await Session.list()){
|
|
82
|
+
const a=await agentInfo(m,path.join(sessionsDir,m.id));if(a)out.push(a);
|
|
83
|
+
if(out.length>=limit*2)break;
|
|
84
|
+
}
|
|
85
|
+
const rank=s=>s==='waiting'?0:s==='running'?1:2;
|
|
86
|
+
return out.sort((a,b)=>rank(a.state)-rank(b.state)||String(b.started||'').localeCompare(String(a.started||''))).slice(0,limit);
|
|
87
|
+
}
|
|
88
|
+
export function agentLine(a,c={bold:t=>t,dim:t=>t,yellow:t=>t,green:t=>t,red:t=>t,cyan:t=>t}){
|
|
89
|
+
const st=a.state==='waiting'?c.yellow('needs you'):a.state==='running'?c.cyan('running'):a.state==='completed'?c.green('done'):a.state==='lost'?c.red('ended'):c.red(a.state);
|
|
90
|
+
return c.bold(a.id.slice(0,8))+' '+(st+' '.repeat(Math.max(0,10-String(a.state==='waiting'?'needs you':a.state==='completed'?'done':a.state==='lost'?'ended':a.state).length)))+' '+clip(a.title||a.task,40).padEnd(40)+' '+c.dim(a.folder+' \u00b7 '+(a.started?ago(a.started)+' ago':'')+(a.background?'':' \u00b7 in a terminal'));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A rendered log for `mlai agents logs`: stream-json events through renderEvent, other lines as they are. */
|
|
94
|
+
export function renderLog(text,renderEvent,{c,verbose=false}={}){
|
|
95
|
+
const out=[];
|
|
96
|
+
for(const line of String(text||'').split('\n')){
|
|
97
|
+
if(!line.trim())continue;let e=null;try{e=JSON.parse(line)}catch{}
|
|
98
|
+
if(e&&typeof e==='object'&&e.type){
|
|
99
|
+
if(e.type==='session')out.push((c?.dim||String)('session '+String(e.id||'').slice(0,8)+' · '+(e.mode||'')+' mode'));
|
|
100
|
+
else if(e.type==='result')out.push((c?.dim||String)('result: '+e.state+(e.text?'\n'+e.text:'')));
|
|
101
|
+
else{const r=renderEvent(e,{c,verbose});if(r)out.push(r)}
|
|
102
|
+
}else out.push(line);
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Follows a session: replays the current turn, then streams new events. Approvals are shown once each and answered
|
|
109
|
+
* with handleLine('y'|'a'|'n'); other lines steer the agent; '/stop' stops it; detach() leaves it running.
|
|
110
|
+
* Resolves `done` with {state, detached} when the run ends or on detach.
|
|
111
|
+
*/
|
|
112
|
+
export function attachSession(session,{write,approvalView,renderEvent,c,verbose=false,pollMs=300,replay=40,isRunning}={}){
|
|
113
|
+
let pending=null,shown=new Set(),finished=false,resolveDone;
|
|
114
|
+
const done=new Promise(r=>resolveDone=r);
|
|
115
|
+
const lines=[];
|
|
116
|
+
const onEvent=e=>{if(e.type==='approval')return;const r=renderEvent(e,{c,verbose});if(r)(replaying?lines.push(r):write(r))};
|
|
117
|
+
let replaying=true;session.offset=0;session.on('event',onEvent);
|
|
118
|
+
const end=(state,detached=false)=>{if(finished)return;finished=true;clearInterval(timer);session.off('event',onEvent);resolveDone({state,detached})};
|
|
119
|
+
const tick=async()=>{
|
|
120
|
+
if(finished)return;
|
|
121
|
+
await session.poll().catch(()=>{});
|
|
122
|
+
if(replaying){replaying=false;for(const l of lines.slice(-replay))write(l);lines.length=0}
|
|
123
|
+
const p=await session.pending().catch(()=>null);
|
|
124
|
+
if(p?.id&&!shown.has(p.id)){shown.add(p.id);pending=p;write(approvalView(p,c).text);write((c?.yellow||String)('approve? [y]es / [a]ll / [n]o'))}
|
|
125
|
+
else if(!p?.id)pending=null;
|
|
126
|
+
if(!await isRunning()){await session.poll().catch(()=>{});const st=await readJson(path.join(session.dir,'status.json'),{});end(st.state||'completed')}
|
|
127
|
+
};
|
|
128
|
+
let busy=false;const timer=setInterval(()=>{if(busy)return;busy=true;tick().finally(()=>{busy=false})},pollMs);// kept referenced: attach waits on it until the run ends or detaches
|
|
129
|
+
setImmediate(()=>{if(!busy){busy=true;tick().finally(()=>{busy=false})}});
|
|
130
|
+
return {
|
|
131
|
+
done,
|
|
132
|
+
get pending(){return pending},
|
|
133
|
+
async handleLine(raw){
|
|
134
|
+
const line=String(raw||'').trim();if(!line||finished)return null;
|
|
135
|
+
if(pending){
|
|
136
|
+
const v=line.toLowerCase(),verdict=v==='y'||v==='yes'?'approve':v==='a'||v==='all'?'approve_all':v==='n'||v==='no'?'reject':null;
|
|
137
|
+
if(!verdict){write('Answer y, a or n.');return null}
|
|
138
|
+
const p=pending;pending=null;await session.decide(p.id,verdict);write((c?.dim||String)(verdict==='approve'?'Approved.':verdict==='approve_all'?'Approved, and the rest of this run too.':'Rejected.'));return verdict;
|
|
139
|
+
}
|
|
140
|
+
if(line==='/stop'){await session.cancel();write('Stopping...');return 'stop'}
|
|
141
|
+
if(line==='/detach'){end('running',true);return 'detach'}
|
|
142
|
+
await session.steer(line);write((c?.dim||String)('Sent to the agent.'));return 'steer';
|
|
143
|
+
},
|
|
144
|
+
detach(){end('running',true)},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Stops a session: asks it to stop, then ends the background process if it does not within `graceMs`. */
|
|
149
|
+
export async function stopAgent(session,{graceMs=10000,sleep=ms=>new Promise(r=>setTimeout(r,ms))}={}){
|
|
150
|
+
await session.cancel();
|
|
151
|
+
const bg=await readJson(path.join(session.dir,'bg.json'),null);
|
|
152
|
+
if(!bg?.pid||bg.state!=='running')return {stopped:true};
|
|
153
|
+
for(let t=0;t<graceMs;t+=250){if(!alive(bg.pid))break;await sleep(250)}
|
|
154
|
+
if(alive(bg.pid)){try{process.kill(process.platform==='win32'?bg.pid:-bg.pid,'SIGTERM')}catch{try{process.kill(bg.pid,'SIGTERM')}catch{}}}
|
|
155
|
+
for(let t=0;t<3000&&alive(bg.pid);t+=250)await sleep(250);
|
|
156
|
+
const now=await readJson(path.join(session.dir,'bg.json'),bg);
|
|
157
|
+
if(now.state==='running')await finishBackground(session.dir,{state:'stopped',exitCode:130});
|
|
158
|
+
return {stopped:true};
|
|
159
|
+
}
|
|
160
|
+
/** Reads a log from `offset`; returns {text, offset}. */
|
|
161
|
+
export async function readFrom(file,offset=0){
|
|
162
|
+
let size;try{size=(await stat(file)).size}catch{return {text:'',offset}}
|
|
163
|
+
if(size<offset)offset=0;if(size===offset)return {text:'',offset};
|
|
164
|
+
const fh=await open(file,'r');try{const b=Buffer.alloc(size-offset);await fh.read(b,0,b.length,offset);const t=b.toString('utf8'),end=t.lastIndexOf('\n');if(end<0)return {text:'',offset};return {text:t.slice(0,end+1),offset:offset+Buffer.byteLength(t.slice(0,end+1))}}finally{await fh.close()}
|
|
165
|
+
}
|
|
166
|
+
/** Whether the session's run is still going: its background process, or the terminal that holds its lock. */
|
|
167
|
+
export async function stillRunning(dir){
|
|
168
|
+
const bg=await readJson(path.join(dir,'bg.json'),null);
|
|
169
|
+
if(bg?.state==='running')return bg.pid?alive(bg.pid):Date.now()-Date.parse(bg.started)<15000;
|
|
170
|
+
const pid=Number(await readFile(path.join(dir,'running.lock'),'utf8').catch(()=>''))||0;
|
|
171
|
+
return alive(pid);
|
|
172
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Background terminals: shell commands the user starts with `!cmd &` or /bg that keep running while the session
|
|
3
|
+
* goes on (dev servers, watchers, long builds). /ps lists them, /ps <id> shows recent output, /stop ends one or all.
|
|
4
|
+
* When one finishes, its tail can go with the next message, like `!` output.
|
|
5
|
+
*
|
|
6
|
+
* One manager per process (`terminals`), shared by the full TUI and the plain loop. Dependency-free; on Windows the
|
|
7
|
+
* command runs in PowerShell and is stopped with taskkill /T so child processes go too.
|
|
8
|
+
*/
|
|
9
|
+
import {spawn,execFile} from 'node:child_process';
|
|
10
|
+
import {EventEmitter} from 'node:events';
|
|
11
|
+
|
|
12
|
+
const MAX_OUT=200_000;
|
|
13
|
+
/**
|
|
14
|
+
* Environment for a Windows PowerShell 5.1 child. When the CLI runs inside PowerShell 7, PSModulePath points at
|
|
15
|
+
* PowerShell 7 modules, and 5.1 then fails to load its own (Get-ChildItem "is not recognized"). Dropping it lets
|
|
16
|
+
* 5.1 rebuild its default module path.
|
|
17
|
+
*/
|
|
18
|
+
export function powershellEnv(env=process.env){const e={...env};for(const k of Object.keys(e))if(k.toLowerCase()==='psmodulepath')delete e[k];return e}
|
|
19
|
+
export const shellFor=(command,{platform=process.platform,env=process.env}={})=>platform==='win32'
|
|
20
|
+
?{file:'powershell.exe',args:['-NoProfile','-NonInteractive','-Command',command]}
|
|
21
|
+
:{file:env.SHELL&&!/fish$/.test(env.SHELL)?env.SHELL:'/bin/sh',args:['-c',command]};
|
|
22
|
+
/** `npm run dev &` -> 'npm run dev' (a trailing lone & starts a background terminal); null otherwise. */
|
|
23
|
+
export function backgroundCommand(line){
|
|
24
|
+
const m=/^(.*?[^&|\\])\s*&\s*$/s.exec(String(line||''));
|
|
25
|
+
return m&&m[1].trim()?m[1].trim():null;
|
|
26
|
+
}
|
|
27
|
+
const fmt=ms=>{const s=Math.floor(ms/1000);return s<60?s+'s':s<3600?Math.floor(s/60)+'m '+String(s%60).padStart(2,'0')+'s':Math.floor(s/3600)+'h '+String(Math.floor(s/60)%60).padStart(2,'0')+'m'};
|
|
28
|
+
|
|
29
|
+
export class Terminals extends EventEmitter{
|
|
30
|
+
constructor({spawnImpl=spawn,platform=process.platform}={}){super();this.jobs=new Map();this.next=1;this.spawnImpl=spawnImpl;this.platform=platform}
|
|
31
|
+
/** Starts `command` in `cwd`; returns the job. Emits 'exit' (job) when it ends. */
|
|
32
|
+
start(command,{cwd=process.cwd(),env=process.env}={}){
|
|
33
|
+
command=String(command||'').trim();if(!command)throw new Error('Give a command to run in the background.');
|
|
34
|
+
if(this.running().length>=8)throw new Error('Up to 8 background terminals at a time; /stop one first.');
|
|
35
|
+
const {file,args}=shellFor(command,{platform:this.platform,env});
|
|
36
|
+
const win=this.platform==='win32';
|
|
37
|
+
const child=this.spawnImpl(file,args,{cwd,env:{...(win?powershellEnv(env):env),MLAI_BACKGROUND:'1'},stdio:['ignore','pipe','pipe'],detached:!win,windowsHide:true});
|
|
38
|
+
const job={id:this.next++,command,cwd,pid:child.pid,started:Date.now(),ended:null,code:null,signal:null,out:'',lines:0,child,reported:false,stopping:false};
|
|
39
|
+
const add=d=>{const s=String(d).replace(/\r\n/g,'\n');job.out+=s;job.lines+=(s.match(/\n/g)||[]).length;if(job.out.length>MAX_OUT)job.out=job.out.slice(-MAX_OUT/2)};
|
|
40
|
+
child.stdout?.on('data',add);child.stderr?.on('data',add);
|
|
41
|
+
child.on('error',e=>{add(e.message+'\n');if(job.ended==null){job.ended=Date.now();job.code=127;this.emit('exit',job)}});
|
|
42
|
+
child.on('close',(code,signal)=>{if(job.ended!=null)return;job.ended=Date.now();job.code=code;job.signal=signal;job.child=null;this.emit('exit',job)});
|
|
43
|
+
this.jobs.set(job.id,job);this.emit('start',job);
|
|
44
|
+
return job;
|
|
45
|
+
}
|
|
46
|
+
running(){return [...this.jobs.values()].filter(j=>j.ended==null)}
|
|
47
|
+
list(){return [...this.jobs.values()]}
|
|
48
|
+
get(id){return this.jobs.get(Number(String(id).replace(/^#/,'')))||null}
|
|
49
|
+
/** Last `n` lines of a job's output. */
|
|
50
|
+
tail(job,n=20){const rows=job.out.replace(/\s+$/,'').split(/\r?\n/);return rows.length===1&&!rows[0]?[]:rows.slice(-n)}
|
|
51
|
+
status(job,now=Date.now()){
|
|
52
|
+
if(job.ended==null)return 'running '+fmt(now-job.started);
|
|
53
|
+
if(job.stopping)return 'stopped';
|
|
54
|
+
return (job.code===0?'exit 0':'exit '+(job.code??job.signal))+' after '+fmt(job.ended-job.started);
|
|
55
|
+
}
|
|
56
|
+
/** One row per job for /ps. */
|
|
57
|
+
rows(now=Date.now()){return this.list().map(j=>({id:j.id,command:j.command,status:this.status(j,now),running:j.ended==null,last:this.tail(j,1)[0]||''}))}
|
|
58
|
+
/** Stops one job (process tree). Resolves when it has ended or after 3 s. */
|
|
59
|
+
stop(job){
|
|
60
|
+
if(!job||job.ended!=null)return Promise.resolve(false);
|
|
61
|
+
job.stopping=true;
|
|
62
|
+
return new Promise(resolve=>{
|
|
63
|
+
const done=()=>{clearTimeout(timer);resolve(true)};
|
|
64
|
+
this.once('exit',function on(j){if(j===job)done();else this.once('exit',on)});
|
|
65
|
+
const timer=setTimeout(()=>{try{this.platform==='win32'?execFile('taskkill',['/PID',String(job.pid),'/T','/F'],()=>{}):process.kill(-job.pid,'SIGKILL')}catch{}resolve(true)},3000);
|
|
66
|
+
try{
|
|
67
|
+
if(this.platform==='win32')execFile('taskkill',['/PID',String(job.pid),'/T','/F'],{windowsHide:true},()=>{});
|
|
68
|
+
else{try{process.kill(-job.pid,'SIGTERM')}catch{job.child?.kill('SIGTERM')}}
|
|
69
|
+
}catch{}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
async stopAll(){const r=this.running();await Promise.all(r.map(j=>this.stop(j)));return r.length}
|
|
73
|
+
/** Context for the next message: the tail of a finished job. */
|
|
74
|
+
contextOf(job){
|
|
75
|
+
const tail=this.tail(job,60).join('\n');
|
|
76
|
+
return '$ '+job.command+' (background #'+job.id+')\n```\n'+(tail.length>20000?'...'+tail.slice(-20000):tail)+'\n```\n('+this.status(job)+')';
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export const terminals=new Terminals();
|
package/src/tui/chat.mjs
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The terminal conversation (CLI v1): one Session plus the choices that apply to its next turns (model, mode, effort,
|
|
3
|
+
* extra folders) and the per-session totals. Both the plain loop (cli.mjs) and the full TUI (tui/app.mjs) send every
|
|
4
|
+
* turn through chat.send, so modes, model choice, permissions and /rewind snapshots work the same in both.
|
|
5
|
+
*
|
|
6
|
+
* Fields read by the status line and commands: model, modelLabel, credits, mode, effort, usage {tokens, calls},
|
|
7
|
+
* tokensLeft, context {used, window}, branch, running. Emits 'change' when any of them change, 'session' when the
|
|
8
|
+
* session is replaced (/clear, /resume, /rewind, /fork), and 'turn' with each finished result.
|
|
9
|
+
*/
|
|
10
|
+
import {EventEmitter} from 'node:events';
|
|
11
|
+
import {execFileSync} from 'node:child_process';
|
|
12
|
+
import {existsSync} from 'node:fs';
|
|
13
|
+
import {readFile,readdir,rename,mkdir,rm,cp,writeFile} from 'node:fs/promises';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import {randomUUID} from 'node:crypto';
|
|
16
|
+
import {Session} from '../session.mjs';
|
|
17
|
+
import {sub} from '../home.mjs';
|
|
18
|
+
import {twoWordTitle} from '../two-words.mjs';
|
|
19
|
+
import {MODES,modeName,sessionMode,taskFor,applyMode} from '../modes.mjs';
|
|
20
|
+
import {plainUi} from './plain.mjs';
|
|
21
|
+
import {snapshot,restore,forget} from './snapshots.mjs';
|
|
22
|
+
|
|
23
|
+
/** Used when the server does not list models (older servers, offline). */
|
|
24
|
+
export const FALLBACK_MODELS=[{id:'pixis',label:'Pixis',available:true,vision:true,credits:1,creditLabel:'Standard credits'}];
|
|
25
|
+
/** Credits like the app shows them (lib/plans.ts TOKENS_PER_CREDIT; tests/cli-credits.test.mjs keeps them in step). */
|
|
26
|
+
export const TOKENS_PER_CREDIT=60_000;
|
|
27
|
+
export const creditsFor=tokens=>Math.round(Math.max(0,Number(tokens)||0)/TOKENS_PER_CREDIT*100)/100;
|
|
28
|
+
export function formatCredits(n){const v=Math.max(0,Number(n)||0);return v>=1000?Math.round(v).toLocaleString('en-US'):v>=100?String(Math.round(v)):String(Math.round(v*10)/10)}
|
|
29
|
+
/** Engine run modes the server understands (lib/run-request.ts). */
|
|
30
|
+
const RUN_MODE={guided:'approve',plan:'plan',auto:'auto'};
|
|
31
|
+
/** An overloaded or unavailable model (start refused, or the run failed on model errors): try the next fallback model. */
|
|
32
|
+
export const MODEL_BUSY=/HTTP Error (429|5\d\d)|\b(529|overloaded|over capacity)\b|model_not_configured|is not configured|not available yet|temporarily unavailable|rate.?limit/i;
|
|
33
|
+
export function modelBusy(e){return Boolean(e)&&(e.status===503||e.status===529||e.code==='model_not_configured'||MODEL_BUSY.test(String(e.message||e.error||e)))}
|
|
34
|
+
/** fallbackModel ('a,b', 'a' or ['a','b']) as a list of ids. */
|
|
35
|
+
export const modelList=v=>(Array.isArray(v)?v:typeof v==='string'?v.split(','):[]).map(x=>String(x).trim()).filter(Boolean).slice(0,5);
|
|
36
|
+
const COMPACT_TASK='Summarize our conversation so far so it can continue from the summary alone: the goal, decisions made, files created or changed (with paths), commands and checks that matter, and open items. Be specific and brief. Do not edit files.';
|
|
37
|
+
|
|
38
|
+
/** The final answer of a turn from its events and status, like the app shows it. */
|
|
39
|
+
export function answerOf(turn){
|
|
40
|
+
const ev=turn?.events||[];
|
|
41
|
+
const a=[...ev].reverse().find(e=>e.type==='answer'&&e.content);if(a)return String(a.content);
|
|
42
|
+
const sub=turn?.status?.result?.submission;if(typeof sub==='string'&&sub&&sub!=='Task complete')return sub;
|
|
43
|
+
const last=[...ev].reverse().find(e=>e.type==='assistant'&&typeof e.content==='string'&&e.content.trim());
|
|
44
|
+
return last?String(last.content):(turn?.status?.error||'');
|
|
45
|
+
}
|
|
46
|
+
const sortHistory=names=>names.filter(n=>n.endsWith('.json')).sort((a,b)=>a.length-b.length||a.localeCompare(b));
|
|
47
|
+
|
|
48
|
+
export class Chat extends EventEmitter{
|
|
49
|
+
constructor({session,settings={},cloud=null,flags={},models=null}){
|
|
50
|
+
super();
|
|
51
|
+
this.settings=settings;this.cloud=cloud;this.flags=flags;this.models=models||null;
|
|
52
|
+
this.addDirs=(flags.addDirs||[]).map(d=>path.resolve(d));
|
|
53
|
+
// Restricted mode (src/restricted.mjs) never runs unsandboxed or without approvals.
|
|
54
|
+
this.restricted=Boolean(flags.restricted);this.allowUnsandboxed=!this.restricted&&flags.sandbox===false;this.skipPermissions=!this.restricted&&Boolean(flags.skipPermissions);
|
|
55
|
+
this.running=false;this.tokensLeft=null;this.context=null;this.waiting=[];this.extensions=null;
|
|
56
|
+
this.#bind(session);
|
|
57
|
+
this.mode=modeName(flags.mode)||(session.meta.turns.length||session.meta.cliMode?sessionMode(session.meta):modeName(settings.mode))||'agent';
|
|
58
|
+
this.model=flags.model||session.meta.model||settings.model||null;
|
|
59
|
+
this.effort=flags.effort||session.meta.effort||settings.effort||'medium';
|
|
60
|
+
this.steps=Number(flags.maxSteps||settings.maxSteps)||120;
|
|
61
|
+
this.fallbacks=modelList(flags.fallbackModel??settings.fallbackModel);
|
|
62
|
+
// Headless controls (src/headless.mjs): permission rules from --allowedTools/--disallowedTools/--tools, text added
|
|
63
|
+
// ahead of each task (--append-system-prompt) and a token cap for the next run (--max-budget-credits).
|
|
64
|
+
this.toolRules=flags.toolRules||null;this.appendPrompt=flags.appendSystemPrompt||'';this.maxTokens=null;
|
|
65
|
+
}
|
|
66
|
+
#bind(s){
|
|
67
|
+
if(this.session)this.session.off('started',this.onStarted);
|
|
68
|
+
this.session=s;
|
|
69
|
+
this.onStarted=e=>{if(e.tokensLeft!=null)this.tokensLeft=e.tokensLeft;this.emit('change')};
|
|
70
|
+
s.on('started',this.onStarted);
|
|
71
|
+
this.usage={tokens:s.meta.turns.reduce((a,t)=>a+(t.tokens||0),0),calls:s.meta.turns.reduce((a,t)=>a+(t.calls||0),0)};
|
|
72
|
+
}
|
|
73
|
+
get info(){const list=this.models||FALLBACK_MODELS;return list.find(m=>m.id===this.model)||(this.model&&!this.models?{id:this.model,label:this.model,available:true,creditLabel:'Credits per your plan'}:null)||list.find(m=>m.id===(this.defaultModel||'pixis'))||list[0]}
|
|
74
|
+
get modelLabel(){return this.info?.label||this.model||'Pixis'}
|
|
75
|
+
get credits(){return this.info?.creditLabel||'Standard credits'}
|
|
76
|
+
get branch(){try{return execFileSync('git',['branch','--show-current'],{cwd:this.session.meta.root,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim()||null}catch{return null}}
|
|
77
|
+
|
|
78
|
+
/** The account's model list from the server (GET /api/clients); falls back to the default model. */
|
|
79
|
+
async loadModels(){
|
|
80
|
+
if(this.models)return this.models;
|
|
81
|
+
try{const caps=await this.cloud?.device?.capabilities();if(Array.isArray(caps?.models)&&caps.models.length){this.models=caps.models;this.defaultModel=caps.defaultModel||null}}catch{}
|
|
82
|
+
return this.models||FALLBACK_MODELS;
|
|
83
|
+
}
|
|
84
|
+
async setModel(id){
|
|
85
|
+
const list=await this.loadModels();let m=list.find(x=>x.id===id||x.label.toLowerCase()===String(id).toLowerCase());
|
|
86
|
+
// Without the server's list (older server, offline) any id is passed on; the server checks it.
|
|
87
|
+
if(!m&&!this.models&&/^[\w.:/-]{1,80}$/.test(String(id)))m={id:String(id),label:String(id),available:true,creditLabel:'Credits per your plan'};
|
|
88
|
+
if(!m)throw new Error('No model '+id+'. Run /model to see the list.');
|
|
89
|
+
if(m.available===false)throw new Error(m.label+' is not available yet.');
|
|
90
|
+
this.model=m.id;this.session.meta.model=m.id;await this.session.save();this.emit('change');return m;
|
|
91
|
+
}
|
|
92
|
+
async setMode(m){
|
|
93
|
+
const name=modeName(m);if(!name)throw new Error('Modes: agent, plan, ask, auto');
|
|
94
|
+
await applyMode(this.session,name);this.mode=name;this.emit('change');return name;
|
|
95
|
+
}
|
|
96
|
+
/** Effort levels the current model takes (the server's list; all of them when the server does not say). */
|
|
97
|
+
get efforts(){const e=this.info?.efforts;return Array.isArray(e)?e:['low','medium','high','max']}
|
|
98
|
+
async setEffort(e){if(!['low','medium','high','max'].includes(e))throw new Error('Effort is low, medium, high or max');
|
|
99
|
+
const ok=this.efforts;if(ok.length&&!ok.includes(e))throw new Error(this.modelLabel+' takes '+ok.join(', ')+' effort');this.effort=e;this.session.meta.effort=e;await this.session.save();this.emit('change')}
|
|
100
|
+
async setSession(s){this.#bind(s);this.mode=sessionMode(s.meta);if(s.meta.model)this.model=s.meta.model;this.emit('session',s);this.emit('change')}
|
|
101
|
+
async rename(title){
|
|
102
|
+
const t=String(title||'').replace(/[\x00-\x1f\x7f]/g,'').trim().slice(0,80);if(!t)throw new Error('Give a name: /rename <name>');
|
|
103
|
+
this.session.meta.title=t;this.session.meta.renamed=true;await this.session.save();this.emit('change');return t;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The run body the server builds the request from, exactly like the app's (Contract A). */
|
|
107
|
+
runBody(){
|
|
108
|
+
return {mode:RUN_MODE[MODES[this.mode].engine],model:this.model||undefined,effort:this.effort,role:'engineer',planApproval:'off',askFirst:'never',steps:this.steps,...(this.maxTokens?{maxTokens:this.maxTokens}:{})};
|
|
109
|
+
}
|
|
110
|
+
/** One turn. Takes a file snapshot first (for /rewind), applies the mode, model, effort and permissions. */
|
|
111
|
+
async send(text,{images,onProgress=()=>{},raw=false}={}){
|
|
112
|
+
if(this.running)throw new Error('A task is already running in this session');
|
|
113
|
+
const s=this.session;this.running=true;this.emit('change');
|
|
114
|
+
try{
|
|
115
|
+
if(MODES[this.mode].engine!==s.meta.mode||s.meta.cliMode!==this.mode)await applyMode(s,this.mode);
|
|
116
|
+
const mod=await import('./extensions-local.mjs').catch(()=>null); // every turn: /permissions, /mcp, /hooks, /sandbox apply at once
|
|
117
|
+
// Restricted mode fails closed: without its extensions the run would not be restricted, so it does not start.
|
|
118
|
+
if(this.restricted&&!mod?.localExtensions)throw new Error('Restricted mode could not load its rules, so nothing ran.');
|
|
119
|
+
this.extensions=mod?.localExtensions?await mod.localExtensions({root:s.meta.root,settings:this.settings,skipPermissions:this.skipPermissions,restricted:this.restricted}).catch(e=>{if(this.restricted)throw e;return undefined}):undefined;
|
|
120
|
+
if(this.toolRules){const p={...(this.extensions?.permissions||{})};for(const k of this.restricted?['deny','ask']:['allow','deny','ask'])if(this.toolRules[k]?.length)p[k]=[...new Set([...(p[k]||[]),...this.toolRules[k]])];
|
|
121
|
+
const w=this.extensions?.warnings;this.extensions={...(this.extensions||{}),permissions:p};if(w)Object.defineProperty(this.extensions,'warnings',{value:w})}
|
|
122
|
+
const dirs=this.addDirs.length?'\n\nYou may also read these folders: '+this.addDirs.join(', '):'';
|
|
123
|
+
const body=(raw?text:taskFor(this.mode,text))+dirs;
|
|
124
|
+
const task=this.appendPrompt&&!raw?'Session instructions from the user (follow them for this task):\n'+this.appendPrompt.slice(0,20000)+'\n\nTask:\n'+body:body;
|
|
125
|
+
if(task!==body&&!this.session.meta.title)this.session.meta.title=twoWordTitle(text);// name it after the task, not the instructions
|
|
126
|
+
const queue=this.fallbacks.filter(m=>m!==this.model);let r;
|
|
127
|
+
for(;;){
|
|
128
|
+
await snapshot(s,s.meta.turns.length);
|
|
129
|
+
const next=()=>{const to=queue.shift();if(!to)return null;const from=this.model;this.model=to;this.emit('fallback',{from:from||this.defaultModel||'pixis',to});this.emit('change');return to};
|
|
130
|
+
try{r=await s.send(task,{cloud:this.cloud,steps:this.steps,effort:this.effort,onProgress,allowUnsandboxed:this.allowUnsandboxed,images,run:this.runBody(),
|
|
131
|
+
...(this.addDirs.length?{extraRead:this.addDirs}:{}),...(this.extensions?{extensions:this.extensions}:{})})}
|
|
132
|
+
catch(e){if(modelBusy(e)&&next())continue;throw e}
|
|
133
|
+
this.usage.tokens+=r.usage?.tokens||0;this.usage.calls+=r.usage?.calls||0;
|
|
134
|
+
// Retry only a run that changed nothing: a half-done task is never repeated on another model.
|
|
135
|
+
if(!['completed','stopped','limited'].includes(r.state)&&!r.code&&!(r.completion?.changedFiles||[]).length&&modelBusy(r.error)&&next())continue;
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
if(r.contextTokens)this.context={used:r.contextTokens,window:r.contextWindow||null};
|
|
139
|
+
this.emit('turn',r);
|
|
140
|
+
return r;
|
|
141
|
+
}finally{this.running=false;this.emit('change');this.#drain()}
|
|
142
|
+
}
|
|
143
|
+
/** Queues a turn for when the agent is idle; resolves with {state, answer} when it ends (used by /loop). */
|
|
144
|
+
queue(text){return new Promise((resolve,reject)=>{this.waiting.push({text,resolve,reject});if(!this.running)this.#drain()})}
|
|
145
|
+
#drain(){
|
|
146
|
+
const next=this.waiting.shift();if(!next)return;
|
|
147
|
+
this.send(next.text).then(async r=>next.resolve({state:r.state,answer:await this.lastAnswer(),result:r}),next.reject);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Earlier turns plus the current one (Session.transcript). */
|
|
151
|
+
transcript(){return this.session.transcript()}
|
|
152
|
+
async lastAnswer(){const t=await this.transcript();return answerOf(t.at(-1))}
|
|
153
|
+
/** The conversation as Markdown, for /export. */
|
|
154
|
+
async markdown(){
|
|
155
|
+
const m=this.session.meta,turns=await this.transcript();
|
|
156
|
+
const lines=['# '+(m.title||'ML AI Code session'),'',`Folder: ${m.root} `,`Session: ${m.id} `,`Exported: ${new Date().toISOString().slice(0,16).replace('T',' ')}`,''];
|
|
157
|
+
for(const t of turns){
|
|
158
|
+
lines.push('## You','',String(t.task||'').replace(/^Answer the question from the code[^\n]*\n\nQuestion: /,''),'');
|
|
159
|
+
const files=t.completion?.changedFiles||[];
|
|
160
|
+
lines.push('## ML AI Code','',answerOf(t)||'(no answer)','');
|
|
161
|
+
if(files.length)lines.push('Changed: '+files.map(f=>typeof f==='string'?f:f.path).join(', '),'');
|
|
162
|
+
}
|
|
163
|
+
return lines.join('\n');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** /compact: a read-only summary turn becomes the conversation's only history; older turns move to history-compacted. */
|
|
167
|
+
async compact(focus=''){
|
|
168
|
+
const s=this.session,before=this.mode;
|
|
169
|
+
this.mode='plan';
|
|
170
|
+
let r;try{r=await this.send(COMPACT_TASK+(focus?'\nFocus on: '+focus.slice(0,500):''),{raw:true})}finally{this.mode=before;await applyMode(s,before).catch(()=>{})}
|
|
171
|
+
if(r.state!=='completed')return {ok:false,result:r};
|
|
172
|
+
const h=path.join(s.dir,'history'),old=path.join(s.dir,'history-compacted');
|
|
173
|
+
await mkdir(old,{recursive:true});
|
|
174
|
+
for(const n of sortHistory(await readdir(h).catch(()=>[])))await rename(path.join(h,n),path.join(old,n));
|
|
175
|
+
// The Kimi harness keeps its own session; drop it so the next turn starts from the summary.
|
|
176
|
+
await rm(path.join(s.dir,'kimi-session.json'),{force:true});
|
|
177
|
+
s.meta.compacted=(s.meta.compacted||0)+1;s.meta.compactedAt=s.meta.turns.length;await s.save();
|
|
178
|
+
this.emit('change');
|
|
179
|
+
return {ok:true,result:r,summary:await this.lastAnswer()};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Turns that /rewind can return to: [{turn, task, when}]. */
|
|
183
|
+
rewindPoints(){return this.session.meta.turns.map((t,i)=>({turn:i,task:t.task,when:t.started})).filter(p=>p.turn>=(this.session.meta.compactedAt||0))}
|
|
184
|
+
/**
|
|
185
|
+
* Returns to the moment before `turn` (0-based): files (snapshot), conversation (later turns removed) or both.
|
|
186
|
+
* what: 'both' | 'files' | 'chat'.
|
|
187
|
+
*/
|
|
188
|
+
async rewind(turn,what='both'){
|
|
189
|
+
const s=this.session,n=s.meta.turns.length;
|
|
190
|
+
if(!Number.isInteger(turn)||turn<0||turn>=n)throw new Error('Pick a turn from 1 to '+n+'.');
|
|
191
|
+
if(this.running)throw new Error('Stop the agent first (Esc or Ctrl-C).');
|
|
192
|
+
let files=null;
|
|
193
|
+
if(what!=='chat')files=await restore(s,turn);
|
|
194
|
+
if(what!=='files'){
|
|
195
|
+
const h=path.join(s.dir,'history'),names=sortHistory(await readdir(h).catch(()=>[]));
|
|
196
|
+
const current=existsSync(path.join(s.dir,'events.jsonl'))||existsSync(path.join(s.dir,'request.json'));
|
|
197
|
+
const firstIndex=n-(current?1:0)-names.length;// turn index of names[0]
|
|
198
|
+
const gone=path.join(s.dir,'history-rewound');await mkdir(gone,{recursive:true});
|
|
199
|
+
for(let i=0;i<names.length;i++)if(firstIndex+i>=turn)await rename(path.join(h,names[i]),path.join(gone,names[i]));
|
|
200
|
+
if(current){const stamp=String(Date.now());await mkdir(path.join(gone,stamp),{recursive:true});
|
|
201
|
+
for(const f of ['events.jsonl','request.json','status.json','completion.json','todos.json','checks.json'])if(existsSync(path.join(s.dir,f)))await rename(path.join(s.dir,f),path.join(gone,stamp,f))}
|
|
202
|
+
await rm(path.join(s.dir,'kimi-session.json'),{force:true});
|
|
203
|
+
s.meta.turns=s.meta.turns.slice(0,turn);await s.save();await forget(s,turn);
|
|
204
|
+
this.#bind(s);this.emit('session',s);
|
|
205
|
+
}
|
|
206
|
+
this.emit('change');
|
|
207
|
+
return {turn,files};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** A copy of a session (conversation and settings, not running state) under a new id, for --fork. */
|
|
211
|
+
static async fork(id){
|
|
212
|
+
const from=path.join(sub('sessions'),id),to=randomUUID(),dir=path.join(sub('sessions'),to);
|
|
213
|
+
await cp(from,dir,{recursive:true,filter:src=>!/(running\.lock|cancel|pending\.json|decision-[^/\\]*|steering)$/.test(src)});
|
|
214
|
+
const meta=JSON.parse(await readFile(path.join(dir,'session.json'),'utf8'));
|
|
215
|
+
Object.assign(meta,{id:to,forkedFrom:id,created:new Date().toISOString(),title:(meta.title||'Session')+' (fork)'});delete meta.cloudProject;
|
|
216
|
+
await writeFile(path.join(dir,'session.json'),JSON.stringify(meta));
|
|
217
|
+
return Session.open(to);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The command context (commands.mjs). Missing ui methods fall back to the plain terminal ones. */
|
|
221
|
+
ctx(ui={}){
|
|
222
|
+
const base=plainUi();
|
|
223
|
+
const full={...base,...ui,queue:ui.queue||(text=>this.queue(text)),setSession:async s=>{await this.setSession(s);await ui.setSession?.(s)},setMode:async m=>{if(modeName(m)!==this.mode)await this.setMode(m);ui.setMode?.(m)}};
|
|
224
|
+
const self=this;
|
|
225
|
+
return {
|
|
226
|
+
get session(){return self.session},get settings(){return self.settings},set settings(v){if(v)self.settings=v},ui:full,out:t=>full.print(t),server:this.cloud,chat:this,
|
|
227
|
+
exec:(command,{cwd=self.session.meta.root}={})=>new Promise(r=>{import('node:child_process').then(({exec})=>exec(command,{cwd,maxBuffer:8*1024*1024},(e,stdout,stderr)=>r({code:e?(e.code??1):0,stdout,stderr})))}),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
}
|