mlai-code 0.0.0-stage → 0.3.0
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,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The input box's text model: a multi-line buffer with a cursor, emacs-style keys, history with Up/Down,
|
|
3
|
+
* Ctrl-R reverse search, and an optional vim mode (normal/insert). Pure state, no terminal I/O, so it is
|
|
4
|
+
* unit-tested directly. handle(key) returns an action string for the app or null:
|
|
5
|
+
* 'submit' Enter on a line that does not end with a backslash
|
|
6
|
+
* 'changed' the text or cursor moved
|
|
7
|
+
* null the key is not the editor's (the app may use it)
|
|
8
|
+
*/
|
|
9
|
+
import {readFile,writeFile,mkdir} from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
const isWord=ch=>/[\p{L}\p{N}_]/u.test(ch||'');
|
|
13
|
+
export class Editor{
|
|
14
|
+
constructor({history=[],vim=false}={}){
|
|
15
|
+
this.text='';this.cursor=0;this.history=history.slice(-500);this.hIndex=this.history.length;this.draft='';
|
|
16
|
+
this.vim=vim;this.vimMode='insert';this.pendingOp='';this.search=null;this.yank='';
|
|
17
|
+
}
|
|
18
|
+
set(text,cursor=String(text).length){this.text=String(text);this.cursor=Math.max(0,Math.min(this.text.length,cursor));return 'changed'}
|
|
19
|
+
clear(){this.text='';this.cursor=0;this.hIndex=this.history.length;this.draft='';if(this.vim)this.vimMode='insert';return 'changed'}
|
|
20
|
+
insert(s){s=String(s);this.text=this.text.slice(0,this.cursor)+s+this.text.slice(this.cursor);this.cursor+=s.length;return 'changed'}
|
|
21
|
+
/** Line and column of the cursor (columns in UTF-16 units of that line). */
|
|
22
|
+
pos(){const before=this.text.slice(0,this.cursor);const row=before.split('\n').length-1;return {row,col:this.cursor-(before.lastIndexOf('\n')+1)}}
|
|
23
|
+
lines(){return this.text.split('\n')}
|
|
24
|
+
lineStart(i=this.cursor){return this.text.lastIndexOf('\n',i-1)+1}
|
|
25
|
+
lineEnd(i=this.cursor){const e=this.text.indexOf('\n',i);return e<0?this.text.length:e}
|
|
26
|
+
move(to){this.cursor=Math.max(0,Math.min(this.text.length,to));return 'changed'}
|
|
27
|
+
left(){if(this.cursor>0){const cp=this.text.codePointAt(this.cursor-2);this.cursor-=cp>0xffff?2:1}return 'changed'}
|
|
28
|
+
right(){if(this.cursor<this.text.length){const cp=this.text.codePointAt(this.cursor);this.cursor+=cp>0xffff?2:1}return 'changed'}
|
|
29
|
+
wordLeft(){let i=this.cursor;while(i>0&&!isWord(this.text[i-1]))i--;while(i>0&&isWord(this.text[i-1]))i--;return this.move(i)}
|
|
30
|
+
wordRight(){let i=this.cursor;while(i<this.text.length&&!isWord(this.text[i]))i++;while(i<this.text.length&&isWord(this.text[i]))i++;return this.move(i)}
|
|
31
|
+
/** Up/Down move between lines; at the first or last line they walk the history instead. */
|
|
32
|
+
vertical(d){
|
|
33
|
+
const {row,col}=this.pos(),lines=this.lines();
|
|
34
|
+
if((d<0&&row===0)||(d>0&&row===lines.length-1))return this.historyStep(d);
|
|
35
|
+
const target=row+d;let i=0;for(let r=0;r<target;r++)i+=lines[r].length+1;
|
|
36
|
+
return this.move(i+Math.min(col,lines[target].length));
|
|
37
|
+
}
|
|
38
|
+
historyStep(d){
|
|
39
|
+
if(!this.history.length)return null;
|
|
40
|
+
if(this.hIndex===this.history.length)this.draft=this.text;
|
|
41
|
+
const next=Math.max(0,Math.min(this.history.length,this.hIndex+d));
|
|
42
|
+
if(next===this.hIndex)return null;
|
|
43
|
+
this.hIndex=next;this.text=next===this.history.length?this.draft:this.history[next];
|
|
44
|
+
this.cursor=d<0?Math.min(this.text.length,this.lineEnd(0)):this.text.length;return 'changed';
|
|
45
|
+
}
|
|
46
|
+
backspace(){
|
|
47
|
+
if(this.cursor===0)return 'changed';
|
|
48
|
+
const cp=this.text.codePointAt(this.cursor-2),n=cp>0xffff?2:1;
|
|
49
|
+
this.text=this.text.slice(0,this.cursor-n)+this.text.slice(this.cursor);this.cursor-=n;return 'changed';
|
|
50
|
+
}
|
|
51
|
+
del(){if(this.cursor<this.text.length){const cp=this.text.codePointAt(this.cursor),n=cp>0xffff?2:1;this.text=this.text.slice(0,this.cursor)+this.text.slice(this.cursor+n)}return 'changed'}
|
|
52
|
+
kill(from,to){const a=Math.min(from,to),b=Math.max(from,to);this.yank=this.text.slice(a,b);this.text=this.text.slice(0,a)+this.text.slice(b);this.cursor=a;return 'changed'}
|
|
53
|
+
/** Adds a submitted entry to history (no duplicates in a row, no blanks). */
|
|
54
|
+
remember(entry){
|
|
55
|
+
const e=String(entry);if(e.trim()&&this.history.at(-1)!==e)this.history.push(e);
|
|
56
|
+
if(this.history.length>500)this.history.splice(0,this.history.length-500);
|
|
57
|
+
this.hIndex=this.history.length;this.draft='';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Ctrl-R: incremental reverse search through history.
|
|
61
|
+
startSearch(){this.search={query:'',index:this.history.length,saved:this.text,match:null};return 'changed'}
|
|
62
|
+
searchUpdate(step=false){
|
|
63
|
+
const s=this.search,q=s.query.toLowerCase();
|
|
64
|
+
if(!q){s.match=null;return 'changed'}
|
|
65
|
+
for(let i=(step?s.index:this.history.length)-1;i>=0;i--)if(this.history[i].toLowerCase().includes(q)){s.index=i;s.match=this.history[i];return 'changed'}
|
|
66
|
+
if(!step)s.match=null;return 'changed';
|
|
67
|
+
}
|
|
68
|
+
searchKey(k){
|
|
69
|
+
const s=this.search;
|
|
70
|
+
if(k.name==='r'&&k.ctrl)return this.searchUpdate(true);
|
|
71
|
+
if(k.name==='escape'||(k.ctrl&&(k.name==='g'||k.name==='c'))){this.text=s.saved;this.cursor=this.text.length;this.search=null;return 'changed'}
|
|
72
|
+
if(k.name==='backspace'){s.query=s.query.slice(0,-1);return this.searchUpdate()}
|
|
73
|
+
if(k.name==='char'){s.query+=k.ch;return this.searchUpdate()}
|
|
74
|
+
if(k.name==='paste'){s.query+=k.text.replace(/\n/g,' ');return this.searchUpdate()}
|
|
75
|
+
// Any other key accepts the match and is handled normally (Enter submits it).
|
|
76
|
+
const m=s.match;this.search=null;if(m!=null){this.text=m;this.cursor=m.length}
|
|
77
|
+
return k.name==='enter'?(m!=null?this.handle(k):'changed'):this.handle(k);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
handle(k){
|
|
81
|
+
if(this.search)return this.searchKey(k);
|
|
82
|
+
if(this.vim&&this.vimMode==='normal')return this.normalKey(k);
|
|
83
|
+
if(k.name==='paste')return this.insert(k.text);
|
|
84
|
+
if(k.name==='enter'){
|
|
85
|
+
// Shift+Enter, Alt+Enter, or a trailing backslash add a line; Enter alone submits.
|
|
86
|
+
if(k.shift||k.alt||k.ctrl)return this.insert('\n');
|
|
87
|
+
if(this.text.slice(0,this.cursor).endsWith('\\')&&this.cursor===this.lineEnd()){this.text=this.text.slice(0,this.cursor-1)+this.text.slice(this.cursor);this.cursor--;return this.insert('\n')}
|
|
88
|
+
return 'submit';
|
|
89
|
+
}
|
|
90
|
+
if(k.ctrl&&k.name==='j')return this.insert('\n');
|
|
91
|
+
if(k.name==='escape'&&this.vim){this.vimMode='normal';if(this.cursor>this.lineStart())this.left();return 'changed'}
|
|
92
|
+
if(k.name==='char')return this.insert(k.ch);
|
|
93
|
+
if(k.name==='backspace')return k.alt||k.ctrl?this.kill(this.cursor,(this.wordLeft(),this.cursor)):this.backspace();
|
|
94
|
+
if(k.name==='delete')return this.del();
|
|
95
|
+
if(k.name==='left')return k.ctrl||k.alt?this.wordLeft():this.left();
|
|
96
|
+
if(k.name==='right')return k.ctrl||k.alt?this.wordRight():this.right();
|
|
97
|
+
if(k.name==='up')return this.vertical(-1);
|
|
98
|
+
if(k.name==='down')return this.vertical(1);
|
|
99
|
+
if(k.name==='home')return this.move(this.lineStart());
|
|
100
|
+
if(k.name==='end')return this.move(this.lineEnd());
|
|
101
|
+
if(k.alt&&k.name==='b')return this.wordLeft();
|
|
102
|
+
if(k.alt&&k.name==='f')return this.wordRight();
|
|
103
|
+
if(k.alt&&k.name==='d'){const a=this.cursor;this.wordRight();return this.kill(a,this.cursor)}
|
|
104
|
+
if(k.ctrl)switch(k.name){
|
|
105
|
+
case 'a':return this.move(this.lineStart());
|
|
106
|
+
case 'e':return this.move(this.lineEnd());
|
|
107
|
+
case 'b':return this.left();
|
|
108
|
+
case 'f':return this.right();
|
|
109
|
+
case 'u':return this.kill(this.lineStart(),this.cursor);
|
|
110
|
+
case 'k':return this.kill(this.cursor,this.lineEnd()===this.cursor&&this.cursor<this.text.length?this.cursor+1:this.lineEnd());
|
|
111
|
+
case 'w':{const a=this.cursor;this.wordLeft();return this.kill(this.cursor,a)}
|
|
112
|
+
case 'y':return this.yank?this.insert(this.yank):'changed';
|
|
113
|
+
case 'h':return this.backspace();
|
|
114
|
+
case 'd':return this.text?this.del():null;
|
|
115
|
+
case 'p':return this.vertical(-1);
|
|
116
|
+
case 'n':return this.vertical(1);
|
|
117
|
+
case 'r':return this.history.length?this.startSearch():null;
|
|
118
|
+
}
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Vim normal mode: motions h j k l w b e 0 ^ $ gg G, edits x X dd D C cc cw dw yy p P u-less, inserts i a I A o O. */
|
|
123
|
+
normalKey(k){
|
|
124
|
+
if(k.name==='enter')return 'submit';
|
|
125
|
+
if(k.name==='escape'){this.pendingOp='';return 'changed'}
|
|
126
|
+
if(k.name==='paste'){this.vimMode='insert';return this.insert(k.text)}
|
|
127
|
+
const arrows={left:'h',right:'l',up:'k',down:'j'};
|
|
128
|
+
const ch=k.name==='char'?k.ch:arrows[k.name]||(k.ctrl&&k.name==='r'?null:null);
|
|
129
|
+
if(k.ctrl&&k.name==='r')return this.startSearch();
|
|
130
|
+
if(!ch)return k.name==='backspace'?this.left():null;
|
|
131
|
+
const op=this.pendingOp;
|
|
132
|
+
const motion=c=>{
|
|
133
|
+
const ls=this.lineStart(),le=this.lineEnd();
|
|
134
|
+
switch(c){
|
|
135
|
+
case 'h':return Math.max(ls,this.cursor-1);
|
|
136
|
+
case 'l':return Math.min(Math.max(ls,le-(op?0:1)),this.cursor+1);
|
|
137
|
+
case 'w':{let i=this.cursor;const w=isWord(this.text[i]);while(i<this.text.length&&this.text[i]!=='\n'&&isWord(this.text[i])===w&&this.text[i]!==' ')i++;while(i<this.text.length&&this.text[i]===' ')i++;return i}
|
|
138
|
+
case 'e':{let i=this.cursor+1;while(i<this.text.length&&!isWord(this.text[i]))i++;while(i+1<this.text.length&&isWord(this.text[i+1]))i++;return Math.min(this.text.length,i+(op?1:0))}
|
|
139
|
+
case 'b':{let i=this.cursor;while(i>0&&!isWord(this.text[i-1]))i--;while(i>0&&isWord(this.text[i-1]))i--;return i}
|
|
140
|
+
case '0':return ls;
|
|
141
|
+
case '^':{let i=ls;while(i<le&&/\s/.test(this.text[i]))i++;return i}
|
|
142
|
+
case '$':return op?le:Math.max(ls,le-1);
|
|
143
|
+
case 'G':return this.text.length;
|
|
144
|
+
default:return null;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
if(op==='g'){this.pendingOp='';return ch==='g'?this.move(0):'changed'}
|
|
148
|
+
if(op==='d'||op==='c'||op==='y'){
|
|
149
|
+
this.pendingOp='';
|
|
150
|
+
if(ch===op){const a=this.lineStart(),b=this.lineEnd();
|
|
151
|
+
if(op==='y'){this.yank=this.text.slice(a,b)+'\n';return 'changed'}
|
|
152
|
+
if(op==='c'){this.kill(a,b);this.vimMode='insert';return 'changed'}
|
|
153
|
+
const end=b<this.text.length?b+1:b,start=b>=this.text.length&&a>0?a-1:a;this.kill(start,end);this.yank=this.yank.replace(/^\n/,'')+(this.yank.endsWith('\n')?'':'\n');return 'changed';
|
|
154
|
+
}
|
|
155
|
+
const to=motion(ch==='w'&&op==='c'?'e':ch);if(to==null)return 'changed';
|
|
156
|
+
if(op==='y'){this.yank=this.text.slice(Math.min(this.cursor,to),Math.max(this.cursor,to));return 'changed'}
|
|
157
|
+
this.kill(this.cursor,to);if(op==='c')this.vimMode='insert';return 'changed';
|
|
158
|
+
}
|
|
159
|
+
const to=motion(ch);
|
|
160
|
+
if(to!=null)return this.move(to);
|
|
161
|
+
switch(ch){
|
|
162
|
+
case 'j':return this.vertical(1);
|
|
163
|
+
case 'k':return this.vertical(-1);
|
|
164
|
+
case 'i':this.vimMode='insert';return 'changed';
|
|
165
|
+
case 'a':this.vimMode='insert';if(this.cursor<this.lineEnd())this.right();return 'changed';
|
|
166
|
+
case 'I':this.vimMode='insert';return this.move(this.lineStart());
|
|
167
|
+
case 'A':this.vimMode='insert';return this.move(this.lineEnd());
|
|
168
|
+
case 'o':this.vimMode='insert';this.move(this.lineEnd());return this.insert('\n');
|
|
169
|
+
case 'O':this.vimMode='insert';this.move(this.lineStart());this.insert('\n');return this.left();
|
|
170
|
+
case 'x':return this.cursor<this.lineEnd()?this.kill(this.cursor,this.cursor+1):'changed';
|
|
171
|
+
case 'X':return this.cursor>this.lineStart()?this.kill(this.cursor-1,this.cursor):'changed';
|
|
172
|
+
case 'D':return this.kill(this.cursor,this.lineEnd());
|
|
173
|
+
case 'C':this.kill(this.cursor,this.lineEnd());this.vimMode='insert';return 'changed';
|
|
174
|
+
case 'p':{if(!this.yank)return 'changed';if(this.yank.endsWith('\n')){this.move(this.lineEnd());this.insert('\n'+this.yank.slice(0,-1));return this.move(this.lineStart())}if(this.cursor<this.lineEnd())this.right();this.insert(this.yank);return this.left()}
|
|
175
|
+
case 'P':{if(!this.yank)return 'changed';if(this.yank.endsWith('\n')){this.move(this.lineStart());this.insert(this.yank);this.left();return this.move(this.lineStart())}this.insert(this.yank);return this.left()}
|
|
176
|
+
case 'd':case 'c':case 'y':case 'g':this.pendingOp=ch;return 'changed';
|
|
177
|
+
}
|
|
178
|
+
return 'changed';
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** History file: one JSON string per line, newest last, shared by every session on this machine. */
|
|
183
|
+
export async function loadHistory(file){
|
|
184
|
+
const text=await readFile(file,'utf8').catch(()=>'');
|
|
185
|
+
return text.split('\n').flatMap(l=>{try{const v=JSON.parse(l);return typeof v==='string'?[v]:[]}catch{return []}}).slice(-500);
|
|
186
|
+
}
|
|
187
|
+
export async function saveHistory(file,history){
|
|
188
|
+
await mkdir(path.dirname(file),{recursive:true}).catch(()=>{});
|
|
189
|
+
await writeFile(file,history.slice(-500).map(h=>JSON.stringify(h)).join('\n')+'\n',{mode:0o600}).catch(()=>{});
|
|
190
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-wide state set by the command line for this run (CLI wave 2, section 3). cli.mjs parses the flags into it
|
|
3
|
+
* (src/cli-ext.mjs); the per-turn extension builder (tui/extensions-local.mjs) and the MCP list read it. Kept in its
|
|
4
|
+
* own module so neither side imports cli.mjs.
|
|
5
|
+
* mcpConfigs [{id, servers}] from --mcp-config (a file path or inline JSON)
|
|
6
|
+
* strictMcp true with --strict-mcp-config: only the --mcp-config servers are used
|
|
7
|
+
* pluginDirs absolute folders from --plugin-dir (and checked-out --plugin-url repositories)
|
|
8
|
+
* pluginUrls repository URLs from --plugin-url, fetched once at startup
|
|
9
|
+
* agents custom subagents from --agents JSON ({name: {description, prompt, tools}})
|
|
10
|
+
* plugins [{id, name, dir, hooks, warnings}] read from pluginDirs (plugins-local.mjs loadPlugins)
|
|
11
|
+
* pluginServers [{id, servers}] MCP servers those plugins add (mcp-config.mjs)
|
|
12
|
+
* preset the --preset name applied at startup
|
|
13
|
+
*/
|
|
14
|
+
export const extState={mcpConfigs:[],strictMcp:false,pluginDirs:[],pluginUrls:[],agents:null,preset:null,plugins:[],pluginServers:[]};
|
|
15
|
+
/** For tests: back to the defaults. */
|
|
16
|
+
export function resetExtState(){Object.assign(extState,{mcpConfigs:[],strictMcp:false,pluginDirs:[],pluginUrls:[],agents:null,preset:null,plugins:[],pluginServers:[]})}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What this computer adds to a CLI run's request.extensions (merged in Session.send, enforced by the engine):
|
|
3
|
+
* permissions {allow, deny, ask, bypass} worker/mlai_permissions.py
|
|
4
|
+
* hooks hooks from the settings files (source "local") worker/mlai_hooks.py
|
|
5
|
+
* localRepoHooks true when the user trusted the repository's .mlai/hooks.json (/hooks trust)
|
|
6
|
+
* network {enabled:false} when /sandbox network off (enforced at the OS level where possible: src/netbox.mjs)
|
|
7
|
+
* restricted {enabled:true} in restricted mode (src/restricted.mjs)
|
|
8
|
+
* mcpServers the user's MCP servers (worker/mcp_local.py); mcpEnv carries their ${VAR} values separately
|
|
9
|
+
* skills SKILL.md folders (skills-local.mjs) -> worker/skill_library.py
|
|
10
|
+
* agents custom subagents (agents-local.mjs) -> worker/subagents.py
|
|
11
|
+
* memory {text, files} the opt-in project memory (/memories) -> worker/project_rules.py memory_note
|
|
12
|
+
* Plugins from --plugin-dir / --plugin-url add hooks, skills, agents and MCP servers (plugins-local.mjs).
|
|
13
|
+
* The lead's chat controller calls localExtensions({root, settings, skipPermissions}) once per turn.
|
|
14
|
+
*/
|
|
15
|
+
import {readFileSync} from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import {scopedRules,isTrusted,readLayer} from './permissions.mjs';
|
|
18
|
+
import {engineServers} from './mcp-config.mjs';
|
|
19
|
+
import {loadSettings} from '../settings.mjs';
|
|
20
|
+
import {home} from '../home.mjs';
|
|
21
|
+
import {extState} from './ext-state.mjs';
|
|
22
|
+
import {discoverSkills,engineSkills} from './skills-local.mjs';
|
|
23
|
+
import {discoverAgents,engineAgents} from './agents-local.mjs';
|
|
24
|
+
import {refreshDue} from './mcp-oauth.mjs';
|
|
25
|
+
import {restrictExtensions} from '../restricted.mjs';
|
|
26
|
+
|
|
27
|
+
const isObj=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
|
|
28
|
+
export const HOOK_EVENTS=['before_tool','after_tool','before_command','after_edit','run_end','approval'];
|
|
29
|
+
/** Event names other tools use. Events without an equivalent here are reported, not guessed. */
|
|
30
|
+
export const EVENT_ALIASES={PreToolUse:'before_tool',PostToolUse:'after_tool',Stop:'run_end',PermissionRequest:'approval',beforeShellExecution:'before_command',afterFileEdit:'after_edit',stop:'run_end'};
|
|
31
|
+
const TOOL_ALIASES={Bash:'shell',Edit:'edit',Write:'edit',MultiEdit:'edit',NotebookEdit:'edit',Read:'read',Grep:'read',Glob:'read',LS:'read',WebFetch:'web',WebSearch:'web',Task:'agent',Agent:'agent'};
|
|
32
|
+
const matcherFor=(m)=>m==null||m===''||m==='*'?'':String(m).split('|').map(t=>TOOL_ALIASES[t.trim()]||t.trim()).filter(Boolean).join('|');
|
|
33
|
+
/**
|
|
34
|
+
* settings.hooks ({event: [entry]}) -> engine hooks. An entry is {matcher, command, timeout?, blocking?, name?}, or the
|
|
35
|
+
* nested form {matcher, hooks:[{type:'command', command, timeout}]}. Returns {hooks, warnings}.
|
|
36
|
+
*/
|
|
37
|
+
export function hooksFromSettings(hooks,{source='local'}={}){
|
|
38
|
+
const out=[],warnings=[];
|
|
39
|
+
if(!isObj(hooks))return {hooks:out,warnings};
|
|
40
|
+
for(const [rawEvent,entries] of Object.entries(hooks)){
|
|
41
|
+
const event=HOOK_EVENTS.includes(rawEvent)?rawEvent:EVENT_ALIASES[rawEvent];
|
|
42
|
+
if(!event){warnings.push('Hook event "'+rawEvent+'" is not supported here (use one of '+HOOK_EVENTS.join(', ')+').');continue}
|
|
43
|
+
for(const e of Array.isArray(entries)?entries:[]){
|
|
44
|
+
if(!isObj(e))continue;
|
|
45
|
+
const inner=Array.isArray(e.hooks)?e.hooks:[e];
|
|
46
|
+
for(const h of inner){
|
|
47
|
+
if(!isObj(h))continue;
|
|
48
|
+
const type=h.type==='webhook'||h.url?'webhook':'command';
|
|
49
|
+
if(type==='command'&&!(typeof h.command==='string'&&h.command.trim())){warnings.push('A '+rawEvent+' hook has no command.');continue}
|
|
50
|
+
out.push({name:String(h.name||e.name||(rawEvent+' hook')).slice(0,80),event,type,matcher:matcherFor(e.matcher??h.matcher),
|
|
51
|
+
...(type==='command'?{command:h.command}:{url:h.url,...(h.secret?{secret:h.secret}:{})}),
|
|
52
|
+
...(h.timeout?{timeout:Number(h.timeout)}:{}),...(h.blocking===false||e.blocking===false?{blocking:false}:{}),...(h.onError==='block'?{onError:'block'}:{}),source});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return {hooks:out.slice(0,40),warnings};
|
|
57
|
+
}
|
|
58
|
+
export function repoHooksText(root){
|
|
59
|
+
if(!root)return null;try{return readFileSync(path.join(root,'.mlai','hooks.json'),'utf8').slice(0,100001)}catch{return null}
|
|
60
|
+
}
|
|
61
|
+
/** {user, project, local} hooks from the settings files, and whether the project's own hooks are trusted. */
|
|
62
|
+
export function scopedHooks(root){
|
|
63
|
+
const by={};for(const s of ['user','project','local'])by[s]=readLayer(root,s).hooks;
|
|
64
|
+
const projectHooks=by.project&&Object.keys(by.project).length?by.project:null;
|
|
65
|
+
const file=repoHooksText(root);
|
|
66
|
+
return {by,projectTrusted:!projectHooks||isTrusted(root,'hooks',projectHooks),file,fileTrusted:file!=null&&isTrusted(root,'hooksFile',file)};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function localExtensions({root,settings=null,skipPermissions=false,restricted=false,env=process.env}={}){
|
|
70
|
+
const warnings=[];
|
|
71
|
+
if(typeof extState.ready==='function')await extState.ready().catch(e=>warnings.push(String(e?.message||e)));// --plugin-url checkouts (a failure is reported at startup)
|
|
72
|
+
const rules=scopedRules(root).effective;
|
|
73
|
+
const sh=scopedHooks(root);
|
|
74
|
+
const hooks=[];
|
|
75
|
+
// Restricted mode (src/restricted.mjs) runs no local hooks: any settings file could otherwise start a program.
|
|
76
|
+
if(!restricted)for(const s of ['user','local',...(sh.projectTrusted?['project']:[])]){const r=hooksFromSettings(sh.by[s]);hooks.push(...r.hooks);warnings.push(...r.warnings)}
|
|
77
|
+
if(!restricted&&!sh.projectTrusted)warnings.push('Hooks in .mlai/settings.json are not trusted yet; /hooks trust turns them on.');
|
|
78
|
+
if(!restricted)for(const p of extState.plugins)hooks.push(...p.hooks);// plugin hooks are local programs too
|
|
79
|
+
await refreshDue().catch(()=>{});// MCP sign-ins about to expire
|
|
80
|
+
const mcp=engineServers(root,{env});
|
|
81
|
+
for(const s of mcp.skipped)warnings.push('MCP server '+s.name+' skipped: '+s.reason+'.');
|
|
82
|
+
// Read from disk each turn: /sandbox may have changed a file since `settings` was loaded.
|
|
83
|
+
let fresh=null;try{fresh=loadSettings({root})}catch{}
|
|
84
|
+
const sandbox=isObj(fresh?.sandbox)?fresh.sandbox:isObj(settings?.sandbox)?settings.sandbox:{};
|
|
85
|
+
const cur=fresh||settings||{};
|
|
86
|
+
const skills=engineSkills(discoverSkills(root,{pluginDirs:extState.pluginDirs,disabled:Array.isArray(cur.skills?.disabled)?cur.skills.disabled:[]}));
|
|
87
|
+
const agents=engineAgents(discoverAgents(root,{flagAgents:extState.agents||[],pluginDirs:extState.pluginDirs}));
|
|
88
|
+
const memory=cur.memories===true?readMemory(root):null;
|
|
89
|
+
const ext={
|
|
90
|
+
permissions:{...rules,...(skipPermissions?{bypass:true}:{})},
|
|
91
|
+
...(hooks.length?{hooks}:{}),
|
|
92
|
+
...(sh.fileTrusted?{localRepoHooks:true}:{}),
|
|
93
|
+
...(sandbox.network===false?{network:{enabled:false}}:{}),
|
|
94
|
+
...(Object.keys(mcp.mcpServers).length?{mcpServers:mcp.mcpServers}:{}),
|
|
95
|
+
...(Object.keys(mcp.mcpEnv).length?{mcpEnv:mcp.mcpEnv}:{}),
|
|
96
|
+
...(sandbox.enabled===false?{sandbox:{enabled:false}}:{}),
|
|
97
|
+
// Auto mode's reviewer pass (worker/mlai_auto_review.py); the engine ignores it in other modes.
|
|
98
|
+
autoReview:{enabled:(fresh??settings)?.autoReview!==false&&!skipPermissions,...(((fresh??settings)?.reviewModel)?{model:(fresh??settings).reviewModel}:{})},
|
|
99
|
+
...(skills.length?{skills}:{}),
|
|
100
|
+
...(agents.length?{agents}:{}),
|
|
101
|
+
...(memory?{memory}:{}),
|
|
102
|
+
};
|
|
103
|
+
Object.defineProperty(ext,'warnings',{value:warnings});
|
|
104
|
+
return restricted?restrictExtensions(ext):ext;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Merges local extensions into the server-built request.extensions (Session.send). Server hooks and deny rules stay;
|
|
109
|
+
* local lists are added. mcpEnv and sandbox are returned separately: they never go into request.json.
|
|
110
|
+
*/
|
|
111
|
+
export function mergeExtensions(server,local){
|
|
112
|
+
const base=isObj(server)?{...server}:{};
|
|
113
|
+
if(!isObj(local))return {extensions:base,mcpEnv:null,sandbox:null};
|
|
114
|
+
const {mcpEnv=null,sandbox=null,hooks,permissions,skills,agents,...rest}=local;
|
|
115
|
+
const out={...base,...rest};
|
|
116
|
+
// Skills and agents add up; a local one replaces the account's entry with the same id or name.
|
|
117
|
+
if(Array.isArray(skills)&&skills.length){const ids=new Set(skills.map(x=>x.id));out.skills=[...(Array.isArray(base.skills)?base.skills.filter(x=>!ids.has(x?.id)):[]),...skills]}
|
|
118
|
+
if(Array.isArray(agents)&&agents.length){const ids=new Set(agents.map(x=>x.name));out.agents=[...(Array.isArray(base.agents)?base.agents.filter(x=>!ids.has(x?.name)):[]),...agents]}
|
|
119
|
+
if(Array.isArray(hooks)&&hooks.length)out.hooks=[...(Array.isArray(base.hooks)?base.hooks:[]),...hooks];
|
|
120
|
+
if(isObj(permissions)){
|
|
121
|
+
const cur=isObj(base.permissions)?base.permissions:{};
|
|
122
|
+
out.permissions={...cur,...(permissions.bypass?{bypass:true}:{})};
|
|
123
|
+
for(const k of ['allow','deny','ask'])out.permissions[k]=[...new Set([...(Array.isArray(cur[k])?cur[k]:[]),...(Array.isArray(permissions[k])?permissions[k]:[])])];
|
|
124
|
+
}
|
|
125
|
+
if(base.localRepoHooks===true)out.localRepoHooks=true;
|
|
126
|
+
if(isObj(base.network)&&base.network.enabled===false)out.network=base.network;
|
|
127
|
+
if(isObj(base.mcpServers)||isObj(rest.mcpServers))out.mcpServers={...(isObj(base.mcpServers)?base.mcpServers:{}),...(isObj(rest.mcpServers)?rest.mcpServers:{})};
|
|
128
|
+
return {extensions:out,mcpEnv:isObj(mcpEnv)&&Object.keys(mcpEnv).length?mcpEnv:null,sandbox:isObj(sandbox)?sandbox:null};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Project memory files (/memories): <repo>/.mlai/MEMORY.md, then ~/.mlai/MEMORY.md. Only sent when memories is on. */
|
|
132
|
+
export function memoryFiles(root){return [...(root?[{label:'.mlai/MEMORY.md',file:path.join(root,'.mlai','MEMORY.md'),scope:'project'}]:[]),{label:'~/.mlai/MEMORY.md',file:path.join(home(),'MEMORY.md'),scope:'user'}]}
|
|
133
|
+
export function readMemory(root,limit=20000){
|
|
134
|
+
const parts=[],files=[];let left=limit;
|
|
135
|
+
for(const m of memoryFiles(root)){
|
|
136
|
+
let t='';try{t=readFileSync(m.file,'utf8').trim()}catch{continue}
|
|
137
|
+
if(!t||left<=0)continue;t=t.slice(0,left);left-=t.length;parts.push('# '+m.label+'\n'+t);files.push(m.label);
|
|
138
|
+
}
|
|
139
|
+
return parts.length?{text:parts.join('\n\n'),files}:null;
|
|
140
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The @ picker's file list (git ls-files, or a bounded folder walk outside git), fuzzy ranking for paths, the @token
|
|
3
|
+
* under the cursor, and dropped image paths (terminals paste a dragged file as its path, sometimes quoted or escaped).
|
|
4
|
+
*/
|
|
5
|
+
import {execFile} from 'node:child_process';
|
|
6
|
+
import {readdir,stat} from 'node:fs/promises';
|
|
7
|
+
import {existsSync,statSync} from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import {fuzzy} from './commands.mjs';
|
|
11
|
+
|
|
12
|
+
const SKIP=new Set(['.git','node_modules','.next','dist','build','.venv','venv','__pycache__','.cache','target','.turbo','coverage','.mlai']);
|
|
13
|
+
const cache=new Map();
|
|
14
|
+
function git(args,cwd){return new Promise(r=>execFile('git',args,{cwd,maxBuffer:64*1024*1024,windowsHide:true},(e,out)=>r(e?null:out)))}
|
|
15
|
+
async function walk(root,limit=20000){
|
|
16
|
+
const out=[];const queue=[''];
|
|
17
|
+
while(queue.length&&out.length<limit){
|
|
18
|
+
const rel=queue.shift();let ents=[];try{ents=await readdir(path.join(root,rel),{withFileTypes:true})}catch{continue}
|
|
19
|
+
for(const e of ents){
|
|
20
|
+
if(e.name.startsWith('.')&&e.name!=='.github'&&e.name!=='.mlai')continue;
|
|
21
|
+
const p=rel?rel+'/'+e.name:e.name;
|
|
22
|
+
if(e.isDirectory()){if(!SKIP.has(e.name))queue.push(p)}else if(e.isFile())out.push(p);
|
|
23
|
+
if(out.length>=limit)break;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
/** Files and folders of the project, folders with a trailing slash. Cached for a few seconds. */
|
|
29
|
+
export async function projectEntries(root,{ttl=5000}={}){
|
|
30
|
+
const hit=cache.get(root);if(hit&&Date.now()-hit.at<ttl)return hit.entries;
|
|
31
|
+
const listed=await git(['ls-files','-co','--exclude-standard','-z'],root);
|
|
32
|
+
const files=listed!=null?listed.split('\0').filter(Boolean).filter(f=>!f.split('/').some(s=>SKIP.has(s))):await walk(root);
|
|
33
|
+
const dirs=new Set();for(const f of files){const parts=f.split('/');for(let i=1;i<parts.length;i++)dirs.add(parts.slice(0,i).join('/')+'/')}
|
|
34
|
+
const entries=[...[...dirs].sort(),...files.sort()];
|
|
35
|
+
cache.set(root,{at:Date.now(),entries});
|
|
36
|
+
return entries;
|
|
37
|
+
}
|
|
38
|
+
export function clearEntries(){cache.clear()}
|
|
39
|
+
/** Path ranking: a match in the file name beats one spread over the folders; shorter paths win ties. */
|
|
40
|
+
export function rankPaths(entries,query,limit=50){
|
|
41
|
+
const q=String(query||'');
|
|
42
|
+
if(!q)return entries.filter(e=>!e.slice(0,-1).includes('/')).slice(0,limit);
|
|
43
|
+
const rows=[];
|
|
44
|
+
for(const e of entries){
|
|
45
|
+
const base=e.replace(/\/$/,'').split('/').pop();
|
|
46
|
+
const sb=fuzzy(q,base),sp=fuzzy(q,e);
|
|
47
|
+
if(sb==null&&sp==null)continue;
|
|
48
|
+
rows.push({e,s:Math.max(sb==null?-Infinity:sb+50,sp??-Infinity)-e.length*0.05});
|
|
49
|
+
}
|
|
50
|
+
return rows.sort((a,b)=>b.s-a.s||a.e.localeCompare(b.e)).slice(0,limit).map(r=>r.e);
|
|
51
|
+
}
|
|
52
|
+
/** The @token ending at the cursor: {start, query} or null. An email address (a@b) does not count. */
|
|
53
|
+
export function atToken(text,cursor){
|
|
54
|
+
const before=text.slice(0,cursor);const m=/(^|[\s(])@([^\s@]*)$/.exec(before);
|
|
55
|
+
if(!m)return null;
|
|
56
|
+
return {start:before.length-m[2].length-1,query:m[2]};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const IMAGE_EXT=/\.(png|jpe?g|webp|gif)$/i;
|
|
60
|
+
/** A pasted string that is the path of an existing image file (drag and drop): the resolved path, else null. */
|
|
61
|
+
export function droppedImage(text,cwd=process.cwd()){
|
|
62
|
+
let s=String(text||'').trim();
|
|
63
|
+
if(!s||s.includes('\n')||s.length>1024)return null;
|
|
64
|
+
if(/^file:\/\//.test(s))try{s=decodeURIComponent(new URL(s).pathname);if(process.platform==='win32')s=s.replace(/^\/([A-Za-z]:)/,'$1')}catch{return null}
|
|
65
|
+
if((s.startsWith("'")&&s.endsWith("'"))||(s.startsWith('"')&&s.endsWith('"')))s=s.slice(1,-1);
|
|
66
|
+
else s=s.replace(/\\([ ()'&\[\]])/g,'$1');
|
|
67
|
+
if(s.startsWith('~'))s=path.join(os.homedir(),s.slice(1));
|
|
68
|
+
if(!IMAGE_EXT.test(s))return null;
|
|
69
|
+
const p=path.resolve(cwd,s);
|
|
70
|
+
try{return statSync(p).isFile()?p:null}catch{return null}
|
|
71
|
+
}
|
|
72
|
+
export {existsSync,stat};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Cloud handoff for the CLI (`/cloud`, `&task`): push the session's work to a GitHub branch, start a cloud chat on that
|
|
2
|
+
// branch with a recap, and return its web link. Same rules as the Mac app (apps/desktop/src/handoff.cjs): a folder
|
|
3
|
+
// session is pushed as a snapshot commit on a new mlai/ branch, so the developer's files, index and branch never change.
|
|
4
|
+
import {execFile} from 'node:child_process';
|
|
5
|
+
import {mkdtemp,rm} from 'node:fs/promises';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import {randomBytes} from 'node:crypto';
|
|
9
|
+
|
|
10
|
+
export function git(cwd,args,{env,timeout=30000}={}){
|
|
11
|
+
return new Promise(resolve=>execFile('git',args,{cwd,env:env||process.env,timeout,maxBuffer:8_000_000,windowsHide:true},(err,stdout,stderr)=>resolve({code:err?(typeof err.code==='number'?err.code:1):0,stdout:String(stdout||'').trim(),stderr:String(stderr||'').trim()})));
|
|
12
|
+
}
|
|
13
|
+
async function must(cwd,args,o){const r=await git(cwd,args,o);if(r.code)throw new Error((r.stderr||r.stdout).split('\n').slice(-3).join('\n')||'git '+args[0]+' failed');return r.stdout}
|
|
14
|
+
|
|
15
|
+
/** owner/name from a GitHub remote URL (https, ssh or scp-style), else null. */
|
|
16
|
+
export function githubRepo(url){
|
|
17
|
+
const m=String(url||'').trim().match(/^(?:https:\/\/(?:[^@/\s]+@)?github\.com\/|ssh:\/\/git@github\.com(?::\d+)?\/|git@github\.com:)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/);
|
|
18
|
+
if(!m||m[1].startsWith('.')||m[2].startsWith('.'))return null;
|
|
19
|
+
return m[1]+'/'+m[2];
|
|
20
|
+
}
|
|
21
|
+
export const slug=t=>String(t||'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,40).replace(/-+$/,'')||'session';
|
|
22
|
+
|
|
23
|
+
/** A commit of everything in the folder (tracked changes and non-ignored new files), made with a temporary index. */
|
|
24
|
+
export async function snapshotCommit(dir,message){
|
|
25
|
+
const head=await must(dir,['rev-parse','--verify','HEAD^{commit}']).catch(()=>{throw new Error('This project has no commits yet. Commit once, then send it to the cloud.')});
|
|
26
|
+
const tmp=await mkdtemp(path.join(os.tmpdir(),'mlai-index-'));
|
|
27
|
+
const env={...process.env,GIT_INDEX_FILE:path.join(tmp,'index')};
|
|
28
|
+
if(!(await git(dir,['config','user.email'])).stdout&&!process.env.GIT_AUTHOR_EMAIL)Object.assign(env,{GIT_AUTHOR_NAME:'ML AI Code',GIT_AUTHOR_EMAIL:'mlai@localhost',GIT_COMMITTER_NAME:'ML AI Code',GIT_COMMITTER_EMAIL:'mlai@localhost'});
|
|
29
|
+
try{
|
|
30
|
+
await must(dir,['read-tree',head],{env});
|
|
31
|
+
await must(dir,['add','-A','--','.'],{env,timeout:120000});
|
|
32
|
+
const tree=await must(dir,['write-tree'],{env});
|
|
33
|
+
if(tree===await must(dir,['rev-parse',head+'^{tree}']))return {commit:head,changed:false};
|
|
34
|
+
return {commit:await must(dir,['-c','commit.gpgsign=false','commit-tree',tree,'-p',head,'-m',message],{env}),changed:true};
|
|
35
|
+
}finally{await rm(tmp,{recursive:true,force:true}).catch(()=>{})}
|
|
36
|
+
}
|
|
37
|
+
/** Files that differ from HEAD (at most 40), for the recap. */
|
|
38
|
+
export async function changedFiles(dir){
|
|
39
|
+
const [a,b]=await Promise.all([git(dir,['diff','--name-only','HEAD']),git(dir,['ls-files','--others','--exclude-standard'])]);
|
|
40
|
+
return [...new Set([...a.stdout.split('\n'),...b.stdout.split('\n')].filter(Boolean))].slice(0,40);
|
|
41
|
+
}
|
|
42
|
+
function pushError(r){
|
|
43
|
+
const t=(r.stderr||r.stdout).split('\n').filter(l=>!/^(hint|remote):\s*$/.test(l)).slice(-3).join('\n');
|
|
44
|
+
return 'Could not push to GitHub. '+(/denied|403|Authentication|could not read Username/i.test(t)?'Check that git can push to this repository from a terminal (sign in to GitHub there), then try again.':t||'git push failed');
|
|
45
|
+
}
|
|
46
|
+
/** Pushes the session's work: a worktree session commits and pushes its branch; a folder session pushes a snapshot. */
|
|
47
|
+
export async function pushForCloud(dir,{title,worktree,commitAll}={}){
|
|
48
|
+
const origin=(await git(dir,['config','--get','remote.origin.url'])).stdout,repo=githubRepo(origin);
|
|
49
|
+
if(!repo)throw new Error(origin?'Sending to the cloud needs a GitHub remote. This project\u2019s origin is not on github.com.':'Sending to the cloud needs a GitHub remote named origin. Add one with git remote add origin, then try again.');
|
|
50
|
+
const files=await changedFiles(dir);let branch,commit;
|
|
51
|
+
if(worktree&&!worktree.removed&&worktree.branch){
|
|
52
|
+
if(files.length&&commitAll)await commitAll();
|
|
53
|
+
branch=worktree.branch;commit=await must(dir,['rev-parse','HEAD']);
|
|
54
|
+
const r=await git(dir,['push','-u','origin',branch],{timeout:180000});if(r.code)throw new Error(pushError(r));
|
|
55
|
+
}else{
|
|
56
|
+
({commit}=await snapshotCommit(dir,'ML AI Code: '+(String(title||'').split('\n')[0].slice(0,72)||'work in progress')));
|
|
57
|
+
branch='mlai/'+slug(title)+'-'+randomBytes(2).toString('hex');
|
|
58
|
+
const r=await git(dir,['push','origin',commit+':refs/heads/'+branch],{timeout:180000});if(r.code)throw new Error(pushError(r));
|
|
59
|
+
}
|
|
60
|
+
return {repo,url:'https://github.com/'+repo,branch,commit,files};
|
|
61
|
+
}
|
|
62
|
+
const cut=(s,n)=>s.length>n?s.slice(0,n)+'\u2026':s;
|
|
63
|
+
/** The cloud chat's first task: what the session was about, where it got to, and what to do next. */
|
|
64
|
+
export function recap({title,transcript,branch,files,note}){
|
|
65
|
+
const turns=Array.isArray(transcript)?transcript:(transcript&&transcript.turns)||[];
|
|
66
|
+
const tasks=turns.map(t=>String(t.task||'').trim()).filter(Boolean);let answer='';
|
|
67
|
+
for(const t of [...turns].reverse()){const a=[...(t.events||[])].reverse().find(e=>e&&e.type==='answer'&&e.content);if(a){answer=String(a.content);break}}
|
|
68
|
+
const parts=['Continue '+(title?'"'+cut(String(title).replace(/\s+/g,' '),100)+'"':'my session')+' from my computer. The work so far is on the branch '+branch+', which is checked out here.'];
|
|
69
|
+
if(tasks.length)parts.push('What I asked for, in order:\n'+tasks.slice(-6).map((t,i)=>(i+1)+'. '+cut(t.replace(/\s+/g,' '),400)).join('\n'));
|
|
70
|
+
if(answer)parts.push('Where it got to:\n'+cut(answer,1500));
|
|
71
|
+
if(files&&files.length)parts.push('Files changed on my computer: '+files.join(', ')+'.');
|
|
72
|
+
parts.push(note&&String(note).trim()?'Next: '+cut(String(note).trim(),1500):'Next: read the recent commits on this branch, check that the work builds and its tests pass, then finish anything left from the tasks above. Tell me what you changed.');
|
|
73
|
+
return cut(parts.join('\n\n'),6000);
|
|
74
|
+
}
|
|
75
|
+
/** Cloud chats from GET /api/account (no tokens): [{name,title,repo,updated,state}], newest first. */
|
|
76
|
+
export function cloudSessions(account){
|
|
77
|
+
const runs=Array.isArray(account?.runs)?account.runs:[];
|
|
78
|
+
return (Array.isArray(account?.workspaces)?account.workspaces:[])
|
|
79
|
+
.filter(w=>w&&typeof w.name==='string'&&w.backend!=='laptop'&&!String(w.title||'').startsWith('Laptop: '))
|
|
80
|
+
.map(w=>{
|
|
81
|
+
const last=runs.filter(r=>r&&r.workspace_name===w.name).sort((a,b)=>String(b.started_at||'').localeCompare(String(a.started_at||'')))[0];
|
|
82
|
+
return {name:w.name,title:String(w.title||last?.title||w.repo||w.name).slice(0,120),repo:typeof w.repo==='string'?w.repo:'',updated:last?.started_at||w.created_at||null,state:last?String(last.state||''):'idle'};
|
|
83
|
+
})
|
|
84
|
+
.sort((a,b)=>String(b.updated||'').localeCompare(String(a.updated||''))).slice(0,30);
|
|
85
|
+
}
|
|
86
|
+
/** The web link for a cloud chat. */
|
|
87
|
+
export const chatUrl=(server,name)=>String(server||'').replace(/\/$/,'')+'/?chat='+encodeURIComponent(name);
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The whole handoff. `client` is a signed-in SDK Client (Cloud.device). Returns {name,url,repo,branch,commit}.
|
|
91
|
+
* `note` is what the cloud agent should do next (the text after /cloud or &).
|
|
92
|
+
*/
|
|
93
|
+
export async function sendToCloud(session,{client,server,note='',commitAll}={}){
|
|
94
|
+
if(!client)throw new Error('Sign in first: run mlai login.');
|
|
95
|
+
if(session.child)throw new Error('Wait for the task to finish, or stop it with Esc, before sending the session to the cloud.');
|
|
96
|
+
const m=session.meta,tree=m.worktree&&!m.worktree.removed?m.worktree:null;
|
|
97
|
+
const pushed=await pushForCloud(m.root,{title:m.title||note,worktree:tree,commitAll});
|
|
98
|
+
const task=recap({title:m.title,transcript:await session.transcript().catch(()=>null),branch:pushed.branch,files:pushed.files,note});
|
|
99
|
+
const r=await startCloud({client,server,pushed,task});
|
|
100
|
+
m.cloudHandoffs=[...(Array.isArray(m.cloudHandoffs)?m.cloudHandoffs:[]),{name:r.name,branch:pushed.branch,at:new Date().toISOString()}].slice(-10);
|
|
101
|
+
await session.save?.().catch(()=>{});
|
|
102
|
+
return r;
|
|
103
|
+
}
|
|
104
|
+
/** Creates a cloud workspace on the pushed branch and starts `task` there. Returns {name,token,url,repo,branch,commit}. */
|
|
105
|
+
export async function startCloud({client,server,pushed,task,mode='approve'}){
|
|
106
|
+
const ws=await client.request('/api/workspace',{action:'create',repo:pushed.url,branch:pushed.branch,profile:'small',fit:true});
|
|
107
|
+
if(!ws?.token||!ws?.name)throw new Error('The cloud chat did not start. Try again.');
|
|
108
|
+
await client.start(ws.token,task,{mode});
|
|
109
|
+
return {name:ws.name,token:ws.token,url:chatUrl(server,ws.name),repo:pushed.repo,branch:pushed.branch,commit:pushed.commit};
|
|
110
|
+
}
|