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,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent Skills on this computer: folders with a SKILL.md (the format other coding agents use), sent with each CLI run
|
|
3
|
+
* as request.extensions.skills. The engine lists them in a short catalog and loads a body when the task names the
|
|
4
|
+
* skill (/id), matches its triggers or paths, or the agent asks (worker/skill_library.py).
|
|
5
|
+
* project <repo>/.mlai/skills/<name>/SKILL.md (also .claude/skills)
|
|
6
|
+
* user ~/.mlai/skills/<name>/SKILL.md (also ~/.claude/skills)
|
|
7
|
+
* plugins <plugin>/skills/<name>/SKILL.md (--plugin-dir, --plugin-url)
|
|
8
|
+
* SKILL.md frontmatter: name, description, and optionally triggers / paths (comma lists) and always: true.
|
|
9
|
+
* Other text files in the folder become reference files the agent can open (skill_load {id, file}).
|
|
10
|
+
* A project skill wins over a user skill with the same id. /skills disable <id> turns one off (settings skills.disabled).
|
|
11
|
+
*/
|
|
12
|
+
import {readdirSync,readFileSync,lstatSync} from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import {home} from '../home.mjs';
|
|
15
|
+
|
|
16
|
+
const MAX_SKILLS=60,MAX_BODY=20000,MAX_FILES=10,MAX_FILE=20000;
|
|
17
|
+
const TEXT=/\.(md|txt|json|ya?ml|toml|py|js|mjs|ts|sh|sql|csv|html|css)$/i;
|
|
18
|
+
export const skillId=s=>String(s||'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,60);
|
|
19
|
+
|
|
20
|
+
/** YAML-ish frontmatter: `key: value`, quoted values, and `key: >` / `key: |` blocks of indented lines. */
|
|
21
|
+
export function parseFrontmatter(text){
|
|
22
|
+
const t=String(text||'').replace(/^\uFEFF/,'');
|
|
23
|
+
if(!t.startsWith('---'))return {meta:{},body:t};
|
|
24
|
+
const end=t.indexOf('\n---',3);if(end<0)return {meta:{},body:t};
|
|
25
|
+
const meta={},lines=t.slice(3,end).split(/\r?\n/);
|
|
26
|
+
for(let i=0;i<lines.length;i++){
|
|
27
|
+
const m=/^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(lines[i]);if(!m)continue;
|
|
28
|
+
let v=m[2].trim();
|
|
29
|
+
if(v==='>'||v==='|'||v==='>-'||v==='|-'){const block=[];while(i+1<lines.length&&/^\s+\S/.test(lines[i+1]))block.push(lines[++i].trim());v=block.join(v.startsWith('>')?' ':'\n')}
|
|
30
|
+
else if(v===''){const items=[];while(i+1<lines.length&&/^\s*-\s+/.test(lines[i+1]))items.push(lines[++i].replace(/^\s*-\s+/,'').trim().replace(/^["']|["']$/g,''));if(items.length)v=items}
|
|
31
|
+
if(typeof v==='string'){
|
|
32
|
+
if(/^\[.*\]$/.test(v))v=v.slice(1,-1).split(',').map(x=>x.trim().replace(/^["']|["']$/g,'')).filter(Boolean);
|
|
33
|
+
else v=v.replace(/^["']|["']$/g,'');
|
|
34
|
+
}
|
|
35
|
+
meta[m[1].toLowerCase()]=v;
|
|
36
|
+
}
|
|
37
|
+
return {meta,body:t.slice(end+4).replace(/^\r?\n/,'')};
|
|
38
|
+
}
|
|
39
|
+
const list=v=>(Array.isArray(v)?v:typeof v==='string'?v.split(','):[]).map(x=>String(x).trim()).filter(Boolean).slice(0,20);
|
|
40
|
+
|
|
41
|
+
export function skillDirs(root,{pluginDirs=[],homeDir=null}={}){
|
|
42
|
+
const h=homeDir||path.dirname(home());
|
|
43
|
+
return [
|
|
44
|
+
...(root?[{dir:path.join(root,'.mlai','skills'),scope:'project'},{dir:path.join(root,'.claude','skills'),scope:'project'}]:[]),
|
|
45
|
+
...pluginDirs.map(d=>({dir:path.join(d,'skills'),scope:'plugin',plugin:path.basename(d)})),
|
|
46
|
+
{dir:path.join(home(),'skills'),scope:'user'},{dir:path.join(h,'.claude','skills'),scope:'user'},
|
|
47
|
+
];
|
|
48
|
+
}
|
|
49
|
+
const isDir=p=>{try{const s=lstatSync(p);return s.isDirectory()&&!s.isSymbolicLink()}catch{return false}};
|
|
50
|
+
const isFile=p=>{try{const s=lstatSync(p);return s.isFile()&&!s.isSymbolicLink()}catch{return false}};
|
|
51
|
+
|
|
52
|
+
/** One skill folder -> {id, name, description, content, files, triggers, paths, always, dir, file} or null. */
|
|
53
|
+
export function readSkill(dir){
|
|
54
|
+
const file=path.join(dir,'SKILL.md');if(!isFile(file))return null;
|
|
55
|
+
let text;try{text=readFileSync(file,'utf8')}catch{return null}
|
|
56
|
+
const {meta,body}=parseFrontmatter(text);
|
|
57
|
+
const id=skillId(meta.name||path.basename(dir));if(!id||!body.trim())return null;
|
|
58
|
+
const files={};
|
|
59
|
+
const walk=(d,prefix='',depth=0)=>{
|
|
60
|
+
let names=[];try{names=readdirSync(d).sort()}catch{return}
|
|
61
|
+
for(const n of names){
|
|
62
|
+
if(Object.keys(files).length>=MAX_FILES)return;if(n.startsWith('.'))continue;
|
|
63
|
+
const p=path.join(d,n),rel=prefix+n;
|
|
64
|
+
if(isDir(p)&&depth<2)walk(p,rel+'/',depth+1);
|
|
65
|
+
else if(rel!=='SKILL.md'&&isFile(p)&&TEXT.test(n)){try{const s=readFileSync(p,'utf8');if(s.length<=MAX_FILE)files[rel]=s}catch{}}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
walk(dir);
|
|
69
|
+
return {id,name:String(meta.name||id).slice(0,100),description:String(meta.description||'').replace(/\s+/g,' ').trim().slice(0,300),content:body.slice(0,MAX_BODY),
|
|
70
|
+
files,triggers:list(meta.triggers),paths:list(meta.paths||meta.globs),always:meta.always==='true'||meta.always===true,dir,file};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Every skill found, in precedence order, unique ids: [{...skill, scope, enabled}]. */
|
|
74
|
+
export function discoverSkills(root,{pluginDirs=[],disabled=[],homeDir=null}={}){
|
|
75
|
+
const seen=new Map(),off=new Set(disabled);
|
|
76
|
+
for(const {dir,scope,plugin} of skillDirs(root,{pluginDirs,homeDir})){
|
|
77
|
+
let names=[];try{names=readdirSync(dir).sort()}catch{continue}
|
|
78
|
+
for(const n of names){
|
|
79
|
+
if(seen.size>=MAX_SKILLS*2)break;
|
|
80
|
+
const d=path.join(dir,n);if(n.startsWith('.')||!isDir(d))continue;
|
|
81
|
+
const s=readSkill(d);if(!s||seen.has(s.id))continue;
|
|
82
|
+
seen.set(s.id,{...s,scope,...(plugin?{plugin}:{}),enabled:!off.has(s.id)});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return [...seen.values()];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** What the engine gets (worker/skill_library.py _clean): only enabled skills, bounded. */
|
|
89
|
+
export function engineSkills(skills){
|
|
90
|
+
return skills.filter(s=>s.enabled).slice(0,MAX_SKILLS).map(s=>({id:s.id,name:s.name,description:s.description,content:s.content,
|
|
91
|
+
...(Object.keys(s.files).length?{files:s.files}:{}),...(s.triggers.length?{triggers:s.triggers}:{}),...(s.paths.length?{paths:s.paths}:{}),...(s.always?{always:true}:{})}));
|
|
92
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-turn file snapshots for /rewind. Before each turn the project folder is recorded in a private git store in the
|
|
3
|
+
* session folder (<session>/snapshots.git), never in the project's own repository: no commits, branches or stash
|
|
4
|
+
* entries appear there. .gitignore rules are honored, so node_modules and build output are not copied.
|
|
5
|
+
* Restoring a turn writes its files back and removes files created after it.
|
|
6
|
+
*/
|
|
7
|
+
import {execFile} from 'node:child_process';
|
|
8
|
+
import {existsSync} from 'node:fs';
|
|
9
|
+
import {mkdir,readFile,writeFile,rm} from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
const LIMIT_MS=20000,MAX_BUFFER=64*1024*1024;
|
|
13
|
+
const store=session=>path.join(session.dir,'snapshots.git');
|
|
14
|
+
function git(session,args,{input}={}){
|
|
15
|
+
const dir=store(session);
|
|
16
|
+
const env={...process.env,GIT_DIR:dir,GIT_WORK_TREE:session.meta.root,GIT_INDEX_FILE:path.join(dir,'mlai-index'),
|
|
17
|
+
GIT_AUTHOR_NAME:'ML AI Code',GIT_AUTHOR_EMAIL:'snapshots@mlai.local',GIT_COMMITTER_NAME:'ML AI Code',GIT_COMMITTER_EMAIL:'snapshots@mlai.local',GIT_TERMINAL_PROMPT:'0'};
|
|
18
|
+
for(const k of ['GIT_OBJECT_DIRECTORY','GIT_ALTERNATE_OBJECT_DIRECTORIES','GIT_CEILING_DIRECTORIES'])delete env[k];
|
|
19
|
+
return new Promise((resolve,reject)=>{
|
|
20
|
+
const p=execFile('git',['-c','core.autocrlf=false','-c','core.safecrlf=false','-c','gc.auto=0',...args],{cwd:session.meta.root,env,timeout:LIMIT_MS,maxBuffer:MAX_BUFFER,encoding:'utf8'},(e,stdout,stderr)=>e?reject(Object.assign(new Error(String(stderr||e.message).trim().split('\n').pop()),{code:e.code})):resolve(stdout.trim()));
|
|
21
|
+
if(input!=null)p.stdin.end(input);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
async function ensure(session){
|
|
25
|
+
const dir=store(session);
|
|
26
|
+
if(existsSync(path.join(dir,'HEAD')))return;
|
|
27
|
+
await mkdir(dir,{recursive:true,mode:0o700});
|
|
28
|
+
await new Promise((res,rej)=>execFile('git',['init','-q','--bare',dir],{timeout:LIMIT_MS},e=>e?rej(e):res()));
|
|
29
|
+
// The project's own excludes, plus the session store itself when the session lives inside the project.
|
|
30
|
+
const own=await readFile(path.join(session.meta.root,'.git','info','exclude'),'utf8').catch(()=>'');
|
|
31
|
+
await mkdir(path.join(dir,'info'),{recursive:true});
|
|
32
|
+
await writeFile(path.join(dir,'info','exclude'),own+'\n.git\n.mlai/sessions/\n');
|
|
33
|
+
}
|
|
34
|
+
const ref=n=>'refs/turns/'+n;
|
|
35
|
+
/** The current folder as a tree id. */
|
|
36
|
+
async function tree(session){await git(session,['add','-A','--','.']);return git(session,['write-tree'])}
|
|
37
|
+
|
|
38
|
+
/** Records the folder as it is before turn `turn` (0-based). Returns the commit id, or null when snapshots are off. */
|
|
39
|
+
export async function snapshot(session,turn){
|
|
40
|
+
if(session.meta.snapshots===false)return null;
|
|
41
|
+
try{
|
|
42
|
+
await ensure(session);
|
|
43
|
+
const t=await tree(session);
|
|
44
|
+
const c=await git(session,['commit-tree',t,'-m','Before turn '+(turn+1)]);
|
|
45
|
+
await git(session,['update-ref',ref(turn),c]);
|
|
46
|
+
return c;
|
|
47
|
+
}catch(e){
|
|
48
|
+
// A folder too large to record in time: turn snapshots off for this session rather than slowing every turn.
|
|
49
|
+
if(e.code==='ETIMEDOUT'||e.killed||/timed out|ENOBUFS/.test(e.message)){session.meta.snapshots=false;await session.save().catch(()=>{})}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Turns that have a snapshot. */
|
|
54
|
+
export async function snapshots(session){
|
|
55
|
+
if(!existsSync(path.join(store(session),'HEAD')))return [];
|
|
56
|
+
const out=await git(session,['for-each-ref','--format=%(refname)','refs/turns/']).catch(()=>'');
|
|
57
|
+
return out.split('\n').map(r=>Number(r.split('/').pop())).filter(Number.isInteger).sort((a,b)=>a-b);
|
|
58
|
+
}
|
|
59
|
+
/** Files that differ between now and the snapshot before `turn`: [{status:'A'|'M'|'D', path}] (A: created since). */
|
|
60
|
+
export async function changesSince(session,turn){
|
|
61
|
+
const now=await tree(session);
|
|
62
|
+
const out=await git(session,['diff','--name-status','--no-renames',ref(turn),now]);
|
|
63
|
+
return out?out.split('\n').map(l=>{const [s,...p]=l.split('\t');return {status:s[0],path:p.join('\t')}}):[];
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Writes the folder back to how it was before `turn`. The current state is kept as refs/turns/undo-<time> first, so a
|
|
67
|
+
* rewind can itself be undone by hand. Returns {restored, removed} file counts.
|
|
68
|
+
*/
|
|
69
|
+
export async function restore(session,turn){
|
|
70
|
+
const list=await snapshots(session);
|
|
71
|
+
if(!list.includes(turn))throw new Error('No file snapshot for turn '+(turn+1)+'.');
|
|
72
|
+
const now=await tree(session);
|
|
73
|
+
await git(session,['update-ref','refs/turns/undo-'+Date.now(),await git(session,['commit-tree',now,'-m','Before rewind'])]);
|
|
74
|
+
const changes=await changesSince(session,turn);
|
|
75
|
+
const created=changes.filter(c=>c.status==='A').map(c=>c.path);
|
|
76
|
+
for(const f of created){
|
|
77
|
+
const abs=path.resolve(session.meta.root,f);
|
|
78
|
+
if(abs.startsWith(path.resolve(session.meta.root)+path.sep))await rm(abs,{force:true});
|
|
79
|
+
}
|
|
80
|
+
await git(session,['read-tree',ref(turn)]);
|
|
81
|
+
await git(session,['checkout-index','-a','-f']);
|
|
82
|
+
return {restored:changes.length-created.length,removed:created.length};
|
|
83
|
+
}
|
|
84
|
+
/** Drops snapshots after `turn` (they belong to turns that no longer exist). */
|
|
85
|
+
export async function forget(session,fromTurn){
|
|
86
|
+
for(const n of await snapshots(session))if(n>fromTurn)await git(session,['update-ref','-d',ref(n)]).catch(()=>{});
|
|
87
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The status line under the input box: mode, model and its credit rate on the left; branch, context use and the
|
|
3
|
+
* account allowance on the right. settings.statusLine.command replaces it with the first line a command prints
|
|
4
|
+
* (it gets the same data as JSON on stdin), like other agent CLIs.
|
|
5
|
+
*/
|
|
6
|
+
import {execFile,spawn} from 'node:child_process';
|
|
7
|
+
import {width,truncate} from './ansi.mjs';
|
|
8
|
+
import {MODES,modeName,sessionMode} from '../modes.mjs';
|
|
9
|
+
|
|
10
|
+
export const compact=n=>{n=Number(n)||0;const a=Math.abs(n);return a>=1e9?(n/1e9).toFixed(1).replace(/\.0$/,'')+'B':a>=1e6?(n/1e6).toFixed(1).replace(/\.0$/,'')+'M':a>=1e4?Math.round(n/1e3)+'k':a>=1e3?(n/1e3).toFixed(1).replace(/\.0$/,'')+'k':String(Math.round(n))};
|
|
11
|
+
|
|
12
|
+
/** What the status line shows, from ctx.chat when the core provides it, else from the session and settings. */
|
|
13
|
+
export function statusData({chat,session,settings,running=false,branch=null,context=null}={}){
|
|
14
|
+
const mode=modeName(chat?.mode)||(session?.meta?sessionMode(session.meta):modeName(settings?.mode))||'agent';
|
|
15
|
+
const ctx=context||chat?.context;
|
|
16
|
+
return {
|
|
17
|
+
mode,modeLabel:MODES[mode]?.label||mode,
|
|
18
|
+
model:chat?.modelLabel||chat?.model||settings?.model||null,
|
|
19
|
+
credits:chat?.credits||null,
|
|
20
|
+
effort:chat?.effort||settings?.effort||null,
|
|
21
|
+
branch:branch||null,
|
|
22
|
+
context:ctx&&ctx.window?{used:ctx.used||0,window:ctx.window,percent:Math.min(100,Math.round(100*(ctx.used||0)/ctx.window))}:null,
|
|
23
|
+
tokensLeft:chat?.tokensLeft??null,
|
|
24
|
+
usage:chat?.usage||null,
|
|
25
|
+
running,folder:session?.meta?.folder||null,session:session?.meta?.id||null,sessionName:session?.meta?.name||null,
|
|
26
|
+
items:itemsOf(settings),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
const MODE_STYLE={agent:'accent',plan:'borderPlan',ask:'accent2',auto:'warn'};
|
|
30
|
+
export function modeStyle(t,mode){return t[MODE_STYLE[mode]]||t.accent}
|
|
31
|
+
/** Status line items (settings.statusLine.items picks and orders them). */
|
|
32
|
+
export const ITEMS={
|
|
33
|
+
mode:{side:'left',summary:'Mode (agent, plan, ask, auto)'},
|
|
34
|
+
model:{side:'left',summary:'Model and its credit rate'},
|
|
35
|
+
effort:{side:'left',summary:'Reasoning effort when not medium'},
|
|
36
|
+
vim:{side:'left',summary:'Vim mode (NORMAL or INSERT) when vim keys are on'},
|
|
37
|
+
queue:{side:'left',summary:'Messages queued for after this turn'},
|
|
38
|
+
jobs:{side:'left',summary:'Background terminals still running'},
|
|
39
|
+
branch:{side:'right',summary:'Git branch'},
|
|
40
|
+
cwd:{side:'right',summary:'Project folder'},
|
|
41
|
+
session:{side:'right',summary:'Session name or id'},
|
|
42
|
+
context:{side:'right',summary:'Context window used'},
|
|
43
|
+
credits:{side:'right',summary:'Allowance left on your plan'},
|
|
44
|
+
time:{side:'right',summary:'Clock (HH:MM)'},
|
|
45
|
+
};
|
|
46
|
+
export const DEFAULT_ITEMS=['mode','model','effort','vim','queue','jobs','branch','context','credits'];
|
|
47
|
+
export function itemsOf(settings){const v=settings?.statusLine?.items;return Array.isArray(v)&&v.length?v.filter(x=>ITEMS[x]):DEFAULT_ITEMS}
|
|
48
|
+
function piece(name,d,t){
|
|
49
|
+
switch(name){
|
|
50
|
+
case 'mode':return modeStyle(t,d.mode)(t.bold(d.modeLabel))+t.dim(' (shift+tab)');
|
|
51
|
+
case 'model':return d.model?t.text(d.model)+(d.credits?t.dim(' '+d.credits):''):'';
|
|
52
|
+
case 'effort':return d.effort&&d.effort!=='medium'?t.dim(d.effort+' effort'):'';
|
|
53
|
+
case 'vim':return d.vim?t.dim(d.vimMode==='normal'?'NORMAL':'INSERT'):'';
|
|
54
|
+
case 'queue':return d.queued?t.accent(d.queued+' queued'):'';
|
|
55
|
+
case 'jobs':return d.jobs?t.accent2(d.jobs+' background'):'';
|
|
56
|
+
case 'branch':return d.branch?t.dim(d.branch):'';
|
|
57
|
+
case 'cwd':return d.folder?t.dim(d.folder):'';
|
|
58
|
+
case 'session':return d.sessionName||d.session?t.dim(String(d.sessionName||d.session).slice(0,24)):'';
|
|
59
|
+
case 'context':{if(!d.context)return '';const p=d.context.percent,style=p>=85?t.bad:p>=65?t.warn:t.dim;return style(p+'% context')}
|
|
60
|
+
case 'credits':return d.tokensLeft!=null?t.dim(compact(d.tokensLeft)+' tokens left'):d.usage?.tokens?t.dim(compact(d.usage.tokens)+' tokens'):'';
|
|
61
|
+
case 'time':{const n=d.now?new Date(d.now):new Date();return t.dim(String(n.getHours()).padStart(2,'0')+':'+String(n.getMinutes()).padStart(2,'0'))}
|
|
62
|
+
}
|
|
63
|
+
return '';
|
|
64
|
+
}
|
|
65
|
+
/** One line, cut to cols. d.items picks the pieces (default DEFAULT_ITEMS). */
|
|
66
|
+
export function statusLine(d,{t,cols=80,box,hint=''}){
|
|
67
|
+
const sep=t.dim(' · ');
|
|
68
|
+
const items=Array.isArray(d.items)&&d.items.length?d.items:DEFAULT_ITEMS;
|
|
69
|
+
const left=[],right=[];
|
|
70
|
+
for(const name of items){const p=piece(name,d,t);if(p)(ITEMS[name]?.side==='right'?right:left).push(p)}
|
|
71
|
+
let l=' '+left.join(sep),r=right.join(sep)+' ';
|
|
72
|
+
if(hint)l=' '+(items.includes('mode')?piece('mode',d,t)+sep:'')+t.text(hint);
|
|
73
|
+
const room=cols-1;
|
|
74
|
+
if(width(l)+width(r)+2>room){r=d.context&&items.includes('context')?(d.context.percent+'% context '):'';r=t.dim(r)}
|
|
75
|
+
if(width(l)+width(r)+2>room)return truncate(l,room);
|
|
76
|
+
return l+' '.repeat(Math.max(1,room-width(l)-width(r)))+r;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Runs settings.statusLine.command (1 s limit) and returns its first line, or null. */
|
|
80
|
+
export function customStatus(command,data,{cwd,timeout=1000}={}){
|
|
81
|
+
return new Promise(resolve=>{
|
|
82
|
+
let out='',done=false;const finish=v=>{if(!done){done=true;resolve(v)}};
|
|
83
|
+
let p;try{p=spawn(process.platform==='win32'?'cmd':'sh',process.platform==='win32'?['/c',command]:['-c',command],{cwd,stdio:['pipe','pipe','ignore'],windowsHide:true})}catch{return finish(null)}
|
|
84
|
+
const timer=setTimeout(()=>{try{p.kill()}catch{}finish(null)},timeout);
|
|
85
|
+
p.stdout.on('data',d=>{out+=d;if(out.length>4000)p.kill()});
|
|
86
|
+
p.on('error',()=>finish(null));
|
|
87
|
+
p.on('close',()=>{clearTimeout(timer);finish(out.split('\n')[0]?.replace(/[\x00-\x08\x0b-\x1a\x7f]/g,'')||null)});
|
|
88
|
+
p.stdin.on('error',()=>{});p.stdin.end(JSON.stringify(data));
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** Current git branch (or short commit when detached), or null outside git. */
|
|
92
|
+
export function gitBranch(cwd){
|
|
93
|
+
return new Promise(r=>execFile('git',['rev-parse','--abbrev-ref','HEAD'],{cwd,windowsHide:true},(e,out)=>{
|
|
94
|
+
if(e)return r(null);const b=out.trim();
|
|
95
|
+
if(b!=='HEAD')return r(b);
|
|
96
|
+
execFile('git',['rev-parse','--short','HEAD'],{cwd,windowsHide:true},(e2,o2)=>r(e2?null:'@'+o2.trim()));
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Harness events -> transcript lines for the TUI. Tool calls are one row each (read, edit, run, search ...);
|
|
3
|
+
* their output is collapsed to a summary unless expanded (Ctrl-O). Pure, so it is tested without a terminal.
|
|
4
|
+
*/
|
|
5
|
+
import {render as markdown} from './markdown.mjs';
|
|
6
|
+
import {wrap,truncate,width} from './ansi.mjs';
|
|
7
|
+
import {prose,renderEvent} from '../render.mjs';
|
|
8
|
+
|
|
9
|
+
/** Tool names from the harness -> the verb shown on the row. */
|
|
10
|
+
const VERBS=[
|
|
11
|
+
[/^(read_file|read_files|parallel_reads|view|cat|Read)$/i,'Read'],
|
|
12
|
+
[/^(edit_file|str_replace|apply_patch|Edit|MultiEdit)$/i,'Edit'],
|
|
13
|
+
[/^(write_file|create_file|Write)$/i,'Write'],
|
|
14
|
+
[/^(search|grep|search_code|ripgrep|Grep|code_search|find_symbol)$/i,'Search'],
|
|
15
|
+
[/^(glob|list_files|list_dir|ls|Glob|LS)$/i,'List'],
|
|
16
|
+
[/^(web_search|research|WebSearch)$/i,'Web search'],
|
|
17
|
+
[/^(web_fetch|fetch_url|browse|WebFetch)$/i,'Fetch'],
|
|
18
|
+
[/^(run|bash|shell|run_command|Bash)$/i,'Run'],
|
|
19
|
+
[/^(todo|TodoWrite)$/i,'Plan'],
|
|
20
|
+
[/^(generate_image)$/i,'Image'],
|
|
21
|
+
[/^(computer)$/i,'Computer'],
|
|
22
|
+
];
|
|
23
|
+
export function verb(name){const n=String(name||'');for(const [re,v] of VERBS)if(re.test(n))return v;return n.replace(/^mcp__/,'').replace(/__/g,' ').replace(/_/g,' ').replace(/^\w/,c=>c.toUpperCase())||'Tool'}
|
|
24
|
+
|
|
25
|
+
/** Theme -> the palette render.mjs expects. */
|
|
26
|
+
export const legacy=t=>({dim:t.dim,bold:t.bold,red:t.bad,green:t.ok,yellow:t.warn,cyan:t.accent,gray:t.dim});
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A transcript writer. lines(e) returns the lines one event adds. It remembers the last command so its output
|
|
30
|
+
* row attaches to it, and keeps collapsed outputs so Ctrl-O can show them in full.
|
|
31
|
+
*/
|
|
32
|
+
/** The harness's finish marker (a fenced `echo COMPLETE_TASK...`) is not part of the reply. */
|
|
33
|
+
export const finishless=s=>String(s||'').replace(/```[a-z]*\s*\n\s*echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT\s*\n```/g,'').replace(/^\s*echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT\s*$/gm,'');
|
|
34
|
+
export class Transcript{
|
|
35
|
+
constructor({t,box,cols=80,expanded=false,verbose=false,raw=false}={}){this.t=t;this.box=box;this.cols=cols;this.expanded=expanded;this.verbose=verbose;this.raw=raw;this.collapsed=[];this.lastAssistant=''}
|
|
36
|
+
dot(style){return style(this.box?.dot||'●')+' '}
|
|
37
|
+
elbow(){return this.t.dim(this.box?.ascii?' L ':' ⎿ ')}
|
|
38
|
+
/** The user's message as it goes to the agent. */
|
|
39
|
+
user(text,{images=0,shell=false}={}){
|
|
40
|
+
const t=this.t,mark=shell?t.borderShell('!'):t.accent(this.box?.arrow||'›');
|
|
41
|
+
const lines=this.raw?String(text).split('\n'):wrap(String(text),this.cols-4);
|
|
42
|
+
return ['',...lines.map((l,i)=>(i?' ':mark+' ')+t.bold(l)),...(images?[t.dim(' + '+images+' image'+(images===1?'':'s'))]:[])];
|
|
43
|
+
}
|
|
44
|
+
assistant(content){
|
|
45
|
+
const p=prose(finishless(content));if(!p||p===this.lastAssistant)return [];
|
|
46
|
+
this.lastAssistant=p;
|
|
47
|
+
// Raw scrollback: the reply exactly as written (markdown source, no wrapping or color), for copying.
|
|
48
|
+
if(this.raw)return ['',...p.split('\n')];
|
|
49
|
+
const md=markdown(p,{t:this.t,cols:this.cols-2,box:this.box});
|
|
50
|
+
return ['',...md.map((l,i)=>(i?' ':this.dot(this.t.text))+l)];
|
|
51
|
+
}
|
|
52
|
+
tool(name,target){
|
|
53
|
+
const t=this.t,v=verb(name);
|
|
54
|
+
const tgt=target?' '+truncate(String(target),Math.max(10,this.cols-width(v)-6)):'';
|
|
55
|
+
return [this.dot(t.tool)+t.bold(v)+t.dim(tgt)];
|
|
56
|
+
}
|
|
57
|
+
command(cmd){
|
|
58
|
+
const t=this.t,first=String(cmd||'').split('\n');
|
|
59
|
+
const head=truncate(first[0],this.cols-8)+(first.length>1?t.dim(' (+'+(first.length-1)+' lines)'):'');
|
|
60
|
+
return [this.dot(t.tool)+t.bold('Run ')+t.accent(head)];
|
|
61
|
+
}
|
|
62
|
+
output(e){
|
|
63
|
+
const t=this.t,text=String(e.output||'').replace(/\s+$/,'');const rows=text?text.split('\n'):[];const ok=e.returncode===0;
|
|
64
|
+
if(!rows.length)return [this.elbow()+(ok?t.dim('done'):t.bad('exit '+e.returncode))];
|
|
65
|
+
// One-line results read best inline; bookkeeping results (task list saved) stay quiet.
|
|
66
|
+
if(ok&&/^todo: Task list updated\.?$/.test(text))return [];
|
|
67
|
+
if(ok&&rows.length<=2&&/^(\w+: )?\{"/.test(text))return [];
|
|
68
|
+
if(ok&&/^Command ran successfully and produced no output\.?$/.test(text))return [this.elbow()+t.dim('no output')];
|
|
69
|
+
if(this.raw)return [this.elbow()+(ok?t.dim(rows.length+' line'+(rows.length===1?'':'s')):t.bad('exit '+e.returncode)),...rows.slice(-200)];
|
|
70
|
+
if(ok&&rows.length<=2&&!this.expanded)return rows.map((r,i)=>(i?' ':this.elbow())+t.dim(truncate(r.replace(/^\w+: /,'').replace(/\t/g,' '),this.cols-6)));
|
|
71
|
+
const show=this.expanded?rows.slice(-200):ok?[]:rows.slice(-4);
|
|
72
|
+
const summary=(ok?t.dim(rows.length+' line'+(rows.length===1?'':'s')):t.bad('exit '+e.returncode)+t.dim(' · '+rows.length+' line'+(rows.length===1?'':'s')))+(this.expanded||rows.length<=show.length?'':t.dim(' (Ctrl-O to expand)'));
|
|
73
|
+
if(!this.expanded&&rows.length>show.length)this.collapsed.push(rows);
|
|
74
|
+
if(this.collapsed.length>20)this.collapsed.shift();
|
|
75
|
+
const body=show.flatMap(r=>wrap(r.replace(/\t/g,' '),this.cols-6)).map(r=>' '+(ok?t.dim(r):t.warn(r)));
|
|
76
|
+
return [this.elbow()+summary,...body];
|
|
77
|
+
}
|
|
78
|
+
/** The last collapsed output in full (Ctrl-O). */
|
|
79
|
+
expandLast(){
|
|
80
|
+
const rows=this.collapsed.pop();if(!rows)return [];
|
|
81
|
+
return [this.t.dim(' Output ('+rows.length+' lines)'),...rows.slice(-400).flatMap(r=>wrap(r,this.cols-6)).map(r=>' '+this.t.dim(r))];
|
|
82
|
+
}
|
|
83
|
+
todos(items){
|
|
84
|
+
const t=this.t;if(!Array.isArray(items)||!items.length)return [];
|
|
85
|
+
return [this.dot(t.tool)+t.bold('Plan'),...items.slice(0,30).map(it=>{const s=it.status;const mark=s==='done'?t.ok('[x]'):s==='in_progress'?t.accent('[>]'):t.dim('[ ]');return ' '+mark+' '+(s==='done'?t.faint(truncate(it.text,this.cols-10)):truncate(String(it.text),this.cols-10))})];
|
|
86
|
+
}
|
|
87
|
+
/** Lines for one event; [] for events that stay quiet. */
|
|
88
|
+
lines(e){
|
|
89
|
+
const t=this.t;
|
|
90
|
+
switch(e?.type){
|
|
91
|
+
case 'assistant':return this.assistant(e.content);
|
|
92
|
+
case 'answer':return e.content?this.assistant(String(e.content)):[];
|
|
93
|
+
case 'tool':return e.name==='todo'?[]:this.tool(e.name,e.target);
|
|
94
|
+
case 'command':return this.command(e.command);
|
|
95
|
+
case 'output':return this.output(e);
|
|
96
|
+
case 'todos':return this.todos(e.items);
|
|
97
|
+
case 'verification':{const ok=e.verdict?.status==='passed'||(e.verdict==null&&e.returncode===0);return [this.dot(ok?t.ok:t.bad)+t.bold(ok?'Check passed':'Check '+(e.verdict?.status||'failed'))+t.dim(' '+truncate(String(e.label||''),this.cols-20))]}
|
|
98
|
+
case 'edit_guard':return [this.dot(t.warn)+t.warn('Blocked edit ')+truncate(String(e.path||''),60)+t.dim(': '+truncate(String(e.content||''),this.cols-30))];
|
|
99
|
+
case 'steering':return [this.elbow()+t.accent('Steering received')];
|
|
100
|
+
case 'mode':return e.content?[this.elbow()+t.dim(String(e.content))]:[];
|
|
101
|
+
case 'note':return e.content?[this.elbow()+t.dim(truncate(String(e.content),this.cols-6))]:[];
|
|
102
|
+
case 'error':return ['',...wrap(String(e.content||e.error||'Error'),this.cols-2).map((l,i)=>(i?' ':this.dot(t.bad))+t.bad(l))];
|
|
103
|
+
case 'completion':{const l=renderEvent(e,{c:legacy(t)});return l?['',this.elbow()+l]:[]}
|
|
104
|
+
case 'inference':case 'inference_progress':case 'intent':case 'budget':case 'run_metrics':case 'prompt_profile':case 'model':case 'approval':return [];
|
|
105
|
+
case 'retry':return this.verbose?[this.elbow()+t.dim('retry: '+truncate(String(e.content||''),this.cols-14))]:[];
|
|
106
|
+
default:{const l=renderEvent(e,{c:legacy(t),verbose:this.verbose});return l?l.split('\n').map(x=>' '+truncate(x,this.cols-2)):[]}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The live preview of a reply that is still streaming: the last few rendered lines of its prose. */
|
|
112
|
+
export function previewLines(content,{t,cols,box,max=8}){
|
|
113
|
+
const p=prose(finishless(content));if(!p)return [];
|
|
114
|
+
const md=markdown(p,{t,cols:cols-2,box});
|
|
115
|
+
return md.slice(-max).map(l=>' '+l);
|
|
116
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Same as lib/two-words.ts (tests/two-words.test.mjs keeps them identical). Every automatic name is exactly two title-case words. Names a person types are never passed through here.
|
|
2
|
+
const STOP=new Set(('a an the to for of in on at by with from into onto about as and or but if so then than this that these those it its is are was were be been am do does did done '+
|
|
3
|
+
'i me my mine we us our you your yours he she they them their please pls plz kindly can could would should will shall may might must just also really maybe like '+
|
|
4
|
+
'help want wanted need needs needed lets let hey hi hello thanks thank ok okay now here there what how why when where which who whom whose some any all every something anything thing things '+
|
|
5
|
+
'get got go going make sure try trying im ive id dont doesnt didnt isnt cant wont im not no yes very quite bit little lot new set up out failing broken current existing simple small quick basic few better good nice '+
|
|
6
|
+
'el la los las lo de del un una unos unas por para que y o en con al es se su sus le les des du et au aux der die das und ein eine einen zu mit von ist il di che per').split(' '));
|
|
7
|
+
const ACRONYM={api:'API',apis:'APIs',css:'CSS',html:'HTML',ui:'UI',ux:'UX',ci:'CI',cd:'CD',pr:'PR',prs:'PRs',sql:'SQL',url:'URL',json:'JSON',ios:'iOS',jwt:'JWT',sdk:'SDK',cli:'CLI',
|
|
8
|
+
aws:'AWS',gcp:'GCP',db:'DB',ai:'AI',ml:'ML',seo:'SEO',csv:'CSV',pdf:'PDF',http:'HTTP',https:'HTTPS',dns:'DNS',ssh:'SSH',oauth:'OAuth',github:'GitHub',macos:'macOS',npm:'npm',js:'JS',ts:'TS'};
|
|
9
|
+
const INTENT=[[/\b(fix|fixe[sd]|fixing|bug|bugs|broken|error|errors|crash\w*|fail\w*|issue|debug\w*|repair)\b/i,'Fix'],[/\b(build|create|make|add|implement\w*|scaffold|generate|write|set ?up|new)\b/i,'Build'],
|
|
10
|
+
[/\b(review\w*|check|audit|inspect|look|analy[sz]e)\b/i,'Review'],[/\?\s*$|^\s*(what|how|why|when|where|who|explain|tell)\b/i,'Chat']];
|
|
11
|
+
const word=(t)=>{const k=t.toLowerCase();if(ACRONYM[k])return ACRONYM[k];if(/#|[A-Z]/.test(t.slice(1)))return t;const c=[...t];return c[0].toLocaleUpperCase()+c.slice(1).join('')};
|
|
12
|
+
function tokens(text){
|
|
13
|
+
const s=String(text??'').replace(/```[\s\S]*?(```|$)/g,' ').replace(/`/g,' ').replace(/\b(https?:\/\/|www\.)\S+/gi,' ').replace(/['\u2019](s|t|re|ll|d|m|ve)\b/gi,'');
|
|
14
|
+
const out=[];
|
|
15
|
+
const prose=/\s/.test(s.trim());
|
|
16
|
+
for(const raw of s.split(/\s+/)){
|
|
17
|
+
if(!raw||/[\/\\]|^[~.@]|@|^\[(image|file|attachment)/i.test(raw))continue;
|
|
18
|
+
// a file name counts as its base name: notes.txt is Notes, never Txt
|
|
19
|
+
const t=raw.replace(/^[^\p{L}\p{N}#]+|[^\p{L}\p{N}]+$/gu,'').replace(/^([\p{L}\p{N}_-]+)\.[a-z][a-z0-9]{0,4}$/iu,'$1');if(!t)continue;
|
|
20
|
+
const parts=/\p{N}|#/u.test(t)&&/\p{L}/u.test(t)||prose&&/^\p{L}{2,}-\p{L}{2,}$/u.test(t)?[t]:t.split(/[^\p{L}\p{N}]+/u); // in a sentence, long-running stays one word; slugs split
|
|
21
|
+
for(const p of parts)if(p&&/\p{L}/u.test(p)&&!STOP.has(p.toLowerCase()))out.push(p.slice(0,24));
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
/** Exactly two meaningful title-case words from free text, or the two-word fallback. `second` completes a single word (else it follows the intent). */
|
|
26
|
+
export function twoWordTitle(text,fallback='New Chat',second){
|
|
27
|
+
const w=tokens(text);if(!w.length)return fallback||'New Chat';
|
|
28
|
+
if(w.length>1)return word(w[0])+' '+word(w[1]);
|
|
29
|
+
const first=word(w[0]),hit=INTENT.find(([re])=>re.test(String(text??'')));let next=second||(hit?hit[1]:/\?\s*$/.test(String(text??''))?'Chat':'Task');
|
|
30
|
+
if(next.toLowerCase()===first.toLowerCase())next='Task';
|
|
31
|
+
return first+' '+next;
|
|
32
|
+
}
|
|
33
|
+
/** The first meaningful word plus a fixed second one: "Login Fork", "Web Team". */
|
|
34
|
+
export const nameWith=(text,second)=>(tokens(text).length?twoWordTitle(text).split(' ')[0]:'New')+' '+second;
|
|
35
|
+
/** True when a name is exactly two words, the shape every automatic name has. */
|
|
36
|
+
export const isTwoWords=(t)=>String(t??'').trim().split(/\s+/).filter(Boolean).length===2;
|
package/src/wakeups.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Self-scheduled wakeups for sessions on this computer. The harness writes <session>/wakeup.json (worker/wakeups.py);
|
|
2
|
+
// this scheduler checks every minute and right after a run ends, and starts the due wakeup as a new run in the same
|
|
3
|
+
// session. Timers do not run while the Mac sleeps, so the first check after waking catches up on anything overdue.
|
|
4
|
+
import {readFile,writeFile,rename} from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const ID=/^[a-f0-9]{16}$/;
|
|
8
|
+
async function readJson(file,fallback){try{return JSON.parse(await readFile(file,'utf8'))}catch{return fallback}}
|
|
9
|
+
async function writeJson(file,data){const tmp=file+'.'+process.pid+'.tmp';await writeFile(tmp,JSON.stringify(data));await rename(tmp,file)}
|
|
10
|
+
/** A pending, well-formed wakeup due at or before `now`, else null. */
|
|
11
|
+
export function dueWake(w,now=Date.now()){
|
|
12
|
+
if(!w||typeof w!=='object'||w.state!=='pending'||!ID.test(String(w.id)))return null;
|
|
13
|
+
const at=Date.parse(String(w.at));if(!Number.isFinite(at)||at>now)return null;
|
|
14
|
+
return {id:w.id,kind:w.kind==='goal'?'goal':'agent',note:String(w.note||'').slice(0,1000),at:w.at};
|
|
15
|
+
}
|
|
16
|
+
/** Run fields for the wake run, carried over from the session's last request (the worker keeps its own context). */
|
|
17
|
+
export function wakeRun(request,wake){
|
|
18
|
+
const r=request&&typeof request==='object'?request:{};
|
|
19
|
+
return {task:wake.note||(wake.kind==='goal'?'Continue the goal':'Scheduled check-in'),wake:{id:wake.id,kind:wake.kind,note:wake.note},
|
|
20
|
+
...(['plan','approve','auto','brief'].includes(r.mode)?{mode:r.mode}:{}),...(typeof r.role==='string'&&r.role?{role:r.role}:{}),
|
|
21
|
+
...(typeof r.modelId==='string'?{model:r.modelId}:{}),...(['low','medium','high'].includes(r.reasoningEffort)?{effort:r.reasoningEffort}:{}),
|
|
22
|
+
...(typeof r.planApproval==='string'?{planApproval:r.planApproval}:{}),...(Number(r.steps)>0?{steps:Math.min(160,Number(r.steps))}:{})};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* sessions(): [{token, dir}] for live sessions on this computer. running(token): a run is going. start(token, body):
|
|
26
|
+
* starts a run like the shell's 'run' action. A failed start (signed out, usage limit) keeps the wakeup pending and
|
|
27
|
+
* retries after `retryMs`; a started one is marked fired so it can never start twice.
|
|
28
|
+
*/
|
|
29
|
+
export function createWakeScheduler({sessions,running,start,now=()=>Date.now(),retryMs=10*60_000,onFired=()=>{}}){
|
|
30
|
+
const inflight=new Set(),failed=new Map();
|
|
31
|
+
async function tick(){
|
|
32
|
+
const fired=[];
|
|
33
|
+
for(const {token,dir} of await sessions()){
|
|
34
|
+
const file=path.join(dir,'wakeup.json');
|
|
35
|
+
const w=dueWake(await readJson(file,null),now());if(!w||inflight.has(w.id))continue;
|
|
36
|
+
if((failed.get(w.id)||0)>now()||await running(token))continue;
|
|
37
|
+
inflight.add(w.id);
|
|
38
|
+
try{
|
|
39
|
+
await start(token,wakeRun(await readJson(path.join(dir,'request.json'),{}),w));
|
|
40
|
+
const cur=await readJson(file,null);
|
|
41
|
+
if(cur?.id===w.id)await writeJson(file,{...cur,state:'fired',fired:new Date(now()).toISOString()});
|
|
42
|
+
failed.delete(w.id);fired.push(w.id);onFired({token,wake:w});
|
|
43
|
+
}catch(e){failed.set(w.id,now()+retryMs)}
|
|
44
|
+
finally{inflight.delete(w.id)}
|
|
45
|
+
}
|
|
46
|
+
return fired;
|
|
47
|
+
}
|
|
48
|
+
let timer=null;
|
|
49
|
+
return {tick,
|
|
50
|
+
start(intervalMs=60_000){if(!timer){timer=setInterval(()=>{tick().catch(()=>{})},intervalMs);timer.unref?.()}return this},
|
|
51
|
+
stop(){if(timer)clearInterval(timer);timer=null},
|
|
52
|
+
soon(ms=3000){const t=setTimeout(()=>{tick().catch(()=>{})},ms);t.unref?.()}};
|
|
53
|
+
}
|
package/src/winenv.mjs
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Windows support: the harness runs commands in bash, which Git for Windows provides (Git Bash).
|
|
2
|
+
import {existsSync,mkdirSync,readFileSync,renameSync,writeFileSync} from 'node:fs';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {execFileSync,spawnSync} from 'node:child_process';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
const isWin=process.platform==='win32';
|
|
9
|
+
/** Git for Windows install folder (contains bin\bash.exe and usr\bin), or null. Never the WSL bash in System32. */
|
|
10
|
+
export function gitForWindows(env=process.env){
|
|
11
|
+
if(!isWin)return null;
|
|
12
|
+
env={...process.env,...env};
|
|
13
|
+
const ok=dir=>dir&&existsSync(path.join(dir,'bin','bash.exe'))&&existsSync(path.join(dir,'usr','bin'))?dir:null;
|
|
14
|
+
if(env.MLAI_GIT_BASH){const d=path.dirname(path.dirname(env.MLAI_GIT_BASH));if(ok(d))return d}
|
|
15
|
+
try{
|
|
16
|
+
for(const line of execFileSync('where',['git'],{encoding:'utf8',stdio:['ignore','pipe','ignore'],env}).split(/\r?\n/)){
|
|
17
|
+
const p=line.trim();if(!p)continue;
|
|
18
|
+
// ...\Git\cmd\git.exe or ...\Git\bin\git.exe or ...\Git\mingw64\bin\git.exe
|
|
19
|
+
for(const up of [path.dirname(path.dirname(p)),path.dirname(path.dirname(path.dirname(p)))]){const d=ok(up);if(d)return d}
|
|
20
|
+
}
|
|
21
|
+
}catch{}
|
|
22
|
+
for(const base of [env.ProgramFiles,env['ProgramFiles(x86)'],env.LOCALAPPDATA&&path.join(env.LOCALAPPDATA,'Programs'),'C:\\Program Files']){const d=ok(base&&path.join(base,'Git'));if(d)return d}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Git Bash (MSYS2) cannot start under a restricted token: its signal pipe and per-user objects allow only the user,
|
|
27
|
+
* Administrators and SYSTEM. Inside the Windows sandbox, commands therefore run in busybox-w32, a native Windows build
|
|
28
|
+
* of the BusyBox shell and tools (https://frippery.org/busybox/). It is downloaded once and checked against this hash.
|
|
29
|
+
* Sources, in order (busyboxSources): MLAI_BUSYBOX_URL, the ML AI Code server this CLI talks to and the production
|
|
30
|
+
* site (both serve the pinned copy from public/tools/), then the upstream site. Only the SHA-256 makes a file
|
|
31
|
+
* trusted, so a mirror that fails or serves something else is skipped and the next one is tried.
|
|
32
|
+
*/
|
|
33
|
+
export const BUSYBOX={version:'FRP-6354-g5f09fb446',file:'busybox-w64u-FRP-6354-g5f09fb446.exe',sha256:'36b266923fc5765b42f5f981319f39568498fba60b53ccf26e8fc1e575e2a9a9'};
|
|
34
|
+
export const BUSYBOX_UPSTREAM='https://frippery.org/files/busybox/';
|
|
35
|
+
const PROD='https://mlai-mini-code.vercel.app';
|
|
36
|
+
/** Download URLs for the pinned busybox, most trusted host first, without duplicates. */
|
|
37
|
+
export function busyboxSources({server,env=process.env}={}){
|
|
38
|
+
const out=[];const add=u=>{if(typeof u==='string'&&/^https?:\/\//.test(u)&&!out.includes(u))out.push(u)};
|
|
39
|
+
add(env.MLAI_BUSYBOX_URL);
|
|
40
|
+
for(const host of [server,env.MLAI_URL,PROD])if(typeof host==='string'&&/^https:\/\//.test(host))add(host.replace(/\/+$/,'')+'/tools/'+BUSYBOX.file);
|
|
41
|
+
add(BUSYBOX_UPSTREAM+BUSYBOX.file);
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
// A pinned copy shipped with the engine: tools/ in the desktop app's engine, public/tools/ in a source checkout.
|
|
45
|
+
export const BUSYBOX_SEEDS=['../tools/','../../../public/tools/'].map(d=>fileURLToPath(new URL(d+BUSYBOX.file,import.meta.url)));
|
|
46
|
+
export const BUSYBOX_SEED=BUSYBOX_SEEDS[1];
|
|
47
|
+
export async function ensureBusybox(mlaiHome,{onProgress,server,sources=busyboxSources({server}),fetchImpl=fetch,seeds=BUSYBOX_SEEDS}={}){
|
|
48
|
+
if(process.env.MLAI_BUSYBOX&&existsSync(process.env.MLAI_BUSYBOX))return process.env.MLAI_BUSYBOX;
|
|
49
|
+
const dir=path.join(mlaiHome,'tools'),exe=path.join(dir,BUSYBOX.file);
|
|
50
|
+
if(existsSync(exe))return exe;
|
|
51
|
+
mkdirSync(dir,{recursive:true});
|
|
52
|
+
// The engine may ship the pinned copy (BUSYBOX_SEEDS): use it, without the network, when its hash matches.
|
|
53
|
+
for(const seed of seeds||[])try{const buf=readFileSync(seed);if(createHash('sha256').update(buf).digest('hex')===BUSYBOX.sha256){writeFileSync(exe+'.part',buf);renameSync(exe+'.part',exe);return exe}}catch{}
|
|
54
|
+
onProgress?.({type:'runtime',content:'Downloading the sandbox shell (busybox-w32, 0.7 MB)'});
|
|
55
|
+
const failed=[];let mismatch=false;
|
|
56
|
+
for(const url of sources){
|
|
57
|
+
try{
|
|
58
|
+
// The upstream host refuses some generic user agents (403), so send a specific one.
|
|
59
|
+
const r=await fetchImpl(url,{headers:{'User-Agent':'mlai/'+BUSYBOX.version+' (+'+PROD+')'},signal:AbortSignal.timeout(60000)});
|
|
60
|
+
if(!r.ok){failed.push(new URL(url).host+' '+r.status);continue}
|
|
61
|
+
const buf=Buffer.from(await r.arrayBuffer());
|
|
62
|
+
if(createHash('sha256').update(buf).digest('hex')!==BUSYBOX.sha256){mismatch=true;failed.push(new URL(url).host+' checksum');continue}
|
|
63
|
+
writeFileSync(exe+'.part',buf);renameSync(exe+'.part',exe);return exe;
|
|
64
|
+
}catch(e){failed.push(new URL(url).host+' '+(e?.name==='TimeoutError'?'timeout':'unreachable'))}
|
|
65
|
+
}
|
|
66
|
+
if(mismatch&&failed.every(f=>f.endsWith('checksum')))throw Object.assign(new Error('The sandbox shell download did not match its checksum, so it was not used.'),{code:'sandbox_shell_checksum'});
|
|
67
|
+
throw Object.assign(new Error('Could not download the sandbox shell ('+failed.join(', ')+'). Check the network, or use Guided mode.'),{code:'sandbox_shell_missing'});
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Environment for the harness on Windows: Git Bash and its tools first on PATH, UTF-8 Python, and bash stays in the
|
|
71
|
+
* project. With MLAI_BUSYBOX set (the sandbox), the shell is busybox and the MSYS folders are left off PATH; git.exe
|
|
72
|
+
* (a native program) stays.
|
|
73
|
+
*/
|
|
74
|
+
export function windowsEnv(env){
|
|
75
|
+
if(!isWin)return env;
|
|
76
|
+
const git=gitForWindows(env);if(!git)throw Object.assign(new Error('ML AI Code needs Git for Windows (it provides Git Bash). Install it from https://git-scm.com/download/win, then try again.'),{code:'git_bash_missing'});
|
|
77
|
+
const key=Object.keys(env).find(k=>k.toUpperCase()==='PATH')||'Path';
|
|
78
|
+
const rest=String(env[key]||'');
|
|
79
|
+
const out={...env};for(const k of Object.keys(out))if(k.toUpperCase()==='PATH')delete out[k];
|
|
80
|
+
if(env.MLAI_BUSYBOX){
|
|
81
|
+
const msys=[path.join(git,'usr','bin'),path.join(git,'bin')].map(p=>p.toLowerCase());
|
|
82
|
+
const kept=rest.split(';').filter(p=>p&&!msys.includes(path.resolve(p).toLowerCase()));
|
|
83
|
+
out.Path=[path.dirname(env.MLAI_BUSYBOX),path.join(git,'mingw64','bin'),path.join(git,'cmd'),...kept].join(';');
|
|
84
|
+
}else out.Path=[path.join(git,'usr','bin'),path.join(git,'bin'),path.join(git,'mingw64','bin'),rest].filter(Boolean).join(';');
|
|
85
|
+
// Git Bash's login profile changes to HOME unless this is set.
|
|
86
|
+
out.MLAI_BASH=path.join(git,'usr','bin','bash.exe');out.CHERE_INVOKING='1';out.PYTHONUTF8='1';
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
/** Stops a process and everything it started. */
|
|
90
|
+
export function killTree(pid){
|
|
91
|
+
if(!pid)return;
|
|
92
|
+
if(isWin){spawnSync('taskkill',['/T','/F','/PID',String(pid)],{stdio:'ignore',windowsHide:true});return}
|
|
93
|
+
try{process.kill(-pid,'SIGTERM')}catch{try{process.kill(pid,'SIGTERM')}catch{}}
|
|
94
|
+
}
|