vigthoria-cli 0.0.0-stage → 2.3.7
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/LICENSE +3 -0
- package/README.md +102 -2
- package/package.json +24 -4
- package/public-dist/account.mjs +38 -0
- package/public-dist/agent.mjs +48 -0
- package/public-dist/api-keys.mjs +14 -0
- package/public-dist/catalog.mjs +121 -0
- package/public-dist/commands.mjs +49 -0
- package/public-dist/continuity.mjs +12 -0
- package/public-dist/deck-channel.mjs +16 -0
- package/public-dist/diagnostics.mjs +8 -0
- package/public-dist/index.mjs +81 -0
- package/public-dist/local-tools.mjs +28 -0
- package/public-dist/preferences.mjs +13 -0
- package/public-dist/presentation.mjs +17 -0
- package/public-dist/providers.mjs +111 -0
- package/public-dist/repl-input.mjs +146 -0
- package/public-dist/repository.mjs +14 -0
- package/public-dist/session-state.mjs +11 -0
- package/public-dist/task-progress.mjs +61 -0
- package/public-dist/terminal.mjs +133 -0
- package/public-dist/update.mjs +13 -0
- package/public-dist/workflows.mjs +12 -0
- package/public-dist/workspace-tools.mjs +83 -0
- package/public-dist/workspace.mjs +55 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
3
|
+
import {readFile} from 'node:fs/promises';
|
|
4
|
+
import {realpathSync} from 'node:fs';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {login,logout,request} from './account.mjs';
|
|
7
|
+
import {agent} from './agent.mjs';
|
|
8
|
+
import {repository} from './repository.mjs';
|
|
9
|
+
import {providerCommand,disableProvider} from './providers.mjs';
|
|
10
|
+
import {apiKeys} from './api-keys.mjs';
|
|
11
|
+
import {diagnostics,models} from './diagnostics.mjs';
|
|
12
|
+
import {preferences,setPreference} from './preferences.mjs';
|
|
13
|
+
import {banner,VERSION,settingsMenu,selectModel} from './terminal.mjs';
|
|
14
|
+
import {commandHelp,commandMenu,commandGroups,normalizeArgv,capabilityCatalog} from './catalog.mjs';
|
|
15
|
+
import {replInput} from './repl-input.mjs';
|
|
16
|
+
import {taskCommand,background,history,replay,cancel,services} from './commands.mjs';
|
|
17
|
+
import {update} from './update.mjs';
|
|
18
|
+
import {device,projectScript} from './local-tools.mjs';
|
|
19
|
+
import {workflow} from './workflows.mjs';
|
|
20
|
+
const version=VERSION;
|
|
21
|
+
const commands={status:'vigthoria_memory_status',checkpoint:'vigthoria_memory_checkpoint',compact:'vigthoria_memory_checkpoint',recall:'vigthoria_memory_recall',export:'vigthoria_memory_export',delete:'vigthoria_memory_delete'};
|
|
22
|
+
async function inputJson(){let size=0;const chunks=[];for await(const chunk of process.stdin){size+=chunk.length;if(size>2000000)throw Error('Input exceeds 2 MB');chunks.push(chunk);}return chunks.length?JSON.parse(Buffer.concat(chunks).toString('utf8')):{};}
|
|
23
|
+
export function help(command=''){
|
|
24
|
+
const text=commandHelp;
|
|
25
|
+
if(command&&text[command]){console.log('Usage: vigthoria '+text[command]);return;}
|
|
26
|
+
if(command&& !['help','commands','menu'].includes(command))throw Error('Unknown command: '+command);
|
|
27
|
+
console.log('Vigthoria CLI '+version+' — AI-Powered Coding Assistant\n\n'+commandGroups.map(g=>g.label+':\n '+g.names.join(', ')).join('\n\n')+'\n\nUse vigthoria menu for guided commands, or vigthoria COMMAND --help.\nCore planning and execution stay on Vigthoria servers.\nCopyright (c) 2026 Vigthoria Technologies. All rights reserved.');
|
|
28
|
+
}
|
|
29
|
+
export async function run(argv=process.argv.slice(2)){
|
|
30
|
+
argv=normalizeArgv(argv);
|
|
31
|
+
if((!argv.length&&process.stdin.isTTY&&process.stdout.isTTY)||(argv[0]==='menu'&&!argv.includes('--help')&&!argv.includes('-h'))){if(!process.stdin.isTTY||!process.stdout.isTTY)return help('menu');const lines=replInput();let selected;try{selected=await commandMenu(lines);}finally{lines.close();}if(selected)return run(selected);return;}
|
|
32
|
+
if(argv[0]==='--version'||argv[0]==='-V'){console.log(version);return;}
|
|
33
|
+
if(!argv.length||argv[0]==='--help'||argv[0]==='help'||argv.includes('--help')||argv.includes('-h')){help(argv[0]==='help'?argv[1]||'':argv[0]?.startsWith('-')?'':argv[0]||'');return;}
|
|
34
|
+
const [name,...args]=argv;
|
|
35
|
+
if(name==='commands'){if(args.includes('--json'))return console.log(JSON.stringify({version,...capabilityCatalog()},null,2));return help();}
|
|
36
|
+
if(name==='auth')return help('auth');
|
|
37
|
+
if(name==='login')return login(args);
|
|
38
|
+
if(name==='logout')return logout();
|
|
39
|
+
if(name==='agent'||name==='chat')return agent(args);
|
|
40
|
+
if(name==='chat-resume'){if(!args[0])throw Error('Use chat-resume SESSION_ID');return agent(['--resume',args[0],...args.slice(1)]);}
|
|
41
|
+
if(name==='repo')return repository(args);
|
|
42
|
+
if(name==='provider')return providerCommand(args);
|
|
43
|
+
if(name==='devtools'&&['setup','roles'].includes(args[0]))return args[0]==='setup'?providerCommand(['setup']):console.log(JSON.stringify({billing:preferences().providerEnabled?'your_provider_account':'vigthoria_account',...preferences()},null,2));
|
|
44
|
+
if(name==='api-key'||name==='keys')return apiKeys(args);
|
|
45
|
+
if(name==='doctor')return diagnostics({checkApi:args.includes('--check-api'),json:args.includes('--json')});
|
|
46
|
+
if(name==='models')return models({json:args.includes('--json')});
|
|
47
|
+
if(name==='api'){if(args[0]==='models')return models({json:args.includes('--json')});if(!args.length||['status','test'].includes(args[0]))return diagnostics({checkApi:true,json:args.includes('--json')});throw Error('Use api status, test or models.');}
|
|
48
|
+
if(name==='config'){const [action,key,value]=args;const d=preferences();if(action==='setup'||action==='model'){if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error('Interactive settings require a terminal. Use config set KEY VALUE.');const lines=replInput();try{if(action==='setup')await settingsMenu(lines,d);else{const chosen=await selectModel(lines,d.model,{theme:d.theme});if(chosen!==null){disableProvider();setPreference('model',chosen);}}}finally{lines.close();}return;}if(!action||action==='show'){console.log(JSON.stringify(d,null,2));return;}if(action==='get'&&Object.hasOwn(d,key)){console.log(typeof d[key]==='string'?d[key]:JSON.stringify(d[key]));return;}if(action==='set'&&value!==undefined){setPreference(key,value);if(key==='model')disableProvider();console.log(key+' saved.');return;}throw Error('Use config show, get KEY or set KEY VALUE.');}
|
|
49
|
+
if(name==='status'||name==='whoami'){console.log(JSON.stringify(await request('/api/user/subscription'),null,2));return;}
|
|
50
|
+
if(name==='game'&&['run','validate'].includes(args[0]))return projectScript(args[0],args.slice(1));
|
|
51
|
+
if(['edit','fix','explain','review','generate','security','init','creative','game','e','f','x','r','g'].includes(name))return taskCommand(name,args);
|
|
52
|
+
if(name==='device')return device(args);
|
|
53
|
+
if(name==='workflow')return workflow(args);
|
|
54
|
+
if(name==='preview')return projectScript('run',args);
|
|
55
|
+
if(name==='fork'){if(!args[0])throw Error('Use fork RUN_ID [MESSAGE]');return agent(['--no-setup','--fork',args[0],'--prompt',args.slice(1).join(' ')||'Continue this run.']);}
|
|
56
|
+
if(name==='background')return background(args);
|
|
57
|
+
if(name==='history')return history(args);
|
|
58
|
+
if(name==='replay')return replay(args[0]);
|
|
59
|
+
if(name==='cancel')return cancel(args[0]);
|
|
60
|
+
if(name==='operator'&&args[0]!=='status')return agent(args);
|
|
61
|
+
if(['operator','deploy','wallet','hyper-loop','devtools','bridge','music'].includes(name))return services(name,args);
|
|
62
|
+
if(name==='update')return update(args);
|
|
63
|
+
if(name!=='memory')throw Error('Unknown command: '+name+'. Use vigthoria --help.');
|
|
64
|
+
const [family,command,project,...extra]=argv;
|
|
65
|
+
if(family!=='memory'||!commands[command]||!project||extra.length)throw new Error('Use: vigthoria memory <command> <project_id>. See --help.');
|
|
66
|
+
if(!/^[a-zA-Z0-9_.:-]{1,128}$/.test(project))throw new Error('Invalid project_id');
|
|
67
|
+
const token=process.env.VIGTHORIA_CONTINUITY_TOKEN_FILE?(await readFile(process.env.VIGTHORIA_CONTINUITY_TOKEN_FILE,'utf8')).trim():process.env.VIGTHORIA_CONTINUITY_TOKEN;
|
|
68
|
+
if(!token)throw new Error('Connect your Vigthoria Continuity account using a host-managed credential.');
|
|
69
|
+
const memoryArgs=command==='status'?{}:await inputJson();
|
|
70
|
+
if(memoryArgs.project_id && memoryArgs.project_id!==project)throw new Error('Conflicting project_id');
|
|
71
|
+
memoryArgs.project_id=project;if(command==='compact')memoryArgs.force_compact=true;
|
|
72
|
+
const endpoint=`https://coder.vigthoria.io/continuity/v1/tools/${commands[command]}`;
|
|
73
|
+
// Fixed HTTPS origin; redirects are refused so credentials cannot leave Vigthoria.
|
|
74
|
+
const response=await fetch(endpoint,{method:'POST',redirect:'error',signal:AbortSignal.timeout(30000),headers:{Authorization:`Bearer ${token}`,'Content-Type':'application/json'},body:JSON.stringify(memoryArgs)});
|
|
75
|
+
const limit=command==='export'?150000000:256000;const reader=response.body.getReader();let length=0;const chunks=[];
|
|
76
|
+
try{while(true){const{value,done}=await reader.read();if(done)break;length+=value.length;if(length>limit)throw new Error('Response exceeds the transport limit');chunks.push(Buffer.from(value));}}finally{await reader.cancel();}
|
|
77
|
+
const text=Buffer.concat(chunks).toString('utf8');const result=JSON.parse(text);
|
|
78
|
+
if(!response.ok)throw new Error(result.error||`Continuity request failed (${response.status})`);
|
|
79
|
+
console.log(JSON.stringify(result,null,2));
|
|
80
|
+
}
|
|
81
|
+
if(process.argv[1]&&fileURLToPath(import.meta.url)===realpathSync(process.argv[1]))run().catch(error=>{console.error((error.code?error.code+': ':'')+error.message);process.exitCode=1;});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {spawn,spawnSync} from 'node:child_process';
|
|
5
|
+
import {parse} from './commands.mjs';
|
|
6
|
+
import {configuredRoot} from './preferences.mjs';
|
|
7
|
+
export async function projectScript(action,argv=[]){const {options}=parse(argv,['--workspace','--port','--package-manager'],['--no-open']);const root=configuredRoot(options.workspace?['--workspace',options.workspace]:[]),pkg=JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8'));const manager=options['package-manager']||'npm';if(!['npm','pnpm','yarn','bun'].includes(manager))throw Error('Select npm, pnpm, yarn or bun');const script=action==='validate'?'build':pkg.scripts?.dev?'dev':'start';if(!pkg.scripts?.[script])throw Error('No '+script+' script exists in this project');const args=['run',script];if(action!=='validate'&&options.port){if(!/^\d{2,5}$/.test(options.port)||Number(options.port)>65535)throw Error('Invalid port');args.push('--','--port',options.port);}let executable=manager;if(process.platform==='win32'&&manager==='npm'){const npm=path.join(path.dirname(process.execPath),'node_modules/npm/bin/npm-cli.js');if(!fs.existsSync(npm))throw Error('Install Node.js with npm to run project scripts.');executable=process.execPath;args.unshift(npm);}await new Promise((resolve,reject)=>{const child=spawn(executable,args,{cwd:root,stdio:'inherit',shell:false});child.once('error',reject);child.once('close',code=>{if(code!==0)process.exitCode=code||1;resolve();});});}
|
|
8
|
+
export async function device(argv=[]){const [action='status',...rest]=argv;const {args,options}=parse(rest,['--device','--output','--activity','--lines','--port'],['--follow','--json']);const prefix=options.device?['-s',options.device]:[];let tail;
|
|
9
|
+
if(['status','list'].includes(action))tail=['devices','-l'];
|
|
10
|
+
else if(action==='connect'||action==='disconnect'){if(args[0]&&!/^[A-Za-z0-9_.:[\]-]{1,253}$/.test(args[0]))throw Error('Invalid device address');tail=[action,...args.slice(0,1)];}
|
|
11
|
+
else if(action==='tcpip'){const port=options.port||'5555';if(!/^\d{2,5}$/.test(port)||+port>65535)throw Error('Invalid port');tail=['tcpip',port];}
|
|
12
|
+
else if(action==='install'){if(!args[0])throw Error('Use device install APK');tail=['install','-r',path.resolve(args[0])];}
|
|
13
|
+
else if(action==='launch'){if(!/^[A-Za-z][A-Za-z0-9_.]{1,200}$/.test(args[0]||''))throw Error('Invalid Android package');tail=options.activity?['shell','am','start','-n',args[0]+'/'+options.activity]:['shell','monkey','-p',args[0],'-c','android.intent.category.LAUNCHER','1'];if(options.activity&&!/^[A-Za-z0-9_.$]{1,200}$/.test(options.activity))throw Error('Invalid activity');}
|
|
14
|
+
else if(action==='logs'){const lines=options.lines||'250';if(!/^\d{1,5}$/.test(lines))throw Error('Invalid log count');tail=['logcat',...(options.follow?[]:['-d','-t',lines])];}
|
|
15
|
+
else if(action==='screenshot'){const file=path.resolve(options.output||'android-screenshot.png'),r=spawnSync('adb',[...prefix,'exec-out','screencap','-p'],{maxBuffer:20*1024*1024,timeout:30000});if(r.error)throw r.error;if(r.status!==0)throw Error(r.stderr.toString());fs.writeFileSync(file,r.stdout,{flag:'wx',mode:0o600});console.log(file);return;}
|
|
16
|
+
else throw Error('Use device status, list, screenshot, install, launch, logs, tcpip, connect or disconnect.');
|
|
17
|
+
await new Promise((resolve,reject)=>{const child=spawn('adb',[...prefix,...tail],{stdio:'inherit',shell:false});child.once('error',e=>reject(Error(e.code==='ENOENT'?'Install Android platform-tools to use device commands.':e.message)));child.once('close',code=>{if(code!==0)process.exitCode=code||1;resolve();});});}
|
|
18
|
+
|
|
19
|
+
export async function bridgeStatus({fetcher=fetch}={}){
|
|
20
|
+
const ports=[['DevTools Bridge',process.env.VIGTHORIA_DEVTOOLS_BRIDGE_PORT||'4016'],['Desktop Bridge',process.env.VIGTHORIA_DESKTOP_PORT||'49160']];
|
|
21
|
+
const bridges=await Promise.all(ports.map(async([name,port])=>{
|
|
22
|
+
if(!/^\d{1,5}$/.test(port)||+port<1||+port>65535)throw Error('Invalid local bridge port');
|
|
23
|
+
const endpoint='http://127.0.0.1:'+port+'/health';
|
|
24
|
+
try{const r=await fetcher(endpoint,{method:'GET',redirect:'error',signal:AbortSignal.timeout(3000),headers:{Accept:'application/json'}});if(!r.ok)return {name,reachable:false,status:'HTTP '+r.status};let size=0,text='';for await(const c of r.body){size+=c.length;if(size>4096)throw Error('Unexpected bridge health response');text+=Buffer.from(c).toString('utf8');}const d=JSON.parse(text);return {name,reachable:true,service:typeof d.service==='string'?d.service:undefined,version:typeof d.version==='string'?d.version:undefined,controlEnabled:d.controlEnabled===true||d.control_enabled===true};}
|
|
25
|
+
catch(e){return {name,reachable:false,status:e.name==='TimeoutError'?'Not responding':'Not running or unavailable'};}
|
|
26
|
+
}));
|
|
27
|
+
console.log(JSON.stringify({location:'this machine',bridges},null,2));return bridges;
|
|
28
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import {configDirectory} from './account.mjs';
|
|
2
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {randomUUID} from 'node:crypto';
|
|
7
|
+
const filename=()=>path.join(configDirectory(),'cli-settings.json');
|
|
8
|
+
export const defaults={workspacePath:'',model:'agent',debugMode:false,autoApprove:false,autoSave:true,theme:'cyan',providerEnabled:false,providerKeyId:'',providerPlannerModel:'',providerExecutorModel:''};
|
|
9
|
+
export function preferences(){try{const d=JSON.parse(fs.readFileSync(filename(),'utf8'));return {...defaults,...Object.fromEntries(Object.entries(d).filter(([k])=>Object.hasOwn(defaults,k)))};}catch(e){if(e.code==='ENOENT')return {...defaults};throw Error('CLI settings are unreadable; inspect '+filename());}}
|
|
10
|
+
export function setPreference(key,value){if(!Object.hasOwn(defaults,key))throw Error('Supported settings: '+Object.keys(defaults).join(', '));if(typeof defaults[key]==='boolean'){if(value==='true')value=true;if(value==='false')value=false;if(typeof value!=='boolean')throw Error(key+' must be true or false');}else if(typeof value!=='string'||value.length>4096||/[\x00-\x1f]/.test(value))throw Error('Invalid setting value');if(key==='providerKeyId'&&value&&!/^pkey_[a-f0-9]{32}$/.test(value))throw Error('Invalid provider key ID');if(['providerPlannerModel','providerExecutorModel'].includes(key)&&value&&!/^[A-Za-z0-9][A-Za-z0-9._:/+\-]{0,199}$/.test(value))throw Error('Invalid provider model ID');if(key==='theme'&&!['cyan','violet','plain'].includes(value))throw Error('Choose theme cyan, violet or plain');if(key==='model'&&!/^[A-Za-z0-9._:-]{1,128}$/.test(value))throw Error('Invalid model ID; use the AI model picker');if(key==='workspacePath'&&value){value=fs.realpathSync(path.resolve(value));if(!fs.statSync(value).isDirectory())throw Error('Select an existing project directory');}const d={...preferences(),[key]:value},file=filename();fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});const temp=file+'.'+randomUUID()+'.tmp';fs.writeFileSync(temp,JSON.stringify(d,null,2)+'\n',{mode:0o600,flag:'wx'});fs.renameSync(temp,file);return d;}
|
|
11
|
+
export function configuredRoot(argv=[]){const i=argv.findIndex(a=>a==='--workspace'||a==='-w');if(i>=0&&!argv[i+1])throw Error('--workspace requires a directory');const root=i>=0?argv[i+1]:process.cwd();const real=fs.realpathSync(path.resolve(root));if(!fs.statSync(real).isDirectory())throw Error('Workspace must be a directory');return real;}
|
|
12
|
+
|
|
13
|
+
export function resolveWorkspace(value){value=String(value||'').trim().replace(/^(["'])(.*)\1$/,'$2');if(value==='~'||value.startsWith('~/'))value=path.join(os.homedir(),value.slice(2));const real=fs.realpathSync(path.resolve(value));if(!fs.statSync(real).isDirectory())throw Error('Choose a project directory.');return real;}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
2
|
+
const clean=s=>String(s??'').replace(/[\x00-\x1f\x7f-\x9f]/g,'');
|
|
3
|
+
const tones={title:'1;97',accent:'1;38;5;117',muted:'38;5;245',success:'38;5;114',warning:'38;5;222',error:'38;5;210'};
|
|
4
|
+
export function paint(value,tone='accent',theme='cyan',out=process.stdout){const text=clean(value);if(!out.isTTY||theme==='plain'||Object.hasOwn(process.env,'NO_COLOR')||process.env.TERM==='dumb')return text;const code=tone==='accent'&&theme==='violet'?'1;38;5;183':tones[tone]||tones.accent;return '\x1b['+code+'m'+text+'\x1b[0m';}
|
|
5
|
+
export function section(title,subtitle='',theme='cyan'){console.log('\n'+paint(title,'title',theme));if(subtitle)console.log(paint(subtitle,'muted',theme));}
|
|
6
|
+
export function detail(label,value,theme='cyan'){console.log(paint(label+' ','muted',theme)+paint(value,'accent',theme));}
|
|
7
|
+
export function notice(kind,message,theme='cyan'){const prefix=({success:'✓',warning:'!',error:'×',info:'›'}[kind]||'›');const lines=String(message??'').split(/\r?\n/);(kind==='error'?console.error:console.log)(lines.map((line,index)=>paint((index?' ':prefix+' ')+line,kind==='info'?'accent':kind,theme)).join('\n'));}
|
|
8
|
+
export function modelName(id){const value=clean(id);const match=value.match(/^(?:openai\/)?gpt-(\d+(?:\.\d+)?)-(astra|sol|terra|luna)(.*)$/i);if(match)return 'GPT-'+match[1]+' '+match[2][0].toUpperCase()+match[2].slice(1)+(match[3]?' · '+match[3].replace(/^-/,''):'');if(/^gpt-/i.test(value))return value.replace(/^gpt-/i,'GPT-');if(/^claude-/i.test(value))return value.replace(/^claude-/i,'Claude ').replaceAll('-',' ');return value;}
|
|
9
|
+
export function visibleModelName(id,ownProvider=false){const value=clean(id);return !ownProvider&&(/vigthoria-cloud|vigthoria-general-v4|vigthoria-v4(?:\.[23])?-(?:code|creative)-(?:27|30|31)b/i.test(value)||value.includes('/')||/^(?:gpt-|claude-|deepseek|qwen|glm|kimi|gemini)/i.test(value))?'Vigthoria Cloud':modelName(value);}
|
|
10
|
+
const cloudProfiles={fast:'Fast replies','balanced-v2':'Balanced work',premium:'Advanced work',balanced:'Balanced work',code:'Code editing',power:'Large tasks',maximum:'Complex work',astra:'Advanced reasoning',sol:'Planning and coding',terra:'Visual understanding',luna:'Quick tasks',opus:'Advanced work',sonnet:'Balanced work',fable:'Creative work','director-gemini':'Creative direction','general-v4':'Automatic planning','micro-recovery':'Recovery','coder-agent':'Code edits','creative-v4':'Creative planning'};
|
|
11
|
+
export const cloudProfile=id=>cloudProfiles[String(id).replace(/^vigthoria-cloud-/,'')]||'Cloud assistance';
|
|
12
|
+
export function providerModelChoices(models=[]){
|
|
13
|
+
const version=id=>{const m=id.match(/(?:^|\/)gpt-(\d+)(?:\.(\d+))?/i);return m?Number(m[1])*100+Number(m[2]||0):0;};
|
|
14
|
+
return models.filter(m=>typeof m.id==='string'&&!/(?:^|\/)(?:gpt-live|gpt-audio|gpt-realtime)/i.test(m.id)).slice().sort((a,b)=>version(b.id)-version(a.id)||Number(/-\d{4}-\d{2}-\d{2}$/.test(a.id))-Number(/-\d{4}-\d{2}-\d{2}$/.test(b.id))||a.id.localeCompare(b.id,undefined,{numeric:true})).map(m=>({value:m.id,label:modelName(m.id),description:clean(m.id)}));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function renderText(text,theme='cyan'){for(const line of String(text??'').split('\n')){const cleaned=clean(line);console.log(/^#{1,3}\s/.test(cleaned)?paint(cleaned.replace(/^#{1,3}\s/,''),'title',theme):cleaned);}}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
2
|
+
import {request,hiddenInput,accessToken} from './account.mjs';
|
|
3
|
+
import {preferences,setPreference} from './preferences.mjs';
|
|
4
|
+
import {choose,safe} from './terminal.mjs';
|
|
5
|
+
import {section,detail,notice,modelName,providerModelChoices} from './presentation.mjs';
|
|
6
|
+
import {replInput} from './repl-input.mjs';
|
|
7
|
+
const base='/api/v3-agent-cli/providers';
|
|
8
|
+
const providers={openai:'OpenAI',anthropic:'Anthropic',openrouter:'OpenRouter'};
|
|
9
|
+
const keyId=id=>{if(!/^pkey_[a-f0-9]{32}$/.test(id||''))throw Error('Choose a saved provider key.');return id;};
|
|
10
|
+
const modelId=id=>{if(typeof id!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._:/+\-]{0,199}$/.test(id))throw Error('Choose a model from provider models KEY_ID.');return id;};
|
|
11
|
+
const print=data=>console.log(JSON.stringify(data,null,2));
|
|
12
|
+
export function providerRoute(settings=preferences()){
|
|
13
|
+
if(!settings.providerEnabled)return null;
|
|
14
|
+
return {enabled:true,keyId:keyId(settings.providerKeyId),plannerModel:modelId(settings.providerPlannerModel),executorModel:modelId(settings.providerExecutorModel)};
|
|
15
|
+
}
|
|
16
|
+
export function routingLabel(settings){return settings.providerEnabled?'Your provider · Plan: '+modelName(settings.providerPlannerModel)+' · Code: '+modelName(settings.providerExecutorModel):null;}
|
|
17
|
+
function sync(session){if(session)for(const k of ['providerEnabled','providerKeyId','providerPlannerModel','providerExecutorModel'])session[k]=preferences()[k];}
|
|
18
|
+
export function disableProvider(session){setPreference('providerEnabled',false);sync(session);}
|
|
19
|
+
export async function useProvider(id,planner,executor,session){
|
|
20
|
+
keyId(id);modelId(planner);modelId(executor);
|
|
21
|
+
const data=await request(base+'/'+id+'/models');
|
|
22
|
+
if(!data.models.some(m=>m.id===planner)||!data.models.some(m=>m.id===executor))throw Error('Both models must be available to this provider key.');
|
|
23
|
+
setPreference('providerEnabled',false);
|
|
24
|
+
setPreference('providerKeyId',id);setPreference('providerPlannerModel',planner);setPreference('providerExecutorModel',executor);setPreference('providerEnabled',true);sync(session);
|
|
25
|
+
notice('success','Your provider is ready.');detail('Planning',modelName(planner));detail('Coding',modelName(executor));console.log('Generation is billed by your provider.');
|
|
26
|
+
}
|
|
27
|
+
async function readSecret(){
|
|
28
|
+
if(process.stdin.isTTY)return hiddenInput('Provider API key (hidden): ');
|
|
29
|
+
let value='';for await(const chunk of process.stdin){value+=chunk.toString('utf8');if(value.length>1024)throw Error('Provider key input is too large.');}return value.trim();
|
|
30
|
+
}
|
|
31
|
+
export async function addProvider(provider,label,read=readSecret){
|
|
32
|
+
if(!Object.hasOwn(providers,provider))throw Error('Choose openai, anthropic or openrouter.');
|
|
33
|
+
if(!accessToken())throw Error('Sign in to Vigthoria before connecting a provider key.');
|
|
34
|
+
if(typeof label!=='string'||!label.trim()||label.length>80||/[\x00-\x1f\x7f]/.test(label))throw Error('Use a key name of 1–80 characters.');
|
|
35
|
+
let secret=await read();
|
|
36
|
+
try{
|
|
37
|
+
const prefix=provider==='anthropic'?'sk-ant-':provider==='openrouter'?'sk-or-v1-':'sk-';
|
|
38
|
+
if(typeof secret!=='string'||!new RegExp('^'+prefix+'[A-Za-z0-9_-]+$').test(secret)||secret.length<20||secret.length>1024||(provider==='openai'&&/^sk-(ant-|or-)/.test(secret)))throw Error('The key format does not match '+providers[provider]+'. Use a provider key, not a Vigthoria CLI key.');
|
|
39
|
+
// Only this HTTPS request contains the key. No preference/session/workspace write.
|
|
40
|
+
return await request(base,{body:{provider,key:secret,label:label.trim(),storageConsent:true}});
|
|
41
|
+
}finally{secret='';}
|
|
42
|
+
}
|
|
43
|
+
async function selectSaved(lines,theme){
|
|
44
|
+
const data=await request(base);
|
|
45
|
+
if(!data.keys.length){console.log('No provider keys connected. Choose Add a provider key first.');return null;}
|
|
46
|
+
return choose(lines,'Choose a provider key',data.keys.map(k=>({value:k.id,label:safe(k.label)+' · '+safe(providers[k.provider]||k.provider)+' · '+safe(k.maskedKey),description:String(k.modelCount||0)+' models found · key stored encrypted'})),preferences().providerKeyId,theme);
|
|
47
|
+
}
|
|
48
|
+
async function configureModels(lines,id,theme,session){
|
|
49
|
+
const data=await request(base+'/'+keyId(id)+'/models'),rows=providerModelChoices(data.models);
|
|
50
|
+
section('Choose your AI team','Planning decides the steps. Coding writes and reviews the code. The same model can do both.',theme);
|
|
51
|
+
const planner=await choose(lines,'Choose the planning model',rows,preferences().providerPlannerModel,theme);if(planner===null)return;
|
|
52
|
+
const executor=await choose(lines,'Choose the coding model',rows,preferences().providerExecutorModel||planner,theme);if(executor===null)return;
|
|
53
|
+
await useProvider(id,planner,executor,session);
|
|
54
|
+
}
|
|
55
|
+
export async function providerMenu(lines,theme='cyan',session){
|
|
56
|
+
while(true){
|
|
57
|
+
section('Provider API keys','Connect OpenAI, Anthropic or OpenRouter. Keys stay encrypted in your Vigthoria account vault.',theme);
|
|
58
|
+
console.log(routingLabel(preferences())||'Current route: Vigthoria account models');
|
|
59
|
+
const action=await choose(lines,'Choose a provider action',[
|
|
60
|
+
{value:'add',label:'Add a provider key',description:'Paste privately, validate access, then choose planning and coding models.'},
|
|
61
|
+
{value:'use',label:'Choose key & models',description:'Enable your own provider for agent and background coding tasks.'},
|
|
62
|
+
{value:'list',label:'List connected provider keys',description:'Show masked metadata only.'},
|
|
63
|
+
{value:'test',label:'Test a provider connection',description:'Check key access and model availability. No generation.'},
|
|
64
|
+
{value:'usage',label:'View provider request history',description:'See confirmed, rejected or uncertain calls. Provider billing remains authoritative.'},
|
|
65
|
+
{value:'off',label:'Use Vigthoria account models',description:'Disable your own provider route on this machine.'},
|
|
66
|
+
{value:'remove',label:'Remove a saved provider key',description:'Remove the encrypted key from your Vigthoria vault. Revoke at the provider to invalidate it.'},
|
|
67
|
+
{value:'back',label:'Back',description:'Return to Account & API.'},
|
|
68
|
+
],'add',theme);if(action===null||action==='back')return;
|
|
69
|
+
try{
|
|
70
|
+
if(action==='add'){
|
|
71
|
+
const provider=await choose(lines,'Choose the key provider',Object.entries(providers).map(([value,label])=>({value,label,description:'Use an API key issued by '+label+'.'})),'openai',theme);if(provider===null)continue;
|
|
72
|
+
const a=await lines.next('Key name (for example My OpenAI account): ');if(a.done||a.cancelled)continue;
|
|
73
|
+
const consent=await choose(lines,'Save this key encrypted in your Vigthoria account vault?',[{value:false,label:'Cancel',description:'Return without entering a key.'},{value:true,label:'Continue to hidden key entry',description:'The key travels over HTTPS to Vigthoria and is encrypted at rest. Your provider bills generation.'}],false,theme);if(consent!==true)continue;
|
|
74
|
+
// The picker has suspended its line reader before hidden input starts.
|
|
75
|
+
const data=await addProvider(provider,a.value.trim());notice('success',providers[provider]+' connected',theme);detail('Saved key',data.key.label+' · '+data.key.maskedKey,theme);detail('Available models',String(data.key.modelCount),theme);notice('info','Connection verified. No generation started.',theme);
|
|
76
|
+
await configureModels(lines,data.key.id,theme,session);
|
|
77
|
+
}else if(action==='list'){const data=await request(base);if(!data.keys.length)notice('info','No provider keys connected.',theme);for(const k of data.keys)detail(providers[k.provider]||k.provider,k.label+' · '+k.maskedKey,theme);}
|
|
78
|
+
else if(action==='usage')print(await request(base+'/usage'));
|
|
79
|
+
else if(action==='off'){disableProvider(session);console.log('Vigthoria account routing selected.');}
|
|
80
|
+
else{
|
|
81
|
+
const id=await selectSaved(lines,theme);if(id===null)continue;
|
|
82
|
+
if(action==='use')await configureModels(lines,id,theme,session);
|
|
83
|
+
else if(action==='test'){const data=await request(base+'/'+id+'/test',{body:{}});notice('success','Connection verified · '+data.modelCount+' models · no generation started.',theme);}
|
|
84
|
+
else if(action==='remove'){
|
|
85
|
+
const yes=await choose(lines,'Remove this saved key from the Vigthoria vault?',[{value:false,label:'Keep key'},{value:true,label:'Remove key'}],false,theme);if(yes!==true)continue;
|
|
86
|
+
await request(base+'/'+id,{method:'DELETE'});notice('success','Saved provider key removed.',theme);if(preferences().providerKeyId===id)disableProvider(session);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}catch(e){notice('error','Provider action failed: '+safe(e.message),theme);}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export async function providerCommand(argv=[]){
|
|
93
|
+
const [action,...args]=argv;
|
|
94
|
+
if(!action||action==='setup'){
|
|
95
|
+
if(args.length||!process.stdin.isTTY||!process.stdout.isTTY)throw Error('Use provider setup in a terminal. See provider --help for automation.');
|
|
96
|
+
const lines=replInput();try{await providerMenu(lines,preferences().theme);}finally{lines.close();}return;
|
|
97
|
+
}
|
|
98
|
+
if(action==='list'&&!args.length)return print(await request(base));
|
|
99
|
+
if(action==='usage'&&!args.length)return print(await request(base+'/usage'));
|
|
100
|
+
if(action==='off'&&!args.length){disableProvider();console.log('Vigthoria account routing selected.');return;}
|
|
101
|
+
if(action==='add'){
|
|
102
|
+
if(!Object.hasOwn(providers,args[0])||args.length!==4||args[1]!=='--name'||args[3]!=='--accept-encrypted-storage')throw Error('Use provider add PROVIDER --name NAME --accept-encrypted-storage; supply the key only through hidden input or private stdin.');
|
|
103
|
+
return print(await addProvider(args[0],args[2]));
|
|
104
|
+
}
|
|
105
|
+
if(['test','models'].includes(action)&&args.length===1)return print(await request(base+'/'+keyId(args[0])+(action==='test'?'/test':'/models'),action==='test'?{body:{}}:{}));
|
|
106
|
+
if(action==='use'&&args.length===5&&args[1]==='--planner'&&args[3]==='--executor')return useProvider(args[0],args[2],args[4]);
|
|
107
|
+
if(action==='remove'&&args.length===2&&args[1]==='--yes'){
|
|
108
|
+
const id=keyId(args[0]);print(await request(base+'/'+id,{method:'DELETE'}));if(preferences().providerKeyId===id)disableProvider();return;
|
|
109
|
+
}
|
|
110
|
+
throw Error('Use provider setup, add, list, test, models, use, off, remove or usage. Keys are never accepted as command arguments.');
|
|
111
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
2
|
+
import {createInterface} from 'node:readline';
|
|
3
|
+
import {PassThrough} from 'node:stream';
|
|
4
|
+
import {StringDecoder} from 'node:string_decoder';
|
|
5
|
+
const clean=s=>String(s??'').replace(/[\x00-\x1f\x7f-\x9f]/g,'');
|
|
6
|
+
|
|
7
|
+
// One consumer owns stdin: line editing for chat, bounded key selection for
|
|
8
|
+
// menus. A menu closes its temporary reader before any credential prompt.
|
|
9
|
+
export function replInput(input=process.stdin, output=process.stdout, cancel=()=>{}) {
|
|
10
|
+
let rl=null,waiting=null,selecting=null,closed=false,prompted=false,bytes=0,cancelled=false,busy=false,warned=false,suspending=false,releaseInput=null;
|
|
11
|
+
const queue=[];
|
|
12
|
+
function reader(){
|
|
13
|
+
if(rl)return rl;
|
|
14
|
+
// readline treats every pasted newline as Enter. Filter bracketed paste
|
|
15
|
+
// before its key decoder, preserving the whole brief until a real Enter.
|
|
16
|
+
// The bridge is removed before menus or private credential entry take stdin.
|
|
17
|
+
let source=input;
|
|
18
|
+
if(input.isTTY&&typeof input.setRawMode==='function'){
|
|
19
|
+
const bridge=new PassThrough(),decoder=new StringDecoder('utf8');
|
|
20
|
+
const start='\x1b[200~',end='\x1b[201~';let pending='',paste=null,timer=null,overflow=false;
|
|
21
|
+
bridge.isTTY=true;bridge.setRawMode=value=>input.setRawMode(value);
|
|
22
|
+
const warnBusy=()=>{if(!warned){output.write('\r\nAn agent request is already running. Wait for vigthoria> before sending another prompt, or press Ctrl+C to cancel.\r\n');warned=true;}};
|
|
23
|
+
function insert(value){
|
|
24
|
+
if(busy&&!waiting){warnBusy();return;}
|
|
25
|
+
value=value.replace(/\r\n?/g,'\n').replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,'');
|
|
26
|
+
if(overflow||(rl.line||'').length+value.length>50000){output.write('\r\nPaste is too large. Send a brief of at most 50,000 characters.\r\n');return;}
|
|
27
|
+
const cursor=rl.cursor||0,line=rl.line||'';
|
|
28
|
+
rl.line=line.slice(0,cursor)+value+line.slice(cursor);rl.cursor=cursor+value.length;rl.prompt(true);
|
|
29
|
+
}
|
|
30
|
+
function forward(value){
|
|
31
|
+
if(busy&&!waiting){if(value.includes('\x03'))bridge.write('\x03');else if(value)warnBusy();return;}
|
|
32
|
+
const normalized=value.replace(/\r\n?/g,'\n');
|
|
33
|
+
if(/\n[\s\S]/.test(normalized))insert(normalized);
|
|
34
|
+
else if(value)bridge.write(value);
|
|
35
|
+
}
|
|
36
|
+
const suffix=(text,marker)=>{for(let n=Math.min(text.length,marker.length-1);n>0;n--)if(text.endsWith(marker.slice(0,n)))return n;return 0;};
|
|
37
|
+
function consume(){
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
while(pending){
|
|
40
|
+
const marker=paste===null?start:end,index=pending.indexOf(marker);
|
|
41
|
+
if(index>=0){
|
|
42
|
+
const value=pending.slice(0,index);pending=pending.slice(index+marker.length);
|
|
43
|
+
if(paste===null){forward(value);paste='';overflow=false;}
|
|
44
|
+
else{if(paste.length+value.length>50000)overflow=true;if(!overflow)paste+=value;insert(paste);paste=null;overflow=false;}
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const keep=suffix(pending,marker),value=pending.slice(0,pending.length-keep);pending=pending.slice(pending.length-keep);
|
|
48
|
+
if(paste===null)forward(value);
|
|
49
|
+
else if(paste.length+value.length>50000)overflow=true;
|
|
50
|
+
else if(!overflow)paste+=value;
|
|
51
|
+
if(paste===null&&pending)timer=setTimeout(()=>{const value=pending;pending='';forward(value);},80);
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const data=chunk=>{pending+=decoder.write(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));consume();};
|
|
56
|
+
const finish=()=>{pending+=decoder.end();consume();if(paste!==null){rl.line='';rl.cursor=0;output.write('\r\nIncomplete paste cancelled.\r\n');}bridge.end();};
|
|
57
|
+
const resume=()=>input.resume(),pause=()=>input.pause();
|
|
58
|
+
bridge.on('resume',resume);bridge.on('pause',pause);input.on('data',data);input.once('end',finish);
|
|
59
|
+
output.write('\x1b[?2004h');source=bridge;
|
|
60
|
+
releaseInput=()=>{clearTimeout(timer);input.off('data',data);input.off('end',finish);bridge.off('resume',resume);bridge.off('pause',pause);bridge.destroy();output.write('\x1b[?2004l');releaseInput=null;};
|
|
61
|
+
}
|
|
62
|
+
rl=createInterface({input:source,output,terminal:Boolean(input.isTTY),crlfDelay:Infinity,prompt:''});
|
|
63
|
+
rl.on('line',value=>{
|
|
64
|
+
prompted=false;rl.setPrompt('');
|
|
65
|
+
if(busy&&!waiting){if(!warned){output.write('\r\nAn agent request is already running. Wait for vigthoria> before sending another prompt, or press Ctrl+C to cancel.\r\n');warned=true;}return;}
|
|
66
|
+
if(waiting){const resolve=waiting;waiting=null;resolve({value,done:false});}
|
|
67
|
+
else if(bytes+value.length<=1000000){queue.push(value);bytes+=value.length;}
|
|
68
|
+
else{queue.length=0;bytes=0;output.write('\r\nInput buffer is full. Resend a shorter brief.\r\n');}
|
|
69
|
+
});
|
|
70
|
+
rl.on('close',()=>{releaseInput?.();if(suspending)return;closed=true;if(waiting){waiting({done:true});waiting=null;}});
|
|
71
|
+
rl.on('SIGINT',()=>{
|
|
72
|
+
cancel();prompted=false;rl.setPrompt('');rl.clearLine(0);queue.length=0;bytes=0;cancelled=true;
|
|
73
|
+
output.write('\r\nCancelled current input/request. Use /exit to close the agent.\r\n');
|
|
74
|
+
if(waiting){const resolve=waiting;waiting=null;cancelled=false;resolve({value:'',done:false,cancelled:true});}
|
|
75
|
+
});
|
|
76
|
+
return rl;
|
|
77
|
+
}
|
|
78
|
+
function suspend(){if(rl){suspending=true;rl.close();rl=null;suspending=false;}prompted=false;}
|
|
79
|
+
function show(prompt='vigthoria> '){if(!closed&&!prompted){prompted=true;output.write('\r\n');reader().setPrompt(prompt);rl.prompt(true);}}
|
|
80
|
+
return {
|
|
81
|
+
setBusy(value){busy=value;warned=false;if(value){queue.length=0;bytes=0;}},
|
|
82
|
+
next(primary=false){
|
|
83
|
+
if(selecting||waiting)throw Error('Concurrent terminal input readers are not permitted');
|
|
84
|
+
if(cancelled){cancelled=false;return Promise.resolve({value:'',done:false,cancelled:true});}
|
|
85
|
+
if(queue.length){const value=queue.shift();bytes-=value.length;return Promise.resolve({value,done:false});}
|
|
86
|
+
if(closed)return Promise.resolve({done:true});
|
|
87
|
+
reader();input.resume();if(primary)show(typeof primary==='string'?primary:'vigthoria> ');else rl.setPrompt('');
|
|
88
|
+
return new Promise(resolve=>{waiting=resolve;});
|
|
89
|
+
},
|
|
90
|
+
async select({message,choices,defaultValue,accent=36,plain=false}){
|
|
91
|
+
if(waiting||selecting)throw Error('Concurrent terminal input readers are not permitted');
|
|
92
|
+
if(closed)return null;
|
|
93
|
+
if(!choices.length||choices.every(c=>c.disabled))throw Error('Menu has no available choices');
|
|
94
|
+
// Non-TTY fallback stays line based; useful for accessible input and tests.
|
|
95
|
+
if(!input.isTTY||!output.isTTY||typeof input.setRawMode!=='function'){
|
|
96
|
+
output.write('\n'+clean(message)+'\n');choices.forEach((c,i)=>output.write(` ${i+1} ${clean(c.label)}${c.disabled?' (unavailable)':''}\n`));
|
|
97
|
+
while(true){const a=await this.next('? Number, or 0 to go back: ');if(a.done||a.cancelled||a.value.trim()==='0')return null;const c=choices[Number(a.value)-1];if(c&&!c.disabled)return c.value;output.write('Choose an available number.\n');}
|
|
98
|
+
}
|
|
99
|
+
suspend();
|
|
100
|
+
let index=choices.findIndex(c=>c.value===defaultValue&&!c.disabled);if(index<0)index=choices.findIndex(c=>!c.disabled);
|
|
101
|
+
const width=Math.max(20,Number(output.columns)||80),page=Math.max(3,Math.min(8,(Number(output.rows)||24)-8));
|
|
102
|
+
const fit=s=>{s=clean(s);return s.length>width-2?s.slice(0,width-3)+'…':s;};
|
|
103
|
+
const colour=(s,code)=>!plain&&!Object.hasOwn(process.env,'NO_COLOR')&&process.env.TERM!=='dumb'?'\x1b['+code+'m'+s+'\x1b[0m':s;
|
|
104
|
+
let rendered=0,digits='',pending='',escapeTimer=null;
|
|
105
|
+
function render(){
|
|
106
|
+
if(rendered)output.write('\x1b['+rendered+'A\r');
|
|
107
|
+
const start=Math.max(0,Math.min(index-Math.floor(page/2),choices.length-page));
|
|
108
|
+
const lines=[colour(fit(message),'1;97')];
|
|
109
|
+
for(let i=start;i<Math.min(choices.length,start+page);i++){
|
|
110
|
+
const c=choices[i],text=fit(`${i===index?'›':' '} ${String(i+1).padStart(2)} ${c.label}${c.disabled?' (unavailable)':''}`);
|
|
111
|
+
lines.push(colour(text,c.disabled?'90':i===index?(accent===35?'1;97;48;5;54':'1;97;48;5;24'):'37'));
|
|
112
|
+
}
|
|
113
|
+
lines.push(colour(fit(choices[index].description||''),'90'));
|
|
114
|
+
lines.push(colour(fit(`↑/↓ move · Enter select · Esc back${choices.length>page?' · '+(index+1)+'/'+choices.length:''}`),'90'));
|
|
115
|
+
lines.push(fit(digits?'Number: '+digits:'Or type a number and press Enter.'));
|
|
116
|
+
output.write(lines.map(s=>'\x1b[2K'+s+'\r\n').join(''));rendered=lines.length;
|
|
117
|
+
}
|
|
118
|
+
return await new Promise(resolve=>{
|
|
119
|
+
let finished=false;
|
|
120
|
+
const rawBefore=Boolean(input.isRaw);
|
|
121
|
+
function finish(value){if(finished)return;finished=true;clearTimeout(escapeTimer);input.off('data',data);input.off('end',end);input.setRawMode(rawBefore);input.pause();selecting=null;output.write('\x1b[?25h');resolve(value);}
|
|
122
|
+
const end=()=>{closed=true;finish(null);};
|
|
123
|
+
function step(direction){digits='';for(let n=0;n<choices.length;n++){index=(index+direction+choices.length)%choices.length;if(!choices[index].disabled)break;}render();}
|
|
124
|
+
function data(chunk){
|
|
125
|
+
pending+=chunk.toString('utf8');if(pending.length>256){pending='';return;}
|
|
126
|
+
clearTimeout(escapeTimer);
|
|
127
|
+
while(pending){
|
|
128
|
+
const sequence=pending.match(/^\x1b\[(?:\d+;?)*[A-Za-z~]/)?.[0];
|
|
129
|
+
if(sequence){pending=pending.slice(sequence.length);if(sequence==='\x1b[A')step(-1);else if(sequence==='\x1b[B')step(1);else if(sequence==='\x1b[5~')for(let j=0;j<page;j++)step(-1);else if(sequence==='\x1b[6~')for(let j=0;j<page;j++)step(1);continue;}
|
|
130
|
+
if(pending[0]==='\x1b'){if(pending==='\x1b'||/^\x1b\[[\d;]*$/.test(pending)){escapeTimer=setTimeout(()=>finish(null),80);return;}finish(null);return;}
|
|
131
|
+
const ch=pending[0];pending=pending.slice(1);
|
|
132
|
+
if(ch==='\x03'||ch==='\x04'){finish(null);return;}
|
|
133
|
+
if(ch==='\r'||ch==='\n'){
|
|
134
|
+
if(digits){const candidate=Number(digits)-1;if(!choices[candidate]||choices[candidate].disabled){digits='';render();continue;}index=candidate;}
|
|
135
|
+
finish(choices[index].value);return;
|
|
136
|
+
}
|
|
137
|
+
if(/[0-9]/.test(ch)){digits=(digits+ch).slice(-3);render();}
|
|
138
|
+
else if(ch==='\x7f'||ch==='\b'){digits=digits.slice(0,-1);render();}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
selecting=finish;input.on('data',data);input.once('end',end);input.setRawMode(true);output.write('\n\x1b[?25l');render();input.resume();
|
|
142
|
+
});
|
|
143
|
+
},
|
|
144
|
+
close(){if(selecting)selecting(null);closed=true;if(rl)rl.close();},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import {randomUUID} from 'node:crypto';
|
|
5
|
+
import {request} from './account.mjs';
|
|
6
|
+
import {snapshot,applyFiles} from './workspace.mjs';
|
|
7
|
+
export async function repository(argv){const[action,...args]=argv;const list=()=>request('/api/community-repo/my-repos');if(action==='list'){console.log(JSON.stringify(await list(),null,2));return;}
|
|
8
|
+
if(action==='status'){console.log(JSON.stringify(await request('/api/repo/status/'+encodeURIComponent(path.basename(process.cwd()))),null,2));return;}
|
|
9
|
+
if(action==='push'){const snap=snapshot(args[0]&&!args[0].startsWith('-')?args[0]:process.cwd(),{binary:true,portablePlans:true});if(snap.excluded.length)throw Error('Repository push excludes oversized or credential-bearing files; review these files before pushing: '+snap.excluded.slice(0,10).join(', '));const option=(name,fallback)=>args.includes(name)?args[args.indexOf(name)+1]:fallback;const visibility=option('--visibility','private');if(!['private','restricted','public'].includes(visibility))throw Error('Invalid repository visibility');if(args.includes('--id')&&!/^[1-9][0-9]*$/.test(option('--id','')))throw Error('Invalid repository ID');if(!args.includes('--yes'))throw Error('Repository publication requires explicit --yes authorization');const data=await request('/api/community-repo/push',{signal:AbortSignal.timeout(120000),body:{operationId:randomUUID(),projectName:option('--name',path.basename(snap.root)),description:'',techStack:'',visibility,files:Object.entries(snap.files).map(([name,content])=>({path:name,content:Buffer.isBuffer(content)?content.toString('base64'):content,encoding:Buffer.isBuffer(content)?'base64':'utf8',size:Buffer.byteLength(content)})),...(option('--id',null)?{projectId:Number(option('--id',null))}:{}),clientSource:'community-cli',commitMessage:option('--message','Vigthoria CLI project snapshot')}});console.log(JSON.stringify(data,null,2));return;}
|
|
10
|
+
if(action==='review'){const review=args[0]&&!args[0].startsWith('-')?args[0]:null;if(review&&!/^[A-Za-z0-9._:-]{1,128}$/.test(review))throw Error('Invalid review id');console.log(JSON.stringify(await request('/api/community-repo/security-reviews'+(review?'/'+encodeURIComponent(review):'?mine=true')),null,2));return;}
|
|
11
|
+
if(action==='share'){if(!args[0]||!args.includes('--yes'))throw Error('Use repo share NAME --yes after reviewing the sharing destination');const expires=args.includes('--expires')?args[args.indexOf('--expires')+1]:'7d';console.log(JSON.stringify(await request('/api/community-repo/share',{body:{operationId:randomUUID(),projectName:args[0],expiresIn:expires}}),null,2));return;}
|
|
12
|
+
if(action==='delete'){if(!args[0]||!args.includes('--yes'))throw Error('Use repo delete NAME_OR_ID --yes');const data=await list(),repos=data.repos||data.projects||data.repositories||[];const match=repos.find(r=>[r.name,r.project_name,r.id].some(v=>String(v)===args[0]));if(!match)throw Error('Owned repository not found');console.log(JSON.stringify(await request('/api/community-repo/projects/'+encodeURIComponent(match.id),{method:'DELETE'}),null,2));return;}
|
|
13
|
+
if(action==='pull'){const name=args[0];if(!name)throw Error('Repository name is required');const data=await list();const repos=data.repos||data.projects||data.repositories||[];const match=repos.find(r=>[r.name,r.project_name,r.id].some(x=>String(x)===name));if(!match)throw Error('Repository not found');const result=await request('/api/community-repo/pull',{body:{projectId:match.id}});if(result.inlineComplete===false)throw Error('This repository requires the complete ZIP archive. Download it from Community; no partial files were written.');const target=args.includes('--output')?args[args.indexOf('--output')+1]:process.cwd();if(!target)throw Error('--output requires a directory');fs.mkdirSync(target,{recursive:true,mode:0o700});const snap=snapshot(target,{binary:true,portablePlans:true});const files=result.files||result.project?.files;if(!Array.isArray(files))throw Error('Repository response is not a supported complete file set');const map=Object.create(null);for(const f of files){if(!['utf8','base64',undefined].includes(f.encoding)||typeof f.path!=='string'||typeof f.content!=='string')throw Error('Invalid repository file');if(Object.hasOwn(map,f.path)||Object.hasOwn(snap.files,f.path))throw Error('Repository pull refuses duplicate paths or existing files');let content=f.content;if(f.encoding==='base64'){if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(content))throw Error('Invalid binary encoding');content=Buffer.from(content,'base64');}map[f.path]=content;}applyFiles(snap,map,{portablePlans:true});console.log(`Restored ${Object.keys(map).length} files without overwriting existing files.`);return;}
|
|
14
|
+
throw Error('Use repo list, status, push, pull, review, share or delete.');}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {configDirectory} from './account.mjs';
|
|
2
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {randomUUID} from 'node:crypto';
|
|
7
|
+
const directory=()=>path.join(configDirectory(),'cli-sessions');
|
|
8
|
+
const filename=id=>{if(!/^[a-f0-9-]{36}$/.test(id))throw Error('Invalid local session id');return path.join(directory(),id+'.json');};
|
|
9
|
+
export function saveSession(data){const dir=directory();fs.mkdirSync(dir,{recursive:true,mode:0o700});const file=filename(data.id);if(!fs.existsSync(file)&&fs.readdirSync(dir).filter(n=>n.endsWith('.json')).length>=100)throw Error('100 local sessions retained; remove selected sessions before saving more');const raw=JSON.stringify({...data,savedAt:new Date().toISOString()});if(Buffer.byteLength(raw)>256000)throw Error('Session exceeds local save limit; use /compact or start a new session');const temp=file+'.'+randomUUID()+'.tmp';fs.writeFileSync(temp,raw,{flag:'wx',mode:0o600});fs.renameSync(temp,file);}
|
|
10
|
+
export function loadSession(id){const raw=fs.readFileSync(filename(id),'utf8');if(Buffer.byteLength(raw)>256000)throw Error('Saved session exceeds limit');const d=JSON.parse(raw);if(d.id!==id||!Array.isArray(d.history)||typeof d.root!=='string')throw Error('Invalid saved session');return d;}
|
|
11
|
+
export function listSessions(){try{return fs.readdirSync(directory()).filter(n=>/^[a-f0-9-]{36}\.json$/.test(n)).map(n=>{const s=loadSession(n.slice(0,-5));return{id:s.id,workspace:s.root,model:s.model,savedAt:s.savedAt,messages:s.history.length};}).sort((a,b)=>b.savedAt.localeCompare(a.savedAt));}catch(e){if(e.code==='ENOENT')return[];throw e;}}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
|
|
2
|
+
// Display only: task authority and acceptance remain on Vigthoria services.
|
|
3
|
+
import {paint} from './presentation.mjs';
|
|
4
|
+
const clean=value=>String(value??'').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,'').replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g,' ').replace(/\s+/g,' ').trim();
|
|
5
|
+
const width=value=>[...value].reduce((n,c)=>n+(/\p{Mark}/u.test(c)||c==='\u200d'?0:/\p{Emoji_Presentation}/u.test(c)||/[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\uff01-\uff60]/u.test(c)?2:1),0);
|
|
6
|
+
function fit(value,columns){let result='',used=0;const text=' '.repeat(String(value).match(/^ */)?.[0].length||0)+clean(value);for(const c of text){const size=width(c);if(used+size>columns-1)return result+'…';result+=c;used+=size;}return result;}
|
|
7
|
+
const frames=['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'];
|
|
8
|
+
export function taskProgress({output=process.stdout,errorOutput=process.stderr,theme='cyan',now=Date.now,schedule=fn=>setInterval(fn,120),unschedule=clearInterval,enabled}={}){
|
|
9
|
+
enabled??=Boolean(output.isTTY&&theme!=='plain'&&!Object.hasOwn(process.env,'NO_COLOR')&&process.env.TERM!=='dumb'&&process.env.VIGTHORIA_DECK_MODE!=='1');
|
|
10
|
+
const tasks=new Map(),writers=new Map();let running=false,paused=false,mode='working',phase='Understanding your request',current=null,started=0,timer=null,frame=0,rendered=0,lastLines=[],partial=false;
|
|
11
|
+
const write=(...args)=>writers.get(output).apply(output,args);
|
|
12
|
+
function clear(){if(!rendered)return;write('\x1b['+rendered+'A\r\x1b[0J');rendered=0;}
|
|
13
|
+
function view(){
|
|
14
|
+
const list=[...tasks.values()],done=list.filter(t=>t.status==='completed').length,total=list.length;
|
|
15
|
+
const active=list.filter(t=>t.status==='in_progress'),index=current?list.findIndex(t=>t.id===current.id):-1;
|
|
16
|
+
const ordinal=mode==='success'?total:index>=0?index+1:Math.min(done+1,total);
|
|
17
|
+
const label=mode==='success'?'Complete':mode==='cancelled'?'Cancelled':mode==='failed'?'Needs attention':active.length>1?'Working · '+active.length+' tasks':'Working';
|
|
18
|
+
const seconds=Math.max(0,Math.floor((now()-started)/1000)),elapsed=String(Math.floor(seconds/60)).padStart(2,'0')+':'+String(seconds%60).padStart(2,'0');
|
|
19
|
+
const columns=Math.max(8,(Number(output.columns)||80)-2),barSize=Math.max(4,Math.min(18,columns-31)),filled=total?Math.floor(done/total*barSize):0;
|
|
20
|
+
const symbol=mode==='success'?'✓':mode==='failed'?'!':mode==='cancelled'?'■':frames[frame++%frames.length];
|
|
21
|
+
const title=mode==='success'?(total?'All planned tasks completed':'Request completed'):(current?.title||phase).replace(/^Apply evidence-grounded repair to /i,'Repair ');
|
|
22
|
+
const header=fit(' '+symbol+' '+(total?'TASK PLAN':'AGENT STATUS')+(total?' '+ordinal+'/'+total:'')+' · '+label+' '+elapsed,columns);
|
|
23
|
+
const subtitle=fit(' '+title,columns);
|
|
24
|
+
const tail=fit(' '+(total?(columns>39?'━'.repeat(filled)+'─'.repeat(barSize-filled)+' ':'')+done+' complete · '+(total-done)+' remaining':mode==='success'?'Ready for your next request':mode==='cancelled'?'Your request was stopped':'Your agent is preparing the next step'),columns);
|
|
25
|
+
return {lines:[header,subtitle,tail],done,total,ordinal,title,label};
|
|
26
|
+
}
|
|
27
|
+
function draw(){if(!enabled||!running||paused||partial)return;clear();const v=view();lastLines=v.lines;const tone=mode==='failed'?'warning':mode==='success'?'success':'accent';write(v.lines.map((line,i)=>'\x1b[2K'+paint(line,i===0?tone:i===1?'title':'muted',theme,output)+'\r\n').join(''));rendered=v.lines.length;}
|
|
28
|
+
function intercept(stream){if(!stream||writers.has(stream))return;const original=stream.write;writers.set(stream,original);stream.write=function(chunk,encoding,callback){
|
|
29
|
+
if(!running||paused)return original.apply(this,arguments);
|
|
30
|
+
clear();let result;try{result=original.apply(this,arguments);}finally{
|
|
31
|
+
const text=Buffer.isBuffer(chunk)?chunk.toString('utf8'):String(chunk??'');if(text)partial=!/[\r\n]$/.test(text);draw();
|
|
32
|
+
}return result;
|
|
33
|
+
};}
|
|
34
|
+
function resize(){if(rendered){const cols=Math.max(1,Number(output.columns)||80);rendered=lastLines.reduce((n,line)=>n+Math.max(1,Math.ceil(width(line)/cols)),0);}draw();}
|
|
35
|
+
function restore(){if(!enabled)return;try{if(writers.has(output))write('\x1b[?25h');}catch{}for(const [stream,original]of writers)stream.write=original;writers.clear();output.off?.('resize',resize);process.removeListener('exit',restore);}
|
|
36
|
+
const api={
|
|
37
|
+
start(){if(running)return;running=true;started=now();if(!enabled)return;intercept(output);intercept(errorOutput);output.on?.('resize',resize);process.once('exit',restore);write('\x1b[?25l');draw();timer=schedule(draw);timer?.unref?.();},
|
|
38
|
+
update(event){
|
|
39
|
+
if(event.type==='plan'&&event.plan?.mode==='planner-executor'&&Array.isArray(event.plan.tasks)){
|
|
40
|
+
const next=new Map();for(const t of event.plan.tasks.slice(0,5000)){if(typeof t.id!=='string'||!t.id)continue;next.set(t.id,{id:t.id,title:clean(t.title||'Planned task'),status:tasks.get(t.id)?.status||'pending'});}tasks.clear();for(const [id,t]of next)tasks.set(id,t);
|
|
41
|
+
}
|
|
42
|
+
if(event.type==='pipeline_stage')phase=({dispatcher:'Understanding your request',architect:'Preparing your plan',executor:'Working on your project'})[event.stage]||phase;
|
|
43
|
+
if(event.type==='executor_start'&&typeof event.task_id==='string'){
|
|
44
|
+
current=tasks.get(event.task_id)||{id:event.task_id,title:clean(event.title||'Working on the next task'),status:'pending'};current.status='in_progress';mode='working';
|
|
45
|
+
}
|
|
46
|
+
if(event.type==='executor_complete'&&event.summary?.status==='failed')mode='failed';
|
|
47
|
+
if(event.type==='task_progress'&&Array.isArray(event.tasks)){
|
|
48
|
+
for(const t of event.tasks.slice(0,5000)){if(typeof t.id!=='string'||!t.id)continue;const row=tasks.get(t.id)||{id:t.id,title:clean(t.title||'Planned task')};row.status=['completed','in_progress','pending','requeued','failed','blocked','skipped'].includes(t.status)?t.status:'pending';row.title=clean(t.title||row.title);tasks.set(t.id,row);}
|
|
49
|
+
current=tasks.get(event.current_task_id)||current;
|
|
50
|
+
mode=[...tasks.values()].some(t=>t.status==='failed')?'failed':'working';
|
|
51
|
+
if(tasks.size&&[...tasks.values()].every(t=>t.status==='completed')){current=null;phase='Final project checks';}
|
|
52
|
+
}
|
|
53
|
+
if(event.type==='error'||event.type==='terminal_error')mode='failed';draw();
|
|
54
|
+
},
|
|
55
|
+
pause(){if(!enabled||paused)return;clear();paused=true;write('\x1b[?25h');},
|
|
56
|
+
resume(){if(!enabled||!running||!paused)return;paused=false;partial=false;write('\x1b[?25l');draw();},
|
|
57
|
+
finish(outcome='success'){if(!running)return;unschedule(timer);timer=null;if(enabled){clear();paused=false;partial=false;mode=outcome;if(outcome==='success')for(const t of tasks.values())t.status='completed';draw();rendered=0;}running=false;restore();},
|
|
58
|
+
state(){const v=view();return {completed:v.done,total:v.total,current:v.ordinal,title:v.title,status:v.label};},
|
|
59
|
+
};
|
|
60
|
+
return api;
|
|
61
|
+
}
|