vigthoria-cli 2.3.8 → 2.3.12
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 +4 -2
- package/package.json +2 -2
- package/public-dist/index.mjs +120 -80
- package/public-dist/account.mjs +0 -38
- package/public-dist/agent.mjs +0 -48
- package/public-dist/api-keys.mjs +0 -14
- package/public-dist/catalog.mjs +0 -121
- package/public-dist/commands.mjs +0 -49
- package/public-dist/continuity.mjs +0 -12
- package/public-dist/deck-channel.mjs +0 -16
- package/public-dist/diagnostics.mjs +0 -8
- package/public-dist/local-tools.mjs +0 -28
- package/public-dist/preferences.mjs +0 -13
- package/public-dist/presentation.mjs +0 -17
- package/public-dist/providers.mjs +0 -111
- package/public-dist/repl-input.mjs +0 -146
- package/public-dist/repository.mjs +0 -14
- package/public-dist/session-state.mjs +0 -11
- package/public-dist/task-progress.mjs +0 -61
- package/public-dist/terminal.mjs +0 -134
- package/public-dist/update.mjs +0 -13
- package/public-dist/workflows.mjs +0 -12
- package/public-dist/workspace-tools.mjs +0 -83
- package/public-dist/workspace.mjs +0 -55
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
2
|
-
// Bounded local filesystem transport. Planning, prompts and tool policy stay hosted.
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import {execFileSync,spawn} from 'node:child_process';
|
|
6
|
-
import {createHash} from 'node:crypto';
|
|
7
|
-
import {safePath,sensitive,generatedPath,binaryPath,workspaceHasSecret,hasSecret,applyFiles,workspaceIssue} from './workspace.mjs';
|
|
8
|
-
const digest=value=>createHash('sha256').update(value).digest('hex');
|
|
9
|
-
export function projectInventory(root){
|
|
10
|
-
root=fs.realpathSync(root);const issue=workspaceIssue(root);if(issue)throw Error(issue);
|
|
11
|
-
let gitFiles=null;try{gitFiles=new Set(execFileSync('git',['-c','core.fsmonitor=false','-c','safe.directory='+root,'ls-files','--cached','--others','--exclude-standard','-z','--','.'],{cwd:root,stdio:['ignore','pipe','pipe'],timeout:10000,maxBuffer:8*1024*1024}).toString('utf8').split('\0').filter(Boolean));}catch(e){if(!/not a git repository/i.test(String(e.stderr||''))&&e.code!=='ENOENT')throw Error('Project ignore rules could not be verified.');if(e.code==='ENOENT'&&fs.existsSync(path.join(root,'.git')))throw Error('Install Git to verify ignore rules.');}
|
|
12
|
-
const files=[],directories=new Set();let visited=0;
|
|
13
|
-
function walk(dir,depth){if(depth>32)throw Error('Project directory nesting exceeds 32 levels.');for(const e of fs.readdirSync(dir,{withFileTypes:true})){if(++visited>50000)throw Error('Project inventory exceeds 50,000 entries. Select a focused project folder.');const abs=path.join(dir,e.name),rel=path.relative(root,abs).split(path.sep).join('/');if(e.isSymbolicLink()||sensitive(rel)||generatedPath(rel)||binaryPath(rel))continue;if(e.isDirectory()){directories.add(rel);walk(abs,depth+1);}else if(e.isFile()&&(!gitFiles||gitFiles.has(rel)))files.push(rel);}}
|
|
14
|
-
walk(root,0);files.sort();return {root,files,directories:[...directories].sort()};
|
|
15
|
-
}
|
|
16
|
-
function patternMatcher(pattern){if(typeof pattern!=='string'||pattern.length>300)throw Error('Use a bounded filename pattern.');let result='';for(let i=0;i<pattern.length;i++){const c=pattern[i];if(c==='*'&&pattern[i+1]==='*'){i++;if(pattern[i+1]==='/'){i++;result+='(?:.*/)?';}else result+='.*';}else if(c==='*')result+='[^/]*';else if(c==='?')result+='[^/]';else result+=c.replace(/[\\^$+?.()|{}\[\]]/g,'\\$&');}return new RegExp('^'+result+'$');}
|
|
17
|
-
export function localWorkspace(root,{approve=async()=>false,approveCommand=async()=>false,signal}={}){
|
|
18
|
-
const inventory=projectInventory(root),changed=new Set(),readHashes=new Map(),receipts=new Map();root=inventory.root;
|
|
19
|
-
const relative=value=>{let name=String(value??'.').replace(/^vigthoria:\/\/workspace\/?/,'').replace(/^\.\//,'');if(name==='.'||!name)return '';if(path.isAbsolute(name)){if(name===root)return '';if(!name.startsWith(root+path.sep))throw Error('Path is outside the selected project.');name=path.relative(root,name).split(path.sep).join('/');}safePath(root,name);return name;};
|
|
20
|
-
function readable(name){if(!inventory.files.includes(name))throw Error('This file is excluded by project ignore rules or source filters.');const abs=safePath(root,name);if(generatedPath(name)||binaryPath(name))throw Error('Generated files and binary assets are excluded from source tools.');const st=fs.lstatSync(abs);if(!st.isFile()||st.size>4*1024*1024)throw Error('Use a smaller source file (maximum 4 MiB).');const raw=fs.readFileSync(abs);if(raw.includes(0))throw Error('Binary files are excluded.');const text=new TextDecoder('utf8',{fatal:true,ignoreBOM:true}).decode(raw);if(workspaceHasSecret(name,text))throw Error('This file contains credential-like values and was not sent.');readHashes.set(name,digest(raw));return {text,raw};}
|
|
21
|
-
function candidates(directory){const prefix=directory?directory+'/':'';return inventory.files.filter(n=>n.startsWith(prefix));}
|
|
22
|
-
async function command(args){
|
|
23
|
-
const cwd=relative(args.cwd||'.'),dir=cwd?safePath(root,cwd):root;
|
|
24
|
-
const text=String(args.command||'');
|
|
25
|
-
if(!text||text.length>10000||text.includes('\0'))throw Error('Invalid command.');
|
|
26
|
-
if(!await approveCommand(text))return {success:false,output:'',error:'Local command was declined.'};
|
|
27
|
-
if(signal?.aborted)return {success:false,output:'',error:'Request cancelled before the local command started.'};
|
|
28
|
-
return await new Promise(resolve=>{
|
|
29
|
-
const env=Object.fromEntries(Object.entries(process.env).filter(([k])=>!/(?:TOKEN|SECRET|PASSWORD|API_KEY|CREDENTIAL)/i.test(k)));
|
|
30
|
-
let output='',finished=false,stopReason='';
|
|
31
|
-
const child=spawn(text,{cwd:dir,env,shell:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe']});
|
|
32
|
-
let killTimer;
|
|
33
|
-
function stop(reason){
|
|
34
|
-
if(finished||stopReason)return;
|
|
35
|
-
stopReason=reason;
|
|
36
|
-
try{if(process.platform!=='win32')process.kill(-child.pid,'SIGTERM');else child.kill();}catch{}
|
|
37
|
-
killTimer=setTimeout(()=>{try{if(process.platform!=='win32')process.kill(-child.pid,'SIGKILL');else child.kill('SIGKILL');}catch{}},2000);
|
|
38
|
-
killTimer.unref();
|
|
39
|
-
}
|
|
40
|
-
const cancel=()=>stop('cancelled');
|
|
41
|
-
const timer=setTimeout(()=>stop('timeout'),Math.max(1000,Math.min(Number(args.timeout)||30,120)*1000));
|
|
42
|
-
signal?.addEventListener('abort',cancel,{once:true});
|
|
43
|
-
if(signal?.aborted)cancel();
|
|
44
|
-
const chunk=b=>{output+=b.toString('utf8');if(Buffer.byteLength(output)>100000){output=output.slice(0,90000)+'\n[Output limit reached]';stop('output_limit');}};
|
|
45
|
-
child.stdout.on('data',chunk);child.stderr.on('data',chunk);
|
|
46
|
-
function finish(result){if(finished)return;finished=true;clearTimeout(timer);clearTimeout(killTimer);signal?.removeEventListener('abort',cancel);resolve(result);}
|
|
47
|
-
child.on('error',()=>finish({success:false,output:'',error:'Local command could not start.'}));
|
|
48
|
-
child.on('close',(code,sig)=>{
|
|
49
|
-
const success=code===0&&!stopReason;
|
|
50
|
-
const stopped={timeout:'Local command timed out; its work may be incomplete.',cancelled:'Local command was cancelled; its work may be incomplete.',output_limit:'Local command exceeded its output limit and was stopped.'};
|
|
51
|
-
finish({success,output:hasSecret(output)?'[Credential-bearing command output withheld]':output,
|
|
52
|
-
error:success?'':stopped[stopReason]||'Local command failed or stopped (exit '+code+(sig?', '+sig:'')+').'});
|
|
53
|
-
});
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
async function execute(name,args){
|
|
57
|
-
if(signal?.aborted)throw Error('Request cancelled.');if(!args||typeof args!=='object'||Array.isArray(args))throw Error('Invalid tool arguments.');
|
|
58
|
-
if(name==='run_command')return command(args);
|
|
59
|
-
if(name==='list_directory'){const dir=relative(args.path||'.'),prefix=dir?dir+'/':'';const files=candidates(dir),dirs=inventory.directories.filter(n=>n.startsWith(prefix));const depth=args.recursive?3:1;const rows=[...dirs.map(n=>n+'/'),...files].filter(n=>n.slice(prefix.length).replace(/\/$/,'').split('/').length<=depth).sort();return {success:true,output:rows.slice(0,300).map(n=>n.slice(prefix.length)).join('\n')+(rows.length>300?'\n[Listing limited to 300 entries]':'')};}
|
|
60
|
-
if(name==='glob'){const dir=relative(args.path||'.'),match=patternMatcher(args.pattern),files=candidates(dir).filter(n=>match.test(dir?n.slice(dir.length+1):n));return {success:true,output:files.slice(0,Math.min(300,Math.max(1,Number(args.max_results)||100))).join('\n')};}
|
|
61
|
-
if(name==='search_files'){const dir=relative(args.path||'.'),match=patternMatcher(args.file_pattern||'*'),files=candidates(dir).filter(n=>match.test(path.posix.basename(n))||match.test(n));const expression=String(args.pattern||'');if(!expression||expression.length>300)throw Error('Use a bounded search expression.');
|
|
62
|
-
// Run regular expressions in a separate process with a strict deadline, so
|
|
63
|
-
// an expensive pattern cannot block the terminal or its cancellation path.
|
|
64
|
-
const source=`let raw='';process.stdin.on('data',c=>raw+=c);process.stdin.on('end',()=>{const {pattern,files,max}=JSON.parse(raw);const re=new RegExp(pattern,'i');const out=[];for(const [name,text]of files){const lines=text.split(/\\r?\\n/);for(let i=0;i<lines.length;i++){if(re.test(lines[i]))out.push(name+':'+(i+1)+': '+lines[i].slice(0,500));if(out.length>=max)break;}if(out.length>=max)break;}process.stdout.write(out.join('\\n'));});`;
|
|
65
|
-
const inputs=[];let bytes=0;for(const name of files){try{const {text}=readable(name);bytes+=Buffer.byteLength(text);if(bytes>20*1024*1024)break;inputs.push([name,text]);}catch{}}
|
|
66
|
-
let output;try{output=execFileSync(process.execPath,['-e',source],{input:JSON.stringify({pattern:expression,files:inputs,max:Math.min(200,Math.max(1,Number(args.max_results)||50))}),encoding:'utf8',timeout:3000,maxBuffer:150000,stdio:['pipe','pipe','pipe']});}catch{throw Error('Search expression failed or exceeded its time limit. Use a narrower pattern.');}return {success:true,output:(output||'No matches in searched source files.')+(inputs.length<files.length?'\n[Some files were excluded or the 20 MiB search budget was reached; narrow the path.]':'')};}
|
|
67
|
-
const file=relative(args.path);if(!file)throw Error('Select a project-relative file path.');
|
|
68
|
-
if(name==='read_file'){const {text,raw}=readable(file),lines=text.split(/\r?\n/),start=Math.max(1,Number(args.start_line)||1),requested=Number(args.end_line)||start+399,end=Math.min(lines.length,requested,start+799);if(!Number.isInteger(start)||!Number.isInteger(end)||end<start)throw Error('Invalid line range.');const output='['+file+'] Lines '+start+'-'+end+' of '+lines.length+'\n'+lines.slice(start-1,end).map((line,i)=>String(start+i).padStart(5)+' | '+line).join('\n');if(Buffer.byteLength(output)>150000)throw Error('Read output is too large. Request fewer lines.');return {success:true,output,...(raw.length<=2*1024*1024?{baseline:{path:file,content:text,sha256:digest(raw),existed:true}}:{})};}
|
|
69
|
-
if(!['write_file','edit_file','delete_file'].includes(name))throw Error('This local tool is unavailable. Use the declared source tools or an approved local command.');
|
|
70
|
-
const abs=safePath(root,file),exists=fs.existsSync(abs);const expected=readHashes.get(file);let before=exists?readable(file):null;
|
|
71
|
-
if(exists&&expected&&digest(before.raw)!==expected)throw Error('The source file changed after it was read. Read it again before editing.');
|
|
72
|
-
if(args.expected_sha256!==undefined&&(!/^[a-f0-9]{64}$/.test(args.expected_sha256)||!before||digest(before.raw)!==args.expected_sha256))throw Error('The source changed before rollback; the current file was preserved.');
|
|
73
|
-
if(before&&before.raw.length>2*1024*1024)throw Error('This source exceeds the 2 MiB transactional edit limit. No change was made.');
|
|
74
|
-
const baseline={path:file,content:before?before.text:'',sha256:digest(before?before.raw:Buffer.alloc(0)),existed:exists};
|
|
75
|
-
let content=null;if(name==='write_file')content=args.content;else if(name==='edit_file'){if(!before||typeof args.old_string!=='string'||!args.old_string||typeof args.new_string!=='string')throw Error('Use nonempty exact old text and replacement text.');const matches=before.text.split(args.old_string).length-1;if(!matches||matches>1&&!args.replace_all)throw Error('Edit anchor was missing or ambiguous; read the file and use an exact unique anchor.');content=args.replace_all?before.text.split(args.old_string).join(args.new_string):before.text.replace(args.old_string,args.new_string);}
|
|
76
|
-
if(content!==null&&(typeof content!=='string'||Buffer.byteLength(content)>2*1024*1024||workspaceHasSecret(file,content)))throw Error('File content exceeds the limit or contains credential-like values.');
|
|
77
|
-
if(!await approve([file]))return {success:false,output:'',error:'Local file change was declined.'};
|
|
78
|
-
if(signal?.aborted)throw Error('Request cancelled before the local file change; the original was preserved.');
|
|
79
|
-
applyFiles({root,files:before?{[file]:before.text}:{},hashes:before?{[file]:digest(before.raw)}:{}},{[file]:content});changed.add(file);readHashes.delete(file);if(content===null)inventory.files=inventory.files.filter(n=>n!==file);else{if(!inventory.files.includes(file))inventory.files.push(file);let parent=path.posix.dirname(file);while(parent!=='.'){if(!inventory.directories.includes(parent))inventory.directories.push(parent);parent=path.posix.dirname(parent);}}
|
|
80
|
-
const raw=content===null?Buffer.alloc(0):Buffer.from(content);return {success:true,output:(content===null?'Deleted ':'Updated ')+file,baseline, ...(content===null?{}:{mutation:{path:file,content,sha256:digest(raw)}})};
|
|
81
|
-
}
|
|
82
|
-
return {inventory,changed,async call(event){if(!/^[a-f0-9]{32}$/.test(event.call_id||''))throw Error('Invalid local tool call identity.');const identity=JSON.stringify([event.name,event.arguments]);if(receipts.has(event.call_id)){const saved=receipts.get(event.call_id);if(saved.identity!==identity)throw Error('Conflicting local tool call identity.');return saved.result;}let result;try{result=await execute(event.name,event.arguments||{});}catch(e){result={success:false,output:'',error:e.message};}receipts.set(event.call_id,{identity,result});if(receipts.size>500)throw Error('Local tool request limit exceeded.');return result;}};
|
|
83
|
-
}
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
2
|
-
import fs from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import {createHash,randomUUID} from 'node:crypto';
|
|
5
|
-
import {execFileSync} from 'node:child_process';
|
|
6
|
-
const denied=new Set(['.git','.vigthoria','.ssh','.aws','.azure','.kube','node_modules','target','dist','build','coverage','secrets','credentials','venv','.venv','__pycache__','.pytest_cache','.mypy_cache','.ruff_cache','.cache','.codex','.agents','logs','uploads','runtime','data','backups','backup','vendor','.flask_secret_key','flask_secret_key','.session_secret','credentials.json','secrets.json']);
|
|
7
|
-
const sourceCodePath=name=>/\.(?:[cm]?[jt]sx?|py|go|rs|java|c|cpp|h|rb|php|html?|vue|svelte|json)$/i.test(name);
|
|
8
|
-
export const generatedPath=name=>/(?:\.(?:bak|backup|old|orig|tmp|swp|log)(?:[.\-_]|$)|\.pre-[^/]+$|\.min\.(?:js|css)$|\.map$|(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$)/i.test(name);
|
|
9
|
-
export const binaryPath=name=>/\.(?:png|jpe?g|webp|gif|avif|ico|mp[34]|m4[av]|mov|avi|webm|wav|flac|ogg|pdf|woff2?|ttf|eot|exe|dll|so|dylib|zip|gz|tar|7z|pyc|wasm|onnx|pt|safetensors|vrm|glb)$/i.test(name);
|
|
10
|
-
const planPrefix=/^\.vigthoria(?:\/plans(?:\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})?)?$/;
|
|
11
|
-
export const portablePlanPath=name=>/^\.vigthoria\/plans\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\/(?:PROJECT_PLAN\.md|AGENT_RULES\.md|README\.md|plan\.json|workloop\.cjs|workloop-state\.cjs|[0-9]{2}_[a-zA-Z0-9_-]+\.md)$/.test(name);
|
|
12
|
-
export function sensitive(name,{portablePlans=false}={}){if(portablePlans&&(planPrefix.test(name)||portablePlanPath(name)))return false;const parts=name.replaceAll('\\','/').split('/');return parts.some(p=>denied.has(p.toLowerCase())||/^\.env(?:\.|$)|^\.(?:npmrc|netrc|pypirc)$|^(?:id_rsa|id_ed25519)$|\.(?:pem|key|p12|pfx|sqlite|db)$/i.test(p));}
|
|
13
|
-
export function hasSecret(text,{sourceCode=false}={}){
|
|
14
|
-
const strong=/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:sk-(?:proj-)?[a-zA-Z0-9_-]{20,}|(?:ghp|github_pat)_[\w]{20,}|vgc_[\w-]{43}|vcli_[A-Za-z0-9_-]{43}|(?:AKIA|ASIA)[A-Z0-9]{16}|AIza[\w-]{30,}|eyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,})\b|\bBearer\s+[A-Za-z0-9_./+=:-]{20,}/i;
|
|
15
|
-
if(strong.test(text))return true;
|
|
16
|
-
// In source, a reference such as password = request.form.get(...) is not
|
|
17
|
-
// a credential value. Literal keys remain excluded; .env/text also scan bare values.
|
|
18
|
-
const assignment=sourceCode?/\b(?:api[_-]?key|password|access[_-]?token|auth[_-]?token|client_secret|secret[_-]?key|jwt[_-]?secret)["']?\s*[:=]\s*["'][A-Za-z0-9_./+=:-]{12,}/i:/\b(?:api[_-]?key|password|access[_-]?token|auth[_-]?token|client_secret|secret[_-]?key|jwt[_-]?secret)["']?\s*[:=]\s*["']?[A-Za-z0-9_./+=:-]{12,}/i;
|
|
19
|
-
return assignment.test(text);
|
|
20
|
-
}
|
|
21
|
-
export const workspaceHasSecret=(name,text)=>hasSecret(text,{sourceCode:sourceCodePath(name)});
|
|
22
|
-
export function workspaceIssue(root){
|
|
23
|
-
root=fs.realpathSync(root);
|
|
24
|
-
if(root===path.parse(root).root||['/var/www','/home','/Users','/var','/mnt'].includes(root))return 'Choose one project folder. '+root+' contains multiple projects or system data. Use /workspace PATH, or Choose an existing workspace.';
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
27
|
-
function transferLimit(root,bytes,count){return Object.assign(Error('Project '+root+' exceeds the source transfer limit ('+(bytes/1048576).toFixed(1)+' MiB, '+count+' files; maximum 20 MiB / 5,000 files). No request was sent. Use /workspace PATH to select a focused project directory.'),{code:'WORKSPACE_TRANSFER_LIMIT',root,bytes,fileCount:count});}
|
|
28
|
-
|
|
29
|
-
// VGP containers can include hash-addressed GLB bytes. Validate them as assets,
|
|
30
|
-
// then scan their JSON metadata rather than mistaking arbitrary base64 for keys.
|
|
31
|
-
export function repositoryHasSecret(name,text){
|
|
32
|
-
if(!name.toLowerCase().endsWith('.vgp'))return workspaceHasSecret(name,text);
|
|
33
|
-
let doc;try{doc=JSON.parse(text);}catch{return hasSecret(text);}
|
|
34
|
-
if(doc?.schemaVersion!==1||doc.engine!=='babylon'||!doc.assets||typeof doc.assets!=='object'||Array.isArray(doc.assets))return hasSecret(text);
|
|
35
|
-
const assets=Object.create(null);
|
|
36
|
-
for(const [key,value] of Object.entries(doc.assets)){
|
|
37
|
-
if(!/^[a-f0-9]{64}$/.test(key)||typeof value!=='string'||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))throw Error('Invalid portable scene asset');
|
|
38
|
-
const bytes=Buffer.from(value,'base64');
|
|
39
|
-
if(bytes.length<28||bytes.readUInt32LE(0)!==0x46546c67||bytes.readUInt32LE(4)!==2||bytes.readUInt32LE(8)!==bytes.length||createHash('sha256').update(bytes).digest('hex')!==key)throw Error('Portable scene asset integrity failed');
|
|
40
|
-
const jsonLength=bytes.readUInt32LE(12);if(bytes.readUInt32LE(16)!==0x4e4f534a||20+jsonLength>bytes.length)throw Error('Invalid portable scene model metadata');
|
|
41
|
-
const metadata=bytes.subarray(20,20+jsonLength).toString('utf8');JSON.parse(metadata);if(hasSecret(metadata))return true;assets[key]='verified-glb:'+key;
|
|
42
|
-
}
|
|
43
|
-
return hasSecret(JSON.stringify({...doc,assets}));
|
|
44
|
-
}
|
|
45
|
-
export function safePath(root,relative,options={}){if(typeof relative!=='string'||!relative||relative.includes('\0')||relative.includes('\\')||path.posix.isAbsolute(relative)||relative.split('/').some(p=>!p||p==='..'||p==='.'||/[<>:"|?*\x00-\x1f]/.test(p)||/[. ]$/.test(p)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p))||sensitive(relative,options))throw Error('Unsafe workspace path');const canonical=fs.realpathSync(root),target=path.resolve(canonical,relative);if(!target.startsWith(canonical+path.sep))throw Error('Workspace boundary violation');let cursor=canonical;for(const p of relative.split('/')){cursor=path.join(cursor,p);const stat=fs.lstatSync(cursor,{throwIfNoEntry:false});if(stat?.isSymbolicLink())throw Error('Workspace symbolic links are excluded');}return target;}
|
|
46
|
-
export function snapshot(root,{binary=false,portablePlans=false}={}){root=fs.realpathSync(root);const files=Object.create(null),hashes=Object.create(null),excluded=[];let bytes=0,entries=0;
|
|
47
|
-
let gitFiles=null;
|
|
48
|
-
try{gitFiles=new Set(execFileSync('git',['-c','core.fsmonitor=false','-c','safe.directory='+root,'ls-files','--cached','--others','--exclude-standard','-z','--','.'],{cwd:root,stdio:['ignore','pipe','pipe'],timeout:10000,maxBuffer:8*1024*1024}).toString('utf8').split('\0').filter(Boolean));}catch(error){if(error.code==='ENOENT'){if(fs.existsSync(path.join(root,'.git')))throw Error('Install Git to verify this project’s ignore rules before cloud transfer.');}else if(!/not a git repository/i.test(String(error.stderr||'')))throw Error('Git ignore inventory could not be verified; no files were submitted.');}
|
|
49
|
-
const walk=(folder,depth)=>{if(depth>32)throw Error('Workspace nesting exceeds transport limit');for(const entry of fs.readdirSync(folder,{withFileTypes:true})){if(++entries>50000)throw Error('Workspace contains too many entries for this transfer');const full=path.join(folder,entry.name),name=path.relative(root,full).split(path.sep).join('/');if(sensitive(name,{portablePlans})||entry.isSymbolicLink()||generatedPath(name)||(!binary&&binaryPath(name))){if(excluded.length<10000)excluded.push(name);continue;}if(entry.isDirectory()){walk(full,depth+1);continue;}if(!entry.isFile()||(gitFiles&&!gitFiles.has(name)))continue;const stat=fs.lstatSync(full);if(stat.size>2*1024*1024){excluded.push(name);continue;}const raw=fs.readFileSync(full);let text;try{if(raw.includes(0))throw Error();text=new TextDecoder('utf8',{fatal:true}).decode(raw);}catch{if(!binary){excluded.push(name);continue;}text=raw;}if(typeof text==='string'&&(binary?repositoryHasSecret(name,text):workspaceHasSecret(name,text))){excluded.push(name);continue;}bytes+=raw.length;if(bytes>20*1024*1024||Object.keys(files).length>=5000)throw transferLimit(root,bytes,Object.keys(files).length+1);files[name]=text;hashes[name]=createHash('sha256').update(raw).digest('hex');}};walk(root,0);return{root,files,hashes,bytes,excluded};}
|
|
50
|
-
export function applyFiles(snap,files,options={}){if(Object.keys(files).length>5000)throw Error('Workspace result exceeds file limit');const names=new Set();for(const name of Object.keys(files)){const lower=name.toLowerCase();if(names.has(lower))throw Error('Duplicate cross-platform workspace path');names.add(lower);}const plans=[];let total=0;
|
|
51
|
-
for(const[name,text]of Object.entries(files)){if(text!==null&&typeof text!=='string'&&!Buffer.isBuffer(text)||text!==null&&Buffer.byteLength(text)>2*1024*1024)throw Error('Invalid workspace result');total+=text===null?0:Buffer.byteLength(text);if(total>20*1024*1024)throw Error('Workspace result exceeds transfer limit');const target=safePath(snap.root,name,options);const before=fs.lstatSync(target,{throwIfNoEntry:false});if(before&&!before.isFile())throw Error('Target is not a regular file');const raw=before?fs.readFileSync(target):null;const current=raw?createHash('sha256').update(raw).digest('hex'):undefined;if(current!==snap.hashes[name])throw Error('Project changed during the run; returned files were not applied.');if(options.preserveSnapshotFormatting&&typeof text==='string'&&typeof snap.files[name]==='string'&&!options.writtenPaths?.has(name)&&text.replace(/\r\n/g,'\n')===snap.files[name].replace(/\r\n/g,'\n'))continue;plans.push({name,target,text,before,raw,temp:target+'.vigthoria-'+randomUUID()+'.tmp'});}
|
|
52
|
-
// Check the complete change set before the first write. Keep originals available for rollback.
|
|
53
|
-
const committed=[];try{for(const p of plans){safePath(snap.root,p.name,options);fs.mkdirSync(path.dirname(p.target),{recursive:true});if(p.text===null)continue;const fd=fs.openSync(p.temp,'wx',p.before?p.before.mode&0o777:0o600);try{fs.writeFileSync(fd,p.text);fs.fsyncSync(fd);}finally{fs.closeSync(fd);}}
|
|
54
|
-
for(const p of plans){safePath(snap.root,p.name,options);const now=fs.lstatSync(p.target,{throwIfNoEntry:false});if(p.before?!now?.isFile()||now.ino!==p.before.ino||!fs.readFileSync(p.target).equals(p.raw):Boolean(now))throw Error('Project changed during application');if(p.text===null){if(p.before)fs.unlinkSync(p.target);}else fs.renameSync(p.temp,p.target);committed.push({...p,after:p.text===null?null:Buffer.from(p.text)});}return plans.map(p=>p.name);
|
|
55
|
-
}catch(error){for(const p of committed.reverse())try{if(p.after===null?!fs.existsSync(p.target):fs.existsSync(p.target)&&fs.readFileSync(p.target).equals(p.after)){if(p.raw===null)fs.unlinkSync(p.target);else{fs.writeFileSync(p.temp,p.raw,{mode:p.before.mode&0o777});fs.renameSync(p.temp,p.target);}}}catch{}throw error;}finally{for(const p of plans)try{fs.unlinkSync(p.temp);}catch{}}}
|