vigthoria-cli 0.0.0-stage → 2.3.8

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.
@@ -0,0 +1,134 @@
1
+ /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import {workspaceIssue} from './workspace.mjs';
6
+ import {projectInventory} from './workspace-tools.mjs';
7
+ import {paint,section,detail,notice,modelName,cloudProfile} from './presentation.mjs';
8
+ import {routingLabel,disableProvider,providerMenu} from './providers.mjs';
9
+ import {preferences,setPreference,configuredRoot} from './preferences.mjs';
10
+ export const VERSION='2.3.8';
11
+ export const safe=s=>String(s??'').replace(/[\x00-\x1f\x7f-\x9f]/g,'');
12
+ const colour=(s,code,output,theme)=>output.isTTY&&theme!=='plain'&&!Object.hasOwn(process.env,'NO_COLOR')&&process.env.TERM!=='dumb'?'\x1b['+code+'m'+s+'\x1b[0m':s;
13
+ const accent=theme=>theme==='violet'?35:36;
14
+ export function banner(output=process.stdout,theme='cyan'){
15
+ const width=Math.max(20,Math.min(54,(output.columns||80)-4));
16
+ const paint=(s,c)=>colour(s,c,output,theme),edge=s=>paint(s,accent(theme));
17
+ const center=(text,code)=>{text=safe(text);if(text.length>width)text=text.slice(0,width-1)+'…';const left=Math.floor((width-text.length)/2);return edge('║')+' '.repeat(left)+paint(text,code)+' '.repeat(width-text.length-left)+edge('║');};
18
+ output.write('\n'+edge('╔'+'═'.repeat(width)+'╗')+'\n'+center('','0')+'\n'+center('VIGTHORIA CLI','1;97')+'\n'+center('AI-Powered Coding Assistant',theme==='violet'?'95':'96')+'\n'+center('Version '+VERSION,'90')+'\n'+center('','0')+'\n'+edge('╚'+'═'.repeat(width)+'╝')+'\n\n');
19
+ }
20
+ export const modelLabel=id=>id==='agent'?'Automatic routing (recommended)':safe(id).startsWith('vigthoria-cloud-')?'Vigthoria Cloud':safe(id);
21
+ const onOff=v=>v?'On':'Off';
22
+ function heading(text,theme){console.log('\n'+colour(safe(text),'1;'+accent(theme),process.stdout,theme));}
23
+ export async function choose(lines,message,choices,defaultValue,theme='cyan'){
24
+ return lines.select({message,choices,defaultValue,accent:theme==='plain'?0:accent(theme),plain:theme==='plain'});
25
+ }
26
+ export function modelChoices(data={}){
27
+ const valid=s=>typeof s==='string'&&/^[A-Za-z0-9._:-]{1,128}$/.test(s);
28
+ const choices=[{value:'agent',label:'Automatic routing (recommended)',description:'Vigthoria chooses cloud models for planning and coding. No model ID needed.'}];
29
+ for(const m of data.allowedCloudModels||[])if(valid(m.alias))choices.push({value:m.alias,label:'Vigthoria Cloud · '+cloudProfile(m.alias),description:'Uses your account allowance.'+(m.available===false?' Currently unavailable':''),disabled:m.available===false||(data.cloudAccessAllowed===false&&data.isMasterAdmin!==true)});
30
+ for(const m of data.localModels||[])if(valid(m.id))choices.push({value:m.id,label:'Local · '+safe(m.label||m.id),description:'Runs on Vigthoria servers. Assistant model; coding planning may still use cloud.',disabled:m.available===false});
31
+ return choices.filter((v,i,a)=>a.findIndex(c=>c.value===v.value)===i);
32
+ }
33
+ export async function selectModel(lines,current='agent',{theme='cyan',loadCatalog}={}){
34
+ heading('AI model',theme);
35
+ console.log('These models use your Vigthoria account. Selecting one disables your own provider route. Picking a model does not start generation.');
36
+ let data;
37
+ try{data=await (loadCatalog||(async()=>{const {request}=await import('./account.mjs');return request('/api/user/credits/model-preferences');}))();}
38
+ catch(e){console.log('Could not load your available models: '+safe(e.message));console.log('Sign in through Account & API, then try again. Your current model is kept.');return null;}
39
+ if(data.isMasterAdmin)console.log('Master Admin · company funded · no customer credits required.');
40
+ else if(data.cloudAccessAllowed===false)console.log('Cloud access is disabled for this account.');
41
+ else console.log('Cloud requests use your account’s funding and consent settings.');
42
+ if(!data.isMasterAdmin&&data.cloudConsent===false)console.log('Cloud consent is not enabled. Manage it in your Vigthoria account before starting cloud work.');
43
+ const selected=await choose(lines,'Choose an AI model',modelChoices(data),current,theme);
44
+ return selected;
45
+ }
46
+ const settingInfo={
47
+ debugMode:['Debug logging','Show tool names and additional progress details.'],
48
+ autoSave:['Save sessions automatically','Keep private local conversation history for resuming later.'],
49
+ autoApprove:['Approve changes automatically','On applies returned file changes and approves cloud verification commands without asking.'],
50
+ };
51
+ export async function settingsMenu(lines,session){
52
+ while(true){
53
+ heading('Session settings',session.theme);
54
+ const rows=Object.entries(settingInfo).map(([value,[label,description]])=>({value,label:label+' · '+onOff(session[value]),description}));
55
+ rows.push({value:'model',label:'AI model · '+(routingLabel(session)||modelLabel(session.model)),description:'Choose Automatic routing or an available model from your account.'},{value:'theme',label:'Header colours · '+({cyan:'Cyan & white',violet:'Violet & white',plain:'No colour'}[session.theme]||'Cyan & white'),description:'Change terminal presentation.'},{value:'back',label:'Back',description:'Return to session setup.'});
56
+ const key=await choose(lines,'Choose a setting',rows,'back',session.theme);if(key===null||key==='back')return;
57
+ if(settingInfo[key]){
58
+ const [label,description]=settingInfo[key];console.log('\n'+description);
59
+ const v=await choose(lines,label,[{value:false,label:'Off',description:key==='autoApprove'?'Ask before applying file changes and running verification commands.':'Disable this setting.'},{value:true,label:'On',description}],session[key],session.theme);
60
+ if(v!==null){session[key]=v;setPreference(key,v);}
61
+ }else if(key==='theme'){
62
+ const v=await choose(lines,'Header colours',[{value:'cyan',label:'Cyan & white',description:'Cyan frame, bright title and subtle version.'},{value:'violet',label:'Violet & white',description:'Violet frame, bright title and subtle version.'},{value:'plain',label:'No colour',description:'Plain text for terminals and accessibility.'}],session.theme,session.theme);
63
+ if(v!==null){session.theme=v;setPreference('theme',v);banner(process.stdout,v);}
64
+ }else if(key==='model'){
65
+ const v=await selectModel(lines,session.model,{theme:session.theme});if(v!==null){disableProvider(session);session.model=v;setPreference('model',v);}
66
+ }
67
+ }
68
+ }
69
+ export async function accountMenu(lines,theme='cyan',session){
70
+ while(true){
71
+ heading('Account & API',theme);
72
+ const a=await choose(lines,'Choose an account action',[
73
+ {value:'login',label:'Sign in with a Vigthoria account',description:'Your password is entered privately.'},
74
+ {value:'key',label:'Connect a CLI API key',description:'Enter a scoped Vigthoria CLI key privately; never a model-provider key.'},
75
+ {value:'providers',label:'Provider API keys (OpenAI, Anthropic, OpenRouter)',description:'Connect your own provider account and choose planning and coding models.'},
76
+ {value:'test',label:'Test API connection',description:'Check authentication, models and the agent. No generation request is started.'},
77
+ {value:'keys',label:'List my CLI API keys',description:'Show key names, expiry and revocation status; secrets are never displayed.'},
78
+ {value:'back',label:'Back',description:'Return to the previous menu.'},
79
+ ],'test',theme);
80
+ if(a===null||a==='back')return;
81
+ try{
82
+ if(a==='providers')await providerMenu(lines,theme,session);
83
+ if(a==='login'){const {login}=await import('./account.mjs');await login([]);}
84
+ if(a==='key'||a==='keys'){const {apiKeys}=await import('./api-keys.mjs');await apiKeys([a==='key'?'login':'list']);}
85
+ if(a==='test'){const {diagnostics}=await import('./diagnostics.mjs');await diagnostics({checkApi:true});}
86
+ }catch(e){console.log('Account action failed: '+safe(e.message));}
87
+ }
88
+ }
89
+ const directory=s=>{s=s.trim().replace(/^(["'])(.*)\1$/,'$2');if(s==='~'||s.startsWith('~/'))s=path.join(os.homedir(),s.slice(2));return path.resolve(s);};
90
+ export async function setup(lines,argv=[]){
91
+ const p=preferences();const session={...p,root:configuredRoot(argv),autoApprove:argv.includes('--auto-approve')||p.autoApprove,autoSave:!argv.includes('--no-save')&&!argv.includes('--no-auto-save')&&p.autoSave,debugMode:argv.includes('--debug')||p.debugMode};
92
+ const mi=argv.findIndex(v=>v==='--model'||v==='-m');if(mi>=0){session.providerEnabled=false;if(!argv[mi+1])throw Error('--model requires a model');session.model=argv[mi+1];}
93
+ if(!process.stdin.isTTY||!process.stdout.isTTY||argv.includes('--no-setup')||argv.includes('--prompt')||argv.includes('-p')||argv.includes('--command-json'))return session;
94
+ if(process.env.VIGTHORIA_DECK_MODE==='1'){if(process.env.VIGTHORIA_NO_BANNER!=='1')banner(process.stdout,session.theme);return session;}
95
+ if(p.workspacePath&&!argv.includes('--workspace')&&!argv.includes('-w')){try{session.root=fs.realpathSync(p.workspacePath);if(!fs.statSync(session.root).isDirectory())throw Error();}catch{console.log('Saved workspace is unavailable. Using the current directory.');session.root=configuredRoot(argv);}}
96
+ if(process.env.VIGTHORIA_NO_BANNER!=='1')banner(process.stdout,session.theme);
97
+ async function answer(prompt){const r=await lines.next(prompt);return r.done||r.cancelled?null:r.value.trim();}
98
+ while(true){
99
+ heading('Agent Session Setup',session.theme);
100
+ detail('Project',safe(session.root),session.theme);
101
+ detail('AI',routingLabel(session)||modelLabel(session.model),session.theme);
102
+ console.log('File changes: '+(session.autoApprove?'Apply automatically':'Ask before applying')+' · Save sessions: '+onOff(session.autoSave)+' · Debug: '+onOff(session.debugMode));
103
+ const a=await choose(lines,'What would you like to do?',[
104
+ {value:'start',label:'Start agent',description:'Start a conversation in the workspace shown above.'},
105
+ {value:'workspace',label:'Choose an existing workspace',description:'Select the project folder the agent should work on.'},
106
+ {value:'create',label:'Create a workspace',description:'Create a new project folder and use it for this session.'},
107
+ {value:'model',label:'Choose AI model',description:'Automatic routing, available cloud models and the hosted Assistant 9B.'},
108
+ {value:'settings',label:'Session settings',description:'Debug logging, saved sessions, file approvals and header colours.'},
109
+ {value:'account',label:'Account & API',description:'Sign in, connect a provider key or CLI key, or test the connection.'},
110
+ {value:'guide',label:'Browse commands & capabilities',description:'Read grouped command help without leaving this setup.'},
111
+ {value:'exit',label:'Exit',description:'Close setup without starting an agent.'},
112
+ ],'start',session.theme);
113
+ if(a===null||a==='exit')return null;
114
+ if(a==='start'){
115
+ let ready=false;
116
+ while(true){
117
+ try{const issue=workspaceIssue(session.root);if(issue)throw Error(issue);const index=projectInventory(session.root);notice('success',index.files.length+' source files available · large projects are read as needed.',session.theme);ready=true;break;}
118
+ catch(e){notice('warning',e.message,session.theme);const entered=await answer('Project folder: ');if(!entered)break;try{const root=directory(entered);if(!fs.statSync(root).isDirectory())throw Error('Choose a directory.');session.root=fs.realpathSync(root);setPreference('workspacePath',session.root);}catch(error){notice('error','Project not changed: '+error.message,session.theme);}}
119
+ }
120
+ if(ready)break;
121
+ continue;
122
+ }
123
+ if(a==='workspace'||a==='create'){
124
+ console.log(a==='create'?'Enter the full path of the new project folder.':'Enter a project folder path. Press Enter to keep the current workspace.');
125
+ const entered=await answer(a==='create'?'New workspace path: ':'Workspace path: ');if(entered===null)continue;if(!entered&&a==='workspace')continue;
126
+ try{if(!entered)throw Error('Enter a folder path.');let root=directory(entered);if(a==='create'){if(fs.existsSync(root))throw Error('That folder exists. Use Choose an existing workspace.');fs.mkdirSync(root,{recursive:true,mode:0o700});}root=fs.realpathSync(root);if(!fs.statSync(root).isDirectory())throw Error('Select a folder, not a file.');session.root=root;setPreference('workspacePath',root);}
127
+ catch(e){console.log('Workspace not changed: '+safe(e.message));}
128
+ }else if(a==='settings')await settingsMenu(lines,session);
129
+ else if(a==='model'){const v=await selectModel(lines,session.model,{theme:session.theme});if(v!==null){disableProvider(session);session.model=v;setPreference('model',v);}}
130
+ else if(a==='account')await accountMenu(lines,session.theme,session);
131
+ else if(a==='guide'){const {commandMenu}=await import('./catalog.mjs');await commandMenu(lines,{guideOnly:true});}
132
+ }
133
+ return session;
134
+ }
@@ -0,0 +1,13 @@
1
+ /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {createHash,createPublicKey,verify} from 'node:crypto';
7
+ import {spawnSync} from 'node:child_process';
8
+ import {VERSION} from './terminal.mjs';
9
+ const origin='https://extension.vigthoria.io';
10
+ const key=createPublicKey({key:Buffer.from('302a300506032b6570032100c338cab09089845dfced93db42819372226d38bc89157a78ce938aaeb8509bc2','hex'),format:'der',type:'spki'});
11
+ async function download(url,limit){const u=new URL(url);if(u.origin!==origin||!u.pathname.startsWith('/downloads/')||u.search||u.hash)throw Error('Untrusted release URL');const r=await fetch(u,{redirect:'error',signal:AbortSignal.timeout(30000)});if(!r.ok)throw Error('Release download failed ('+r.status+')');let bytes=0;const chunks=[];for await(const c of r.body){bytes+=c.length;if(bytes>limit)throw Error('Release download exceeds size limit');chunks.push(c);}return Buffer.concat(chunks);}
12
+ export function verifyRelease(bytes,signature){const sig=Buffer.from(String(signature).trim(),'base64');if(sig.length!==64||!verify(null,bytes,key,sig))throw Error('Vigthoria release signature mismatch');}
13
+ export async function update(argv=[]){const bytes=await download(origin+'/downloads/manifest.json',2000000);verifyRelease(bytes,(await download(origin+'/downloads/manifest.json.ed25519.sig',256)).toString());const release=JSON.parse(bytes).channels?.stable;if(!release||!/^\d+\.\d+\.\d+$/.test(release.version)||!Number.isSafeInteger(release.size)||release.size<1||release.size>5000000||!/^[a-f0-9]{64}$/.test(release.sha256))throw Error('Invalid signed CLI release');console.log('Installed: '+VERSION+'; stable: '+release.version);const newer=release.version.split('.').reduce((n,v,i)=>n||Math.sign(Number(v)-Number(VERSION.split('.')[i])),0)>0;if(argv.includes('--check')||!newer)return;if(process.env.VIGTHORIA_DECK_MODE==='1')throw Error('Update the managed CLI through Workbench Settings → Repair verified CLI.');const archive=await download(release.url,release.size);if(archive.length!==release.size||createHash('sha256').update(archive).digest('hex')!==release.sha256)throw Error('Release checksum mismatch');verifyRelease(archive,(await download(release.url+'.ed25519.sig',256)).toString());const temp=fs.mkdtempSync(path.join(os.tmpdir(),'vigthoria-cli-update-'));try{const file=path.join(temp,'vigthoria-cli-'+release.version+'.tgz');fs.writeFileSync(file,archive,{mode:0o600});const i=argv.indexOf('--prefix');let prefix=i>=0?argv[i+1]:null;if(!prefix){const parts=fileURLToPath(import.meta.url).split(path.sep),n=parts.lastIndexOf('node_modules');prefix=n>0?parts.slice(0,parts[n-1]==='lib'?n-1:n).join(path.sep):path.join(os.homedir(),'.local');}if(!prefix||!path.isAbsolute(prefix))throw Error('--prefix requires an absolute install prefix');let executable='npm',args=['install','--global','--ignore-scripts','--no-audit','--no-fund','--prefix',prefix,file];if(process.platform==='win32'){const npm=path.join(path.dirname(process.execPath),'node_modules/npm/bin/npm-cli.js');if(!fs.existsSync(npm))throw Error('Use the verified Windows installer to update this runtime.');executable=process.execPath;args=[npm,...args];}const r=spawnSync(executable,args,{stdio:'inherit',shell:false});if(r.status!==0)throw Error('Verified CLI installation failed');console.log('Installed verified Vigthoria CLI '+release.version+'. Reopen the terminal.');}finally{fs.rmSync(temp,{recursive:true,force:true});}}
@@ -0,0 +1,12 @@
1
+ /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
+ import {accessToken} from './account.mjs';
3
+ import {parse} from './commands.mjs';
4
+ async function transport(route,{token=accessToken(),body,method=body?'POST':'GET'}={}){const response=await fetch('https://workflow.vigthoria.io/api/'+route,{method,redirect:'error',signal:AbortSignal.timeout(120000),headers:{Authorization:'Bearer '+token,'Content-Type':'application/json',Accept:'application/json'},...(body?{body:JSON.stringify(body)}:{})});let bytes=0;const chunks=[];for await(const c of response.body){bytes+=c.length;if(bytes>2000000)throw Error('Workflow response exceeds transport limit');chunks.push(c);}let d;try{d=JSON.parse(Buffer.concat(chunks).toString());}catch{throw Error('Workflow service returned an invalid response ('+response.status+')');}if(!response.ok)throw Object.assign(Error(d.message||d.error||'Workflow request failed'),{status:response.status,code:d.code});return d;}
5
+ export async function workflow(argv=[]){const [action='list',...rest]=argv;const {args,options}=parse(rest,['--name','--variables','--data','--category','--search'],['--json','--yes']);const sso=await transport('auth/sso',{body:{}});if(!sso.token)throw Error('Workflow sign-in did not issue a service token');const token=sso.token,call=(route,o={})=>transport(route,{...o,token});const print=d=>console.log(JSON.stringify(d,null,2));const id=s=>{if(!s||s.length>200)throw Error('Select a workflow or execution id');return encodeURIComponent(s);};
6
+ if(action==='templates'){const q=new URLSearchParams();for(const k of ['category','search'])if(options[k])q.set(k,options[k]);return print(await call('templates'+(q.size?'?'+q:'')));}
7
+ if(action==='list')return print(await call('workflows'));
8
+ if(action==='status')return print(await call('executions/'+id(args[0])));
9
+ if(action==='use')return print(await call('templates/'+id(args[0])+'/use',{body:{name:options.name,variables:options.variables?JSON.parse(options.variables):{}}}));
10
+ if(action==='run')return print(await call('executions/run/'+id(args[0]),{body:{data:options.data?JSON.parse(options.data):{},options:{}}}));
11
+ if(action==='delete'){if(!options.yes)throw Error('Use workflow delete ID --yes');return print(await call('workflows/'+id(args[0]),{method:'DELETE'}));}
12
+ throw Error('Use workflow templates, list, use, run, status or delete.');}
@@ -0,0 +1,83 @@
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
+ }
@@ -0,0 +1,55 @@
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{}}}