vigthoria-cli 2.3.8 → 2.3.11

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.
@@ -1,38 +0,0 @@
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 {randomUUID} from 'node:crypto';
6
- import readline from 'node:readline';
7
- export const origin='https://coder.vigthoria.io';
8
- export const configDirectory=()=>process.env.VIGTHORIA_CLI_CONFIG_DIR?path.resolve(process.env.VIGTHORIA_CLI_CONFIG_DIR):path.join(os.homedir(),'.vigthoria');
9
- export const configPath=()=>path.join(configDirectory(),'continuity-client.json');
10
- export function readAccount(){for(const name of ['continuity-client.json','config.json'])try{const value=JSON.parse(fs.readFileSync(path.join(configDirectory(),name),'utf8'));const data=value.data||value;if(name==='continuity-client.json')return data.credentialsRetired?{}:data;if(!data.credentialsRetired&&data.authToken)return data;}catch(error){if(name==='continuity-client.json'&&error.code!=='ENOENT')return {};}return {};}
11
- export function accessToken(){
12
- const direct=process.env.VIGTHORIA_TOKEN||process.env.VIGTHORIA_AUTH_TOKEN;if(direct)return direct;
13
- const file=process.env.VIGTHORIA_AUTH_TOKEN_FILE;if(file){
14
- const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);try{const st=fs.fstatSync(fd);if(!st.isFile()||st.size>16384||st.size<1||(process.platform!=='win32'&&((st.mode&0o077)!==0||st.uid!==process.getuid())))throw Error('Use a private account-owned credential file');const token=fs.readFileSync(fd,'utf8').trim();if(!/^[A-Za-z0-9._-]{20,16384}$/.test(token))throw Error('Invalid private credential file');return token;}finally{fs.closeSync(fd);}
15
- }
16
- const account=readAccount();return account.activeCredential==='api_key'?account.apiKey:account.authToken;
17
- }
18
- export async function request(route,{body,method=body===undefined?'GET':'POST',token=accessToken(),signal=AbortSignal.timeout(30000)}={}){
19
- if(!route.startsWith('/api/')||route.includes('://'))throw Error('Invalid Coder route');
20
- const response=await fetch(origin+route,{method,redirect:'error',signal,headers:{Accept:'application/json','Content-Type':'application/json',...(token?{Authorization:`Bearer ${token}`}:{})},...(body===undefined?{}:{body:JSON.stringify(body)})});
21
- let bytes=0;const chunks=[];for await(const chunk of response.body){bytes+=chunk.length;if(bytes>32*1024*1024)throw Error('Coder response exceeds transport limit');chunks.push(chunk);}let data;try{data=JSON.parse(Buffer.concat(chunks).toString('utf8'));}catch{throw Error(`Invalid Coder response (${response.status})`);}if(!response.ok){const detail=data.detail||data.error;const message=typeof detail==='string'?detail:detail?.message||data.message||`Coder request rejected (${response.status})`;throw Object.assign(Error(message),{status:response.status,code:data.errorCode||data.code||detail?.code||detail?.type});}return data;
22
- }
23
- export function persistAccount(data){const file=configPath();fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});const temp=file+'.'+randomUUID()+'.tmp';try{fs.writeFileSync(temp,JSON.stringify(data),{flag:'wx',mode:0o600});fs.renameSync(temp,file);if(process.platform!=='win32')fs.chmodSync(file,0o600);}finally{try{fs.unlinkSync(temp);}catch{}}}
24
- function askEmail(){return new Promise(resolve=>{const r=readline.createInterface({input:process.stdin,output:process.stderr});r.question('Vigthoria account email: ',v=>{r.close();resolve(v.trim());});});}
25
- export function hiddenInput(label='Password: '){return new Promise((resolve,reject)=>{
26
- process.stderr.write(label);readline.emitKeypressEvents(process.stdin);process.stdin.setRawMode(true);process.stdin.resume();let value='';
27
- const finish=(error)=>{process.stdin.off('keypress',key);process.stdin.setRawMode(false);process.stdin.pause();process.stderr.write('\n');error?reject(error):resolve(value);};
28
- const key=(str,k={})=>{if(k.ctrl&&(k.name==='c'||k.name==='d'))return finish(Error('Sign-in cancelled'));if(k.name==='return'||k.name==='enter')return finish();if(k.name==='backspace'){value=Array.from(value).slice(0,-1).join('');return;}if(str&&!k.ctrl&&!k.meta&&!/[\x00-\x1f\x7f]/.test(str)){value+=str;if(value.length>4096)finish(Error('Credential input too large'));}};
29
- process.stdin.on('keypress',key);
30
- });}
31
- export async function login(argv){const index=argv.findIndex(x=>x==='-e'||x==='--email');let email=index>=0?argv[index+1]?.trim():null;
32
- if(!email&&process.stdin.isTTY)email=await askEmail();if(!email)throw Error('Use vigthoria login --email EMAIL; supply the password on private stdin when not in a terminal.');
33
- let password='';if(process.stdin.isTTY)password=await hiddenInput();else{for await(const chunk of process.stdin){password+=chunk.toString('utf8');if(password.length>4096)throw Error('Credential input too large');}password=password.replace(/[\r\n]+$/,'');}if(!password)throw Error('Password is required');
34
- const data=await request('/api/login',{body:{email,password},token:null});const token=data.tokens?.access_token||data.token||data.access_token||data.authToken;if(typeof token!=='string'||!token)throw Error('Coder did not issue an access token');
35
- // Validate the issued credential at the actual account endpoint before storing it.
36
- const live=await request('/api/user/subscription',{token});const user=data.user||{};persistAccount({apiUrl:origin,modelsApiUrl:'https://api.vigthoria.io',authToken:token,refreshToken:data.tokens?.refresh_token||data.refreshToken||null,email:user.email||email,userId:user.user_id||user.id||live.userId||null});console.log('Signed in to Coder.');}
37
- export function logout(){// A current empty canonical record overrides older imported credentials in Workbench.
38
- persistAccount({apiUrl:origin,authToken:null,credentialsRetired:false,loggedOut:true});console.log('Local Coder session cleared.');}
@@ -1,48 +0,0 @@
1
- /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
- import path from 'node:path';
3
- import {taskProgress} from './task-progress.mjs';
4
- import {createHash,randomUUID} from 'node:crypto';
5
- import {replInput} from './repl-input.mjs';
6
- import {writeDeckRecord} from './deck-channel.mjs';
7
- import {origin,accessToken} from './account.mjs';
8
- import {snapshot,applyFiles,workspaceIssue} from './workspace.mjs';
9
- import {notice,section,detail,paint,renderText,visibleModelName} from './presentation.mjs';
10
- import {localWorkspace} from './workspace-tools.mjs';
11
- import {memoryCredential,memoryCall} from './continuity.mjs';
12
- import {providerRoute,disableProvider,providerMenu,routingLabel} from './providers.mjs';
13
- import {setup,choose,settingsMenu,selectModel,modelChoices,modelLabel} from './terminal.mjs';
14
- import {setPreference,resolveWorkspace} from './preferences.mjs';
15
- import {saveSession,loadSession} from './session-state.mjs';
16
- import {request} from './account.mjs';
17
- import {parse} from './commands.mjs';
18
- export function deck(event){if(process.env.VIGTHORIA_DECK_MODE!=='1')return;const value={...event,ts:Date.now()};if(process.env.VIGTHORIA_DECK_EVENTS_DIR){try{writeDeckRecord(process.env.VIGTHORIA_DECK_EVENTS_DIR,value);}catch(error){throw Error('Agent status channel unavailable. Check terminal output and project files before continuing.',{cause:error});}}else process.stdout.write('\n@vigthoria-deck:'+JSON.stringify(value)+'\n');}
19
- export async function consumeEvents(response,onEvent){const decoder=new TextDecoder();let buffer='',bytes=0;for await(const chunk of response.body){bytes+=chunk.length;if(bytes>64*1024*1024)throw Error('Agent response exceeds transport limit');buffer+=decoder.decode(chunk,{stream:true});if(buffer.length>8*1024*1024)throw Error('Agent event exceeds transport limit');const records=buffer.split(/\r?\n\r?\n/);buffer=records.pop()||'';for(const record of records){const data=record.split(/\r?\n/).filter(s=>s.startsWith('data:')).map(s=>s.slice(5).trimStart()).join('\n');if(!data||data==='[DONE]')continue;await onEvent(JSON.parse(data));}}if(buffer.trim()&&!buffer.trim().startsWith(':'))throw Error('Agent stream ended with an incomplete event');}
20
- export async function runRemote(prompt,{root=process.cwd(),fetcher=fetch,approve=async()=>false,approveCommand=async()=>false,signal,report=()=>{},serverContext=null,memory=null,history=[],model='agent',providerKey=null,localTools=false,cliCommand=null,forkRun=null}={}){
21
- if(process.env.VIGTHORIA_WORKSPACE_MODE==='cloud')throw Error('Cloud Workspace cannot read or edit local project files. Switch to Local Copilot.');
22
- const token=accessToken();if(!token)throw Error('Sign in with vigthoria login or vigthoria api-key login first.');
23
- const issue=workspaceIssue(root);if(issue)throw Error(issue);
24
- let snap,broker=null;try{if(localTools)throw Object.assign(Error('Local tools selected'),{code:'WORKSPACE_TRANSFER_LIMIT'});snap=snapshot(root);}catch(e){if(e.code!=='WORKSPACE_TRANSFER_LIMIT')throw e;broker=localWorkspace(root,{approve,approveCommand,signal});snap={root:broker.inventory.root,files:{},hashes:{},excluded:[]};report({type:'status',message:'Working directly in the selected project. Source files are read as needed; the full project is not uploaded.'});}
25
- const operation=randomUUID(),ref='workspace:'+createHash('sha256').update(snap.root).digest('hex');
26
- // Only public workspace facts and transport bounds are client-side. The cloud owns planning, prompts, ranking and context budgets.
27
- const context={workspace:{name:path.basename(snap.root),path:ref},workspacePath:null,projectPath:null,targetPath:null,localWorkspaceRef:ref,localWorkspacePath:ref,localWorkspaceName:path.basename(snap.root),localWorkspaceSummary:{name:path.basename(snap.root),path:ref,files:Object.keys(snap.files),fileCount:Object.keys(snap.files).length},workspaceHydrationRequired:true,clientToolExecution:false,client_tool_execution:false,localMachineCapable:false,approvalLevel:'confirm',approval_level:'confirm',executionSurface:'cli',clientSurface:'cli',rawPrompt:prompt};
28
- if(broker){const names=[];let inventoryBytes=2;for(const name of broker.inventory.files){const size=Buffer.byteLength(JSON.stringify(name))+1;if(names.length>=5000||inventoryBytes+size>120000)break;names.push(name);inventoryBytes+=size;}context.workspaceHydrationRequired=false;context.clientToolExecution=true;context.client_tool_execution=true;context.localMachineCapable=true;context.clientToolCapabilities={supported:['read_file','list_directory','glob','search_files','write_file','edit_file','delete_file','run_command','mutation_baseline_v1','source_baseline_v1']};context.localWorkspaceSummary={name:path.basename(snap.root),path:ref,files:names,fileCount:broker.inventory.files.length,inventoryTruncated:broker.inventory.files.length>names.length};}
29
- if(providerKey){context.providerKey=providerKey;model='byok';}
30
- if(model!=='agent')context.agentExecutionPolicy={explicitModel:true,cloudSelected:model==='byok'||model.startsWith('vigthoria-cloud-')};context.history=history;if(memory)context.attachedContext=JSON.stringify({kind:'untrusted_continuity_memory',...memory,untrusted_memory:true});const serializedContext=JSON.stringify(context);if(prompt.length>50000)throw Error('Agent requests are limited to 50,000 characters; use a structured Continuity checkpoint for larger context.');if(serializedContext.length>180000)throw Error('Session context exceeds the server transport limit. Use /compact before starting this run.');if(snap.excluded.length)report({type:'status',message:`${snap.excluded.length} binary, oversized or credential-bearing files excluded from the cloud snapshot.`});
31
- const headers={'Content-Type':'application/json',Accept:'text/event-stream',Authorization:`Bearer ${token}`,'Idempotency-Key':operation,'X-Vigthoria-Operation-Id':operation,'X-Vigthoria-Source-Product':process.env.VIGTHORIA_DECK_MODE==='1'?'vigthoria-workbench':'vigthoria-cli','X-Vigthoria-Agent-Lane':'cli'};
32
- const response=await fetcher(origin+(forkRun?'/api/runs-cli/'+encodeURIComponent(forkRun)+'/fork':'/api/v3-agent-cli/run'),{method:'POST',redirect:'error',headers,body:JSON.stringify(forkRun?{workspace_root:'',local_workspace_path:'',new_request:prompt,context:serializedContext,stream:true}:{request:prompt,model,preferred_model:model,requested_model:model,...(cliCommand?{cli_command:cliCommand}:{}),context:serializedContext,workspace_files:snap.files,...(serverContext?{context_id:serverContext}:{}),operation_id:operation,strict_mode:true,stream:true}),signal:signal?AbortSignal.any([signal,AbortSignal.timeout(1800000)]):AbortSignal.timeout(1800000)});
33
- if(!response.ok)throw Error(`V3 agent rejected the request (${response.status}): ${(await response.text()).slice(0,500)}`);
34
- let final=null,error=null,contextId=response.headers.get('x-context-id');const streamed=Object.create(null),writtenPaths=new Set();
35
- const stop=async()=>{if(!contextId)return;try{await fetcher(origin+'/api/v3-agent-cli/stop',{method:'POST',redirect:'error',signal:AbortSignal.timeout(10000),headers,body:JSON.stringify({context_id:contextId})});}catch{}};
36
- try{await consumeEvents(response,async event=>{if(event.context_id){if(contextId&&contextId!==event.context_id)throw Error('Agent context changed unexpectedly');contextId=event.context_id;}report(event);if(event.type==='tool_call'&&['write_file','edit_file'].includes(event.name||event.tool)&&typeof event.arguments?.path==='string')writtenPaths.add(event.arguments.path);if(event.type==='file_mutation'&&typeof event.path==='string')writtenPaths.add(event.path);if(event.type==='approval_required'){if(!contextId||typeof event.approval_id!=='string'||typeof event.command!=='string')throw Error('Invalid server approval request');const approved=await approveCommand(event.command);const answer=await fetcher(origin+'/api/v3-agent-cli/approval',{method:'POST',redirect:'error',signal:AbortSignal.timeout(10000),headers,body:JSON.stringify({context_id:contextId,approval_id:event.approval_id,approved})});if(!answer.ok)throw Error('Server did not acknowledge command approval');}if(['error','terminal_error'].includes(event.type))error=event.message||event.error||'Agent execution failed';if(event.type==='client_tool_request'){if(!broker||event.context_id!==contextId)throw Error('Unexpected local tool request');const result=await broker.call(event);const ack=await fetcher(origin+'/api/v3-agent-cli/client-tool-result',{method:'POST',redirect:'error',signal:AbortSignal.timeout(30000),headers,body:JSON.stringify({context_id:contextId,call_id:event.call_id,...result})});if(!ack.ok)throw Error('Local tool result was not acknowledged. Approved actions were not replayed.');}if(event.type==='client_inference_request')throw Error('Server requested an unsupported inference surface');if(event.type==='file_mutation'){if(typeof event.path!=='string')throw Error('Invalid file mutation');streamed[event.path]=event.action==='delete'?null:event.content;}if(event.type==='workspace_snapshot'&&event.files&&typeof event.files==='object')Object.assign(streamed,event.files);if(event.type==='tool_result'&&event.success&&['write_file','edit_file'].includes(event.name||event.tool)&&typeof event.arguments?.content==='string')streamed[event.target||event.arguments.path]=event.arguments.content;if(event.type==='complete')final=event;});}
37
- catch(e){await stop();throw Error(broker?`Agent outcome is unconfirmed. Approved local changes were retained; operation ${operation} was not replayed.`:`Agent outcome is unconfirmed. Project files were preserved; operation ${operation} was not replayed.`,{cause:e});}
38
- if(error)throw Error(String(error));if(!final)throw Error('Agent did not confirm completion. Project files were preserved.');
39
- const result=final.result||final;if(result.success===false||result.status==='failed'||result.status==='cancelled')throw Error(result.message||result.error||'Agent reported an unsuccessful run');if(broker)return {...result,appliedFiles:[...broker.changed],contextId};const files={...streamed,...(result.files||final.files||{})};const names=Object.keys(files).filter(name=>files[name]!==snap.files[name]&&!(files[name]===null&&!Object.hasOwn(snap.files,name)));const changed=Object.fromEntries(names.map(name=>[name,files[name]]));if(names.length&&!await approve(names))return{...result,appliedFiles:[],changesDeclined:true,contextId};
40
- const appliedFiles=names.length?applyFiles(snap,changed,{preserveSnapshotFormatting:true,writtenPaths}):[];return{...result,appliedFiles,contextId};
41
- }
42
- export async function agent(argv=[]){const parsed=parse(argv,['--workspace','-w','--model','-m','--prompt','-p','--resume','--command-json','--fork'],['--local-tools','--no-setup','--auto-approve','--debug','--no-save','--no-auto-save']);let one=argv.findIndex(v=>v==='--prompt'||v==='-p');if(one>=0&&parsed.args.length)throw Error('Supply either a positional task or --prompt');const directPrompt=one>=0?argv[one+1]:parsed.args.join(' ');const oneShot=!!directPrompt||argv.includes('--command-json');let controller,activeProgress;const lines=replInput(process.stdin,process.stdout,()=>{activeProgress?.pause();controller?.abort();});const settings=await setup(lines,directPrompt&&one<0?[...argv,'--no-setup']:argv);if(!settings){lines.close();return;}let serverContext=null,memory=null,pending=null;let history=[],session=randomUUID();const resumeIndex=argv.indexOf('--resume');if(resumeIndex>=0){const saved=loadSession(argv[resumeIndex+1]);if(saved.root!==settings.root){lines.close();throw Error('Resume from the original project directory or select it with --workspace');}history=saved.history;session=saved.id;serverContext=saved.serverContext||null;}const projectId=(root,useOverride=true)=>useOverride&&process.env.VIGTHORIA_CONTINUITY_PROJECT_ID||'workspace-'+createHash('sha256').update(root).digest('hex').slice(0,24);let project=projectId(settings.root);function save(){if(settings.autoSave)saveSession({id:session,root:settings.root,model:settings.model,serverContext,history});}
43
- async function checkpoint(force=false){if(!await memoryCredential()){if(force)throw Error('Connect a Continuity subscription in Workbench Settings and reopen the agent terminal first.');return;}if(!pending){const status=await memoryCall('status',{project_id:project});pending={project_id:project,session_id:session,base_revision:status.revision,idempotency_key:randomUUID(),state:{},messages:history,force_compact:force};}const appliedForce=pending.force_compact;const saved=await memoryCall('checkpoint',pending);pending=null;console.log(`Continuity checkpoint ${saved.checkpoint_id}, revision ${saved.revision}.`);if(force&&!appliedForce){await checkpoint(true);return;}if(force){memory=await memoryCall('recall',{project_id:project,budget:{max_chars:3000,max_utf8_bytes:12000,target_tokens:12000}});history.length=0;serverContext=null;console.log(`Compacted on the private server: ${memory.chars}/3000 characters. Pinned decisions retained.`);}}
44
- const stop=()=>{activeProgress?.pause();controller?.abort();};process.on('SIGINT',stop);
45
- async function execute(text,command=null){if(pending){console.error('A Continuity checkpoint is unconfirmed. Use /compact to retry it before starting another run.');return;}history.push({role:'user',content:text,id:randomUUID()});controller=new AbortController();lines.setBusy(true);activeProgress=taskProgress({theme:settings.theme});activeProgress.start();let outcome='failed';const runId=randomUUID();let eventIndex=0,toolIndex=0,lastMessage='';const runDeck=event=>deck({...event,runId,eventId:runId+':'+(++eventIndex)});try{runDeck({type:'agent_start'});const result=await runRemote(text,{root:settings.root,model:settings.model,providerKey:providerRoute(settings),localTools:parsed.options['local-tools']===true,cliCommand:command,forkRun:parsed.options.fork||null,signal:controller.signal,serverContext,memory,history,approveCommand:async command=>{if(settings.autoApprove)return true;activeProgress.pause();try{console.log('Verification command (on-demand workspaces run this on your machine):\n'+command);return await choose(lines,'Allow this verification command?',[{value:false,label:'Decline',description:'Keep the command from running.'},{value:true,label:'Allow command',description:'Run the displayed command with this account’s permissions in the selected workspace.'}],false,settings.theme)===true;}finally{activeProgress.resume();}},approve:async names=>{if(settings.autoApprove)return true;activeProgress.pause();try{console.log('Project file changes:\n'+names.join('\n'));return await choose(lines,'Apply '+names.length+' returned project file(s)?',[{value:false,label:'Decline',description:'Preserve the current local project files.'},{value:true,label:'Apply changes',description:'Apply these returned files to the selected local project.'}],false,settings.theme)===true;}finally{activeProgress.resume();}},report:event=>{activeProgress.update(event);if(['status','progress','message'].includes(event.type)&&typeof(event.content||event.message)==='string'){const text=event.content||event.message;if(event.type==='message')renderText(text,settings.theme);else console.log(paint(text,'muted',settings.theme));if(event.type==='message')lastMessage=text;}if(event.type==='tool_start'||event.type==='tool_end')runDeck(event);if(event.type==='pipeline_stage'){const labels={dispatcher:'Understanding your request',architect:'Planning the changes',executor:'Working on your project'};notice('info',(labels[event.stage]||'Working')+(event.model?' · '+visibleModelName(event.model,Boolean(settings.providerEnabled)):''),settings.theme);}if(settings.debugMode&&event.type==='tool_call')console.log(paint('› '+String(event.name||event.tool||'Working').replaceAll('_',' ')+(event.arguments?.path?' · '+event.arguments.path:''),'muted',settings.theme));if(settings.debugMode&&event.type==='tool_result'&&event.success===false)notice('warning','A project check needs another approach.',settings.theme);if(event.type==='tool_call')runDeck({type:'tool_start',tool:event.name||event.tool,index:++toolIndex});if(event.type==='tool_result')runDeck({type:'tool_end',tool:event.name||event.tool,success:event.success});}});serverContext=result.contextId||serverContext;const raw=result.content||result.response||result.summary||result.message||result;let content=typeof raw==='string'?raw:JSON.stringify(raw);if(lastMessage.startsWith(content))content=lastMessage;history.push({role:'assistant',content,id:randomUUID()});if(content!==lastMessage)renderText(content,settings.theme);try{save();}catch(e){console.error('Session save: '+e.message);}if(result.changesDeclined)console.log('Returned changes were declined. Project files were preserved.');runDeck({type:'report_ready',markdown:content});runDeck({type:'run_complete',success:!result.changesDeclined});outcome=result.changesDeclined?'cancelled':'success';try{await checkpoint();}catch(error){console.error('Continuity checkpoint was not confirmed: '+error.message+' Local session history was retained.');}}catch(error){if(controller.signal.aborted)outcome='cancelled';notice('error',error.message,settings.theme);if(oneShot)process.exitCode=1;try{runDeck({type:'run_complete',success:false});}catch(statusError){console.error('Agent status channel unavailable: '+statusError.message);}}finally{activeProgress?.finish(outcome);activeProgress=null;controller=null;lines.setBusy(false);}}
46
- try{section('Ready when you are','Paste your full request, then press Enter. Type /help for commands.',settings.theme);detail('Project',settings.root,settings.theme);detail('AI',routingLabel(settings)||modelLabel(settings.model),settings.theme);detail('Changes',settings.autoApprove?'Apply automatically':'Review before applying',settings.theme);console.log(paint('AI reasoning runs privately on Vigthoria. Large projects share source files as needed.','muted',settings.theme));const commandIndex=argv.indexOf('--command-json');if(commandIndex>=0){const command=JSON.parse(argv[commandIndex+1]);await execute(command.name+' '+command.args.join(' '),command);return;}if(directPrompt){await execute(directPrompt);return;}
47
- let multiline=null;while(true){const next=await lines.next(multiline===null);if(next.done)break;if(next.cancelled){multiline=null;continue;}const line=next.value.trimEnd();if(line==='{{{'){multiline=[];continue;}if(line.startsWith('{{{')&&line.endsWith('}}}')){await execute(line.slice(3,-3));continue;}if(multiline){if(line==='}}}'){const prompt=multiline.join('\n');multiline=null;if(prompt.trim())await execute(prompt);}else{multiline.push(line);if(multiline.join('\n').length>1000000){multiline=null;console.error('Prompt exceeds transport limit. Send a shorter brief.');}}continue;}if(['/exit','/quit'].includes(line.trim()))break;if(!line.trim())continue;if(line.trim()==='/compact'){try{await checkpoint(true);}catch(error){console.error(error.message);}continue;}if(line.trim()==='/help'){console.log('Commands: /help /status /models /model [MODEL] /workspace [PATH] /settings /providers /save /compact /exit. Use {{{ and }}} on separate lines for multiline input.');continue;}if(line.trim()==='/status'){try{console.log(JSON.stringify(await request('/api/user/subscription'),null,2));}catch(e){console.error(e.message);}continue;}if(line.trim()==='/providers'){await providerMenu(lines,settings.theme,settings);continue;}if(line.trim()==='/models'){try{const {models}=await import('./diagnostics.mjs');await models();}catch(e){console.error(e.message);}continue;}if(line.trim()==='/model'){const v=await selectModel(lines,settings.model,{theme:settings.theme});if(v!==null){disableProvider(settings);settings.model=v;setPreference('model',v);console.log('AI model: '+modelLabel(v));}continue;}if(line.startsWith('/model ')){const value=line.slice(7).trim();try{if(value!=='agent'){const data=await request('/api/user/credits/model-preferences');if(!modelChoices(data).some(m=>m.value===value&&!m.disabled))throw Error('Choose an available model with /model.');}disableProvider(settings);settings.model=value;setPreference('model',value);console.log('AI model: '+modelLabel(value));}catch(e){console.error(e.message);}continue;}if(line.trim()==='/workspace'||line.startsWith('/workspace ')){try{let value=line.slice(10).trim();if(!value){console.log('Current project: '+settings.root);const a=await lines.next('Project folder (Enter keeps the current folder): ');if(a.done||a.cancelled||!a.value.trim())continue;value=a.value.trim();}if(pending)throw Error('Resolve the pending Continuity checkpoint with /compact before switching projects.');const next=resolveWorkspace(value);const problem=workspaceIssue(next);if(problem)throw Error(problem);if(history.length)save();settings.root=next;setPreference('workspacePath',next);serverContext=null;memory=null;pending=null;history=[];session=randomUUID();project=projectId(next,false);console.log('Project changed to '+next+'. A new conversation starts here; your provider selection is kept.');}catch(e){console.error('Project not changed: '+e.message);}continue;}if(line.trim()==='/settings'){await settingsMenu(lines,settings);continue;}if(line.trim()==='/save'){try{saveSession({id:session,root:settings.root,model:settings.model,serverContext,history});console.log('Saved session '+session);}catch(e){console.error(e.message);}continue;}if(line.startsWith('/')){console.log('Unknown command. Use /help.');continue;}await execute(line);}
48
- }finally{lines.close();process.removeListener('SIGINT',stop);}}
@@ -1,14 +0,0 @@
1
- /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import {request,persistAccount,readAccount,hiddenInput} from './account.mjs';
5
- async function secretInput(){if(process.stdin.isTTY)return hiddenInput('CLI API key: ');let s='';for await(const chunk of process.stdin){s+=chunk;if(s.length>512)throw Error('API key input is too large');}return s.trim();}
6
- export async function apiKeys(argv=[]){const [action,...args]=argv;const opt=(k,d)=>args.includes(k)?args[args.indexOf(k)+1]:d;
7
- if(['login','set','use'].includes(action)){if(args.length)throw Error('Supply the key through hidden input or private stdin, never as an argument');const key=await secretInput();if(!/^vcli_[A-Za-z0-9_-]{43}$/.test(key))throw Error('Use a scoped Vigthoria CLI API key');await request('/api/cli/keys/status',{token:key});persistAccount({...readAccount(),apiKey:key,activeCredential:'api_key'});console.log('CLI API key verified and saved privately.');return;}
8
- if(action==='clear'){const a=readAccount();delete a.apiKey;delete a.activeCredential;persistAccount(a);console.log('Local API key cleared.');return;}
9
- if(action==='status'||action==='test'){console.log(JSON.stringify(await request('/api/cli/keys/status'),null,2));return;}
10
- if(action==='list'){console.log(JSON.stringify(await request('/api/cli/keys'),null,2));return;}
11
- if(action==='create'){const output=opt('--output');if(!output)throw Error('Use api-key create --name NAME --output PRIVATE_FILE; the secret is never printed');const target=path.resolve(output);const fd=fs.openSync(target,'wx',0o600);try{const r=await request('/api/cli/keys',{body:{name:opt('--name','CLI'),days:Number(opt('--days','90'))},token:readAccount().authToken});fs.writeFileSync(fd,r.token+'\n');console.log(JSON.stringify({id:r.id,name:r.name,expiresAt:new Date(r.expires_at_ms).toISOString(),privateFile:target,scope:r.scope},null,2));}catch(e){fs.closeSync(fd);fs.unlinkSync(target);throw e;}fs.closeSync(fd);return;}
12
- if(action==='revoke'){if(!args[0]||!args.includes('--yes'))throw Error('Use api-key revoke KEY_ID --yes');console.log(JSON.stringify(await request('/api/cli/keys/'+encodeURIComponent(args[0]),{method:'DELETE',token:readAccount().authToken}),null,2));return;}
13
- throw Error('Use api-key create, list, status, test, login, clear, or revoke.');
14
- }
@@ -1,121 +0,0 @@
1
- /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
- import {choose,banner,safe} from './terminal.mjs';
3
- import {preferences} from './preferences.mjs';
4
- export const commandHelp={
5
- provider:'provider setup\nprovider add openai|anthropic|openrouter --name NAME --accept-encrypted-storage\nprovider list | test KEY_ID | models KEY_ID | usage | off\nprovider use KEY_ID --planner MODEL --executor MODEL\nprovider remove KEY_ID --yes\nKeys are entered privately, sent over HTTPS and saved encrypted on Vigthoria. Your provider bills generation; no Vigthoria-paid fallback.',
6
- auth:'auth login [--email EMAIL] | logout | whoami\nAccount authentication; credentials are entered privately.',
7
- menu:'menu\nBrowse command families with arrow keys or numbers.',
8
- music:'music status JOB_ID\nRead the status of an existing music job.',
9
- update:'update [--check] [--prefix ABSOLUTE_PATH]\nVerify the signed stable feed and install a newer public client with lifecycle scripts disabled.',
10
- login:'login [--email EMAIL]\nSign in with hidden password input. Automation supplies the password on private stdin.',
11
- logout:'logout\nClear the current local account and CLI key connection.',
12
- status:'status\nRead authenticated account and product status.',whoami:'whoami\nRead authenticated account and product status.',
13
- replay:'replay RUN_ID\nRead the owned hosted run event log.',cancel:'cancel [CONTEXT_ID]\nList active runs, or cancel a selected context.',
14
- 'hyper-loop':'hyper-loop status','devtools':'devtools setup | roles | status\nCheck local DevTools and Desktop bridges without sending account credentials.','bridge':'bridge status\nCheck local DevTools and Desktop bridges without sending account credentials.',
15
- agent:'agent [--workspace DIR] [--model MODEL] [--prompt TASK] [--no-setup] [--local-tools] [--auto-approve] [--debug] [--no-save]\nInteractive setup selects a workspace and session settings. /workspace PATH switches projects. Large projects use on-demand source tools; planning stays hosted. /help lists session commands.',
16
- chat:'chat [--workspace DIR] [--model MODEL] [--prompt TASK] [--no-setup]\nSame hosted conversation and approval workflow as agent.',
17
- config:'config [setup | model | show | get KEY | set KEY VALUE]\nSettings: workspacePath, model, debugMode, autoApprove, autoSave, theme. Credentials use login or api-key.',
18
- 'api-key':'api-key create --name NAME --days 90 --output PRIVATE_FILE\napi-key list | status | test | login | clear\napi-key revoke KEY_ID --yes\nlogin reads the secret from hidden input or private stdin. Create/revoke require account login.',
19
- api:'api status | test [--json]\napi models [--json]\napi-key manages scoped CLI credentials. provider setup connects OpenAI, Anthropic or OpenRouter keys. Cloud models use hosted services.',
20
- doctor:'doctor [--check-api] [--json]\nCheck the installation and optionally authenticated services without generating paid output.',
21
- models:'models [--json]\nLive account catalog: local Assistant 9B and cloud models.',
22
- background:'background start PROMPT [--workspace DIR] [--model MODEL]\nbackground list | status JOB_ID | events JOB_ID | cancel JOB_ID\nbackground approve JOB_ID APPROVAL_ID --yes|--deny\nbackground apply JOB_ID --yes',
23
- history:'history [--local]\nHosted run history, or local saved sessions. Use chat-resume SESSION_ID to resume locally.',
24
- 'chat-resume':'chat-resume SESSION_ID [--workspace DIR] [--no-setup]',
25
- repo:'repo list | status | push [DIR] --name NAME --visibility private --yes\nrepo pull NAME --output EMPTY_DIR\nrepo review [REVIEW_ID] | share NAME --yes | delete NAME_OR_ID --yes',
26
- memory:'memory <status|checkpoint|compact|recall|export|delete> PROJECT_ID\nNon-status arguments are JSON on stdin. Requires a provisioned Continuity connection.',
27
- edit:'edit FILE --instruction TEXT [--apply] [--workspace DIR] [--model MODEL]',
28
- fix:'fix FILE [--type bugs|style|security|performance] [--apply] [--workspace DIR]',
29
- explain:'explain FILE [--lines 1-50] [--detail brief|normal|detailed] [--workspace DIR]',
30
- review:'review FILE [--format text|json|markdown] [--workspace DIR]',
31
- generate:'generate DESCRIPTION [--language LANG] [--output FILE] [--pro] [--workspace DIR]',
32
- security:'security scan | score | fix [--apply] [--workspace DIR]',
33
- init:'init DESCRIPTION [--language LANG] [--template NAME] [--workspace DIR]',
34
- creative:'creative plan BRIEF [--workspace DIR] [--model MODEL]',
35
- game:'game init NAME [--engine babylon] [--workspace DIR]\ngame run | validate [--workspace DIR] [--package-manager npm|pnpm|yarn|bun]',
36
- preview:'preview [--workspace DIR] [--port PORT] [--package-manager npm|pnpm|yarn|bun]',
37
- fork:'fork RUN_ID [MESSAGE]\nContinue an owned hosted run; returned project changes still require approval.',
38
- device:'device status | list | screenshot [--output FILE] | install APK | launch PACKAGE\ndevice logs | tcpip | connect ADDRESS | disconnect [ADDRESS] [--device ID]',
39
- workflow:'workflow templates | list | use TEMPLATE_ID [--name NAME] | run ID [--data JSON] | status ID\nworkflow delete ID --yes\nUses the authenticated VigFlow service; orchestration remains hosted.',
40
- deploy:'deploy plans | list | status [DOMAIN]\ndeploy preview | subdomain NAME | custom DOMAIN --yes [--workspace DIR]',
41
- wallet:'wallet status | balance',operator:'operator [--prompt TASK] | status',
42
- };
43
-
44
- const field=(label,flag=null,optional=false)=>({label,flag,optional});
45
- const workspace=field('Workspace folder (Enter uses the current directory)','--workspace',true);
46
- const action=(label,args,fields=[],confirm=null)=>({label,args,fields,confirm});
47
- const job=field('Job ID'),run=field('Run ID'),file=field('File path'),project=field('Project ID');
48
- const guides={
49
- provider:[action('Connect and manage provider keys',['provider','setup']),action('List provider keys',['provider','list']),action('View provider request history',['provider','usage']),action('Use Vigthoria account models',['provider','off'])],
50
- agent:[action('Open agent session setup',['agent'])],chat:[action('Open a chat session',['chat'])],
51
- 'chat-resume':[action('Resume a saved local session',['chat-resume'],[field('Session ID (see history --local)')])],
52
- operator:[action('Open hosted agent session',['operator']),action('Show orchestrator status',['operator','status'])],
53
- background:[action('Start a background task',['background','start'],[field('Task description'),workspace]),action('List background jobs',['background','list']),...['status','events'].map(a=>action('Show job '+a,['background',a],[job])),action('Cancel a job',['background','cancel'],[job],'Cancel this selected background job?'),action('Approve a pending command once',['background','approve'],[job,field('Approval ID')],'Approve this pending command once after reviewing background status?'),action('Apply completed job files',['background','apply'],[job],'Apply the completed job’s returned files to its original project?')],
54
- history:[action('Hosted run history',['history']),action('Saved local sessions',['history','--local'])],replay:[action('Read run events',['replay'],[run])],fork:[action('Continue an owned run',['fork'],[run,field('Follow-up request',null,true)])],cancel:[action('List active runs',['cancel']),action('Cancel a context',['cancel'],[field('Context ID')],'Cancel this selected agent context?')],
55
- edit:[action('Edit a file',['edit'],[file,field('Describe the edit','--instruction'),workspace])],
56
- fix:[action('Repair a file',['fix'],[file,workspace])],explain:[action('Explain a file',['explain'],[file,workspace])],review:[action('Review a file',['review'],[file,workspace])],
57
- generate:[action('Generate source',['generate'],[field('What should be generated?'),field('Output file','--output'),workspace])],
58
- init:[action('Initialize a project',['init'],[field('Project description'),workspace])],
59
- security:['scan','score','fix'].map(a=>action('Security '+a,['security',a],[workspace])),
60
- creative:[action('Plan a creative task',['creative','plan'],[field('Creative brief'),workspace])],
61
- game:[action('Initialize a game',['game','init'],[field('Game name'),workspace]),action('Run the project script',['game','run'],[workspace]),action('Validate the project',['game','validate'],[workspace])],preview:[action('Run a local project preview',['preview'],[workspace])],
62
- repo:[action('List my repositories',['repo','list']),action('Repository status',['repo','status']),action('Push a private project',['repo','push'],[field('Project folder'),field('Repository name','--name')],'Upload this project as a private repository?'),action('Pull a repository',['repo','pull'],[field('Repository name'),field('Empty destination folder','--output')]),action('Read a repository review',['repo','review'],[field('Review ID',null,true)]),action('Share a repository',['repo','share'],[field('Repository name')],'Share this selected repository?'),action('Delete a repository',['repo','delete'],[field('Repository name or ID')],'Permanently delete this selected repository?')],
63
- login:[action('Sign in privately',['login'])],logout:[action('Disconnect this local account',['logout'],[],'Clear this CLI’s saved account and key connection?')],status:[action('Show my account',['status'])],
64
- 'api-key':[action('Connect a key privately',['api-key','login']),action('Test the current credential',['api-key','test']),action('List key metadata',['api-key','list']),action('Create an expiring key',['api-key','create'],[field('Key name','--name'),field('Private output file','--output')]),action('Revoke a key',['api-key','revoke'],[field('Key ID')],'Immediately revoke this selected CLI key?'),action('Disconnect the local key',['api-key','clear'])],
65
- models:[action('Choose the default AI model',['config','model']),action('List available models',['models'])],api:[action('Test account and services',['api','test']),action('List available models',['api','models'])],wallet:[action('Show account funding',['wallet','status'])],
66
- workflow:[action('List my workflows',['workflow','list']),action('Browse templates',['workflow','templates']),action('Create from a template',['workflow','use'],[field('Template ID')],'Create a workflow from this template?'),action('Run a workflow',['workflow','run'],[field('Workflow ID'),field('Input JSON (optional)','--data',true)],'Execute this workflow with the supplied data?'),action('Read execution status',['workflow','status'],[field('Execution ID')]),action('Delete a workflow',['workflow','delete'],[field('Workflow ID')],'Permanently delete this selected workflow?')],
67
- device:[...['status','list'].map(a=>action('Device '+a,['device',a])),action('Capture a screenshot',['device','screenshot'],[field('Output PNG file','--output')]),action('Install an Android APK',['device','install'],[field('APK path')],'Install this APK on the connected Android device?'),action('Launch an Android app',['device','launch'],[field('Android package name')]),action('Read device logs',['device','logs']),action('Enable wireless device mode',['device','tcpip'],[],'Enable wireless ADB on the connected device?'),action('Connect a device',['device','connect'],[field('Device address')]),action('Disconnect a device',['device','disconnect'],[field('Device address',null,true)])],
68
- deploy:[...['plans','list'].map(a=>action('Hosting '+a,['deploy',a])),action('Hosting status',['deploy','status'],[field('Domain (optional)',null,true)]),action('Deploy a preview',['deploy','preview'],[workspace],'Upload and deploy this project preview?'),action('Deploy a subdomain',['deploy','subdomain'],[field('Subdomain name'),workspace],'Deploy this project to the selected subdomain?'),action('Deploy a custom domain',['deploy','custom'],[field('Domain'),workspace],'Deploy this project to the selected custom domain?')],
69
- 'hyper-loop':[action('HyperLoop status',['hyper-loop','status'])],devtools:[action('Set up provider keys',['devtools','setup']),action('Show model roles',['devtools','roles']),action('DevTools service status',['devtools','status'])],bridge:[action('Bridge service status',['bridge','status'])],music:[action('Read existing music job status',['music','status'],[job])],
70
- config:[action('Open guided settings',['config','setup']),action('Show saved settings',['config','show'])],doctor:[action('Check installation and authenticated services',['doctor','--check-api'])],update:[action('Check signed release',['update','--check']),action('Install a newer verified client',['update'],[],'Install the newer signed public client if available?')],memory:[action('Show Continuity connection instructions',['memory','--help'])],
71
- };
72
- export const commandTitles={provider:'Provider API keys',agent:'Start coding agent',chat:'Start a conversation','chat-resume':'Resume a saved session',operator:'Hosted agent and operator status',background:'Background jobs',history:'Run and session history',replay:'Read run events',fork:'Continue an owned run',cancel:'Active runs and cancellation',explain:'Explain code',review:'Review code',edit:'Edit a file',fix:'Repair a file',generate:'Generate code',init:'Initialize a project',security:'Security review',creative:'Creative planning',game:'Game projects',preview:'Local project preview',repo:'My repositories',login:'Sign in',logout:'Sign out',status:'My account',auth:'Account authentication','api-key':'CLI API keys',models:'Choose or list AI models',api:'API connection checks',wallet:'Account funding',workflow:'VigFlow workflows',device:'Android devices',deploy:'Project hosting','hyper-loop':'HyperLoop status',devtools:'DevTools status',bridge:'Bridge status',music:'Music job status',config:'CLI settings',doctor:'Installation diagnostics',update:'Verified updates',memory:'Hosted Continuity connection'};
73
- export const commandGroups=[
74
- {label:'Sessions & background jobs',description:'Agent conversations, saved sessions and hosted run lifecycle.',names:['agent','chat','chat-resume','operator','background','history','replay','fork','cancel']},
75
- {label:'Code & projects',description:'Explain, review, generate and repair source; creative and game projects.',names:['explain','review','edit','fix','generate','init','security','creative','game','preview']},
76
- {label:'Repositories',description:'Owned repository upload, download, sharing and reviews.',names:['repo']},
77
- {label:'Account, API keys & models',description:'Sign-in, scoped keys, available models and account funding.',names:['login','logout','status','api-key','provider','models','api','wallet']},
78
- {label:'Workflows, devices & services',description:'Hosted workflows, Android tools, hosting and service status.',names:['workflow','device','deploy','hyper-loop','devtools','bridge','music']},
79
- {label:'Settings, diagnostics & updates',description:'Guided settings, API checks, signed releases and Continuity.',names:['config','doctor','update','memory']},
80
- ];
81
- export async function commandMenu(lines,{guideOnly=false}={}){
82
- const theme=preferences().theme;if(!guideOnly)banner(process.stdout,theme);
83
- while(true){
84
- const group=await choose(lines,guideOnly?'Commands & capabilities':'Vigthoria command menu',[
85
- ...commandGroups.map((g,i)=>({value:i,label:g.label,description:g.description})),{value:'exit',label:guideOnly?'Back to session':'Exit',description:'Close this menu.'},
86
- ],0,theme);
87
- if(group===null||group==='exit')return null;
88
- const g=commandGroups[group];
89
- while(true){
90
- const name=await choose(lines,g.label,[...g.names.map(n=>({value:n,label:commandTitles[n]+' ('+n+')',description:commandHelp[n].split('\n')[0]})),{value:'back',label:'Back',description:'Choose another command family.'}],g.names[0],theme);
91
- if(name===null||name==='back')break;
92
- console.log('\nUsage: vigthoria '+commandHelp[name]+'\n');
93
- if(guideOnly)continue;
94
- const recipes=guides[name]||[action('Show help',[name,'--help'])];
95
- const index=await choose(lines,'Choose an action',[...recipes.map((a,i)=>({value:i,label:a.label,description:'vigthoria '+a.args.join(' ')})),{value:'back',label:'Back',description:'Return to commands.'}],0,theme);
96
- if(index===null||index==='back')continue;
97
- const recipe=recipes[index],argv=[...recipe.args];let aborted=false;
98
- for(const f of recipe.fields){while(true){const a=await lines.next(safe(f.label)+': ');if(a.done||a.cancelled){aborted=true;break;}const value=a.value.trim();if(!value&&!f.optional){console.log('Enter a value, or press Ctrl+C to go back.');continue;}if(value){if(f.flag)argv.push(f.flag);argv.push(value);}break;}if(aborted)break;}
99
- if(aborted)continue;
100
- console.log('\nSelected: vigthoria '+argv.map(s=>JSON.stringify(s)).join(' '));
101
- const yes=await choose(lines,recipe.confirm||'Run this command?',[
102
- {value:false,label:'Back',description:'Return without running this command.'},
103
- {value:true,label:'Run command',description:recipe.confirm||'Open the selected CLI command.'},
104
- ],false,theme);
105
- if(yes===true){if(recipe.confirm&&['background','repo','api-key','workflow','deploy'].includes(argv[0]))argv.push('--yes');return argv;}
106
- }
107
- }
108
- }
109
-
110
- export function normalizeArgv(argv){
111
- if(!argv.length)return [];
112
- const result=argv.flatMap(a=>a.startsWith('--')&&a.includes('=')?[a.slice(0,a.indexOf('=')),a.slice(a.indexOf('=')+1)]:[a]);
113
- const roots={a:'agent',c:'chat',op:'operator',runs:'history',bg:'background',flow:'workflow',repository:'repo',host:'deploy',adb:'device',vsec:'security',audio:'music',upgrade:'update',keys:'api-key',e:'edit',g:'generate',x:'explain',f:'fix',r:'review'};
114
- result[0]=roots[result[0]]||result[0];
115
- if(['agent','chat','operator','chat-resume'].includes(result[0]))for(let i=1;i<result.length;i++)if(result[i]==='--project')result[i]='--workspace';
116
- if(result[0]==='auth'&&['login','logout','whoami'].includes(result[1]))return [result[1]==='whoami'?'status':result[1],...result.slice(2)];
117
- const actions={repo:{ls:'list',upload:'push',download:'pull',rm:'delete'},workflow:{ls:'list',catalog:'templates','use-template':'use',rm:'delete'},background:{ls:'list'},deploy:{ls:'list'},devtools:{connect:'status'},wallet:{'cloud-status':'status'}};
118
- if(actions[result[0]]?.[result[1]])result[1]=actions[result[0]][result[1]];
119
- return result;
120
- }
121
- export function capabilityCatalog(){return {groups:commandGroups,commands:Object.keys(guides).map(name=>({name,title:commandTitles[name],usage:commandHelp[name],actions:guides[name].map(a=>({label:a.label,argv:a.args,fields:a.fields,confirmation:!!a.confirm}))}))};}
@@ -1,49 +0,0 @@
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 {createHash,randomUUID} from 'node:crypto';
6
- import {request,origin,accessToken,configDirectory} from './account.mjs';
7
- import {providerRoute} from './providers.mjs';
8
- import {snapshot,applyFiles} from './workspace.mjs';
9
- import {configuredRoot,preferences} from './preferences.mjs';
10
- const base='/api/v3-agent-cli';
11
- const print=d=>console.log(JSON.stringify(d,null,2));
12
- const id=s=>{if(!/^[a-zA-Z0-9._:-]{1,128}$/.test(s||''))throw Error('Invalid job/run identifier');return encodeURIComponent(s);};
13
- export function parse(argv,values=[],booleans=[]){const args=[],options={};for(let i=0;i<argv.length;i++){const a=argv[i];if(!a.startsWith('-')){args.push(a);continue;}const eq=a.indexOf('=');const name=eq<0?a:a.slice(0,eq);if(values.includes(name)){const v=eq<0?argv[++i]:a.slice(eq+1);if(!v||v.startsWith('--'))throw Error(name+' requires a value');options[name.replace(/^--/,'')]=v;}else if(booleans.includes(name)&&eq<0)options[name.replace(/^--/,'')]=true;else throw Error('Unknown option: '+name);}return {args,options};}
14
- export async function taskCommand(name,argv){const aliases={e:'edit',g:'generate',x:'explain',f:'fix',r:'review'};name=aliases[name]||name;let command=name;if(name==='security'){const action=argv.shift()||'scan';if(!['scan','score','fix'].includes(action))throw Error('Use security scan, score or fix');command='security-'+action;}if(name==='creative'){const action=argv.shift();if(action==='workflows'){print(await request('/api/v2/health'));return;}if(action!=='plan')throw Error('Use creative plan BRIEF');command='creative-plan';}if(name==='game'){if(argv.shift()!=='init')throw Error('Use game init NAME; run and validate through your project package manager');command='game-init';}
15
- const short={edit:{'-i':'instruction','-m':'model'},generate:{'-l':'language','-o':'output','-m':'model','-p':'pro'},explain:{'-l':'lines','-d':'detail'},fix:{'-t':'type'},review:{'-f':'format'}}[name]||{};
16
- const {args,options}=parse(argv,[...Object.keys(short).filter(k=>short[k]!=='pro'),'--instruction','--language','--output','--detail','--lines','--type','--format','--engine','--template','--workspace','--model'],[...Object.keys(short).filter(k=>short[k]==='pro'),'--apply','--pro','--debug','--no-save','--auto-approve']);
17
- for(const [key,long] of Object.entries(short))if(Object.hasOwn(options,key)){options[long]=options[key];delete options[key];}
18
- const forward=['--no-setup'];for(const k of ['workspace','model'])if(options[k]){forward.push('--'+k,options[k]);delete options[k];}for(const k of ['debug','no-save','auto-approve'])if(options[k]){forward.push('--'+k);delete options[k];}if(options.apply){forward.push('--auto-approve');}forward.push('--command-json',JSON.stringify({name:command,args,options}));const {agent}=await import('./agent.mjs');return agent(forward);
19
- }
20
- function jobFile(job){return path.join(configDirectory(),'cli-jobs',id(job)+'.json');}
21
- export async function background(argv){const [action,...rest]=argv;if(action==='list'||!action)return print(await request(base+'/background'));if(action==='status')return print(await request(base+'/background/'+id(rest[0])));if(action==='events')return print(await request(base+'/background/'+id(rest[0])+'/events'));if(action==='cancel')return print(await request(base+'/background/'+id(rest[0])+'/cancel',{body:{}}));
22
- if(action==='approve'){
23
- if(rest.length!==3||!['--yes','--deny'].includes(rest[2]))throw Error('Use background approve JOB_ID APPROVAL_ID --yes (or --deny) after reviewing background status.');
24
- const [job,approval,decision]=rest;id(job);id(approval);
25
- const status=await request(base+'/background/'+id(job));
26
- const pending=(status.pending_approvals||[]).find(a=>a.approval_id===approval&&a.context_id===job);
27
- if(!pending)throw Error('That approval is not pending for this background job.');
28
- console.log((decision==='--yes'?'Approve once: ':'Decline: ')+pending.command);
29
- return print(await request(base+'/approval',{body:{context_id:job,approval_id:approval,approved:decision==='--yes',command:pending.command,allow_mode:'once'}}));
30
- }
31
- if(action==='start'){const {args,options}=parse(rest,['--workspace','--model'],[]);if(!args.length)throw Error('Use background start PROMPT');const root=configuredRoot(options.workspace?['--workspace',options.workspace]:[]),snap=snapshot(root);const ref='workspace:'+createHash('sha256').update(root).digest('hex');const body={request:args.join(' '),model:options.model||(preferences().providerEnabled?'byok':preferences().model),workspace_files:snap.files,context:JSON.stringify({...(options.model?{}:(providerRoute()?{providerKey:providerRoute(),agentExecutionPolicy:{explicitModel:true,cloudSelected:true}}:{})),executionSurface:'cli',clientSurface:'cli',localMachineCapable:false,workspaceHydrationRequired:true,localWorkspaceRef:ref,localWorkspacePath:ref,localWorkspaceName:path.basename(root),localWorkspaceSummary:{name:path.basename(root),path:ref,files:Object.keys(snap.files),fileCount:Object.keys(snap.files).length},approvalLevel:'confirm',clientToolExecution:false})};const r=await request(base+'/background',{body});const file=jobFile(r.job_id);fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});if(fs.readdirSync(path.dirname(file)).length>=100)throw Error('Job started, but local job metadata limit reached; retain job id '+r.job_id);fs.writeFileSync(file,JSON.stringify({root,hashes:snap.hashes}),{flag:'wx',mode:0o600});return print(r);}
32
- if(action==='apply'){if(!rest.includes('--yes'))throw Error('Use background apply JOB_ID --yes after reviewing status and events');const job=rest[0],saved=JSON.parse(fs.readFileSync(jobFile(job),'utf8'));const r=await request(base+'/background/'+id(job)+'/files');if(!['completed','complete','succeeded'].includes(r.status))throw Error('Background job is not confirmed complete');const current=snapshot(saved.root);const original={...current,hashes:saved.hashes};const changed=Object.fromEntries(Object.entries(r.files).filter(([name,text])=>text!==current.files[name]));return print({appliedFiles:applyFiles(original,changed)});}
33
- throw Error('Use background start, list, status, events, approve, apply or cancel.');
34
- }
35
- export async function history(argv=[]){if(argv.includes('--local')){const {listSessions}=await import('./session-state.mjs');return print({sessions:listSessions()});}print(await request('/api/runs-cli?limit=20'));}
36
- export async function replay(run){print(await request('/api/runs-cli/'+id(run)+'/events'));}
37
- export async function cancel(context){if(!context){print(await request('/api/runs-cli/active'));return;}print(await request(base+'/stop',{body:{context_id:context}}));}
38
- export async function services(name,argv){const [action,...args]=argv;if(['devtools','bridge'].includes(name)&&(!action||action==='status')){const {bridgeStatus}=await import('./local-tools.mjs');return bridgeStatus();}const gets={
39
- 'wallet':{'status':'/api/user/credits/model-preferences','balance':'/api/user/credits/model-preferences'},
40
- 'deploy':{'plans':'/api/hosting/plans','list':'/api/hosting/domains','status':args[0]?'/api/hosting/domain/'+encodeURIComponent(args[0])+'/status':'/api/hosting/status'},
41
- 'hyper-loop':{'status':'/api/hyperloop/health'},'devtools':{'status':'/api/devtools/status'},
42
- 'bridge':{'status':'/api/devtools/status'},
43
- 'operator':{'status':'/api/bmad/orchestrator/status'},
44
- 'music':{'status':args[0]?'/api/music/status/'+encodeURIComponent(args[0]):null},
45
- };
46
- const route=gets[name]?.[action||'status'];if(route)return print(await request(route));
47
- if(name==='deploy'&&['preview','subdomain','custom'].includes(action)){const {args:pos,options}=parse(args,['--workspace'],['--yes']);if(!options.yes)throw Error('Deployment requires --yes after reviewing the project and destination');const snap=snapshot(configuredRoot(options.workspace?['--workspace',options.workspace]:[]));const body={files:Object.entries(snap.files).map(([path,content])=>({path,content})),projectName:path.basename(snap.root),...(action==='subdomain'?{subdomain:pos[0]}:action==='custom'?{domain:pos[0]}:{})};return print(await request('/api/hosting/deploy/'+action,{body}));}
48
- throw Error('Use '+name+' --help for supported actions.');
49
- }
@@ -1,12 +0,0 @@
1
- /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
- import {readFile} from 'node:fs/promises';
3
- export async function memoryCredential(){return process.env.VIGTHORIA_CONTINUITY_TOKEN_FILE?(await readFile(process.env.VIGTHORIA_CONTINUITY_TOKEN_FILE,'utf8')).trim():process.env.VIGTHORIA_CONTINUITY_TOKEN;}
4
- export async function memoryCall(tool,args,{fetcher=fetch}={}){
5
- if(!['status','checkpoint','recall','export','delete'].includes(tool))throw Error('Unknown memory tool');
6
- const token=await memoryCredential();if(!token)throw Error('Connect a provisioned Continuity credential in Workbench Settings first.');
7
- const body=JSON.stringify(args);if(Buffer.byteLength(body)>2_000_000)throw Error('Checkpoint exceeds the transport limit; no history was discarded.');
8
- const response=await fetcher(`https://coder.vigthoria.io/continuity/v1/tools/vigthoria_memory_${tool}`,{method:'POST',redirect:'error',signal:AbortSignal.timeout(30000),headers:{Authorization:`Bearer ${token}`,'Content-Type':'application/json'},body});
9
- let length=0;const chunks=[],limit=tool==='export'?150_000_000:256_000;
10
- for await(const chunk of response.body){length+=chunk.length;if(length>limit)throw Error('Continuity response exceeds transport limit');chunks.push(chunk);}
11
- const result=JSON.parse(Buffer.concat(chunks).toString('utf8'));if(!response.ok)throw Error(result.error||`Continuity request rejected (${response.status})`);return result;
12
- }
@@ -1,16 +0,0 @@
1
- /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- let sequence=0;
5
- export function writeDeckRecord(directory,event){
6
- if(!path.isAbsolute(directory)||fs.lstatSync(directory).isSymbolicLink()||!fs.statSync(directory).isDirectory())throw Error('Agent status channel is unavailable. Check terminal output and project files before continuing.');
7
- const body=Buffer.from(JSON.stringify(event));
8
- if(body.length>256*1024)throw Error('Agent status record exceeds its transport limit.');
9
- let size=0,count=0;
10
- for(const name of fs.readdirSync(directory)){const info=fs.lstatSync(path.join(directory,name));if(!info.isFile()||info.isSymbolicLink())throw Error('Invalid agent status channel entry.');size+=info.size;count++;}
11
- if(count>=1024||size+body.length>8*1024*1024)throw Error('Agent status channel is full. Review the current run before continuing.');
12
- const name=String(++sequence).padStart(12,'0');
13
- const temporary=path.join(directory,name+'.tmp'),final=path.join(directory,name+'.json');
14
- try{fs.writeFileSync(temporary,body,{flag:'wx',mode:0o600});if(fs.existsSync(final))throw Error('Agent status identity collision.');fs.renameSync(temporary,final);}
15
- finally{try{fs.unlinkSync(temporary);}catch{}}
16
- }
@@ -1,8 +0,0 @@
1
- /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
- import {accessToken,request,readAccount} from './account.mjs';
3
- import {preferences} from './preferences.mjs';
4
- import {VERSION} from './terminal.mjs';
5
- export async function models({json=false}={}){if(preferences().providerEnabled){const {providerRoute}=await import('./providers.mjs');const route=providerRoute();const data=await request('/api/v3-agent-cli/providers/'+route.keyId+'/models');const result={provider:data.key.provider,key:data.key,models:data.models,planningModel:route.plannerModel,codingModel:route.executorModel,billing:'your_provider_account'};if(json)console.log(JSON.stringify(result,null,2));else{console.log('Your provider models · '+data.key.provider+' · '+data.key.maskedKey);for(const m of data.models)console.log(' '+m.id+' — '+m.label);console.log('Planning: '+route.plannerModel+' · Coding: '+route.executorModel+'\nUse provider setup to change these roles, or provider off for Vigthoria models.');}return result;}const data=await request('/api/user/credits/model-preferences');const local=data.localModels||[],cloud=data.allowedCloudModels||[];const result={local,cloud,defaultModel:preferences().model,balances:{purchased:data.purchasedBalance,subscription:data.subscriptionBalance},billingMode:data.isMasterAdmin?'company_expense':data.cloudBillingMode};if(json)console.log(JSON.stringify(result,null,2));else{console.log('Local models');for(const m of local)console.log(' '+m.id+' — '+m.label);console.log(data.isMasterAdmin?'\nCloud models (Master Admin company expenses)':'\nCloud models (account access and funded credits required)');for(const m of cloud)console.log(' '+m.alias+' — '+m.displayName+(m.available===false?' [unavailable]':''));console.log('\nUse --model MODEL on agent/chat, or config set model MODEL.');}return result;}
6
- export async function diagnostics({checkApi=false,json=false}={}){const report={version:VERSION,node:process.versions.node,workspace:process.cwd(),credentialPresent:!!accessToken(),settings:preferences(),checks:[]};if(checkApi){for(const [name,route] of [['account','/api/user/subscription'],['agent','/api/v3-agent-cli/health'],['commands','/api/v3-agent-cli/commands'],['models','/api/user/credits/model-preferences'],...(preferences().providerEnabled?[['provider','/api/v3-agent-cli/providers/'+preferences().providerKeyId+'/test']]:[])]){try{const d=await request(route,name==='provider'?{body:{}}:{});report.checks.push({name,ok:true,...(name==='models'?{localModels:(d.localModels||[]).map(m=>m.id),cloudModels:(d.allowedCloudModels||[]).map(m=>m.alias),purchasedBalance:d.purchasedBalance,subscriptionBalance:d.subscriptionBalance,companyFunded:d.isMasterAdmin===true}:name==='account'?{plan:d.subscription?.plan,access:d.subscription?.accessLabel}:name==='agent'?{status:d.status}: {count:d.commands?.length})});}catch(e){report.checks.push({name,ok:false,error:e.message,code:e.code});}}}
7
- if(json)console.log(JSON.stringify(report,null,2));else{console.log(`Vigthoria CLI ${report.version} · Node ${report.node}`);console.log('Credential: '+(report.credentialPresent?'configured':'sign in with vigthoria login'));for(const c of report.checks)console.log((c.ok?'✓ ':'✗ ')+c.name+(c.error?': '+c.error:''));const m=report.checks.find(c=>c.name==='models');if(m)console.log('Local: '+(m.localModels||[]).join(', ')+(m.companyFunded?'\nCloud funding: company expenses (Master Admin)':'\nCloud credits: '+(m.purchasedBalance||0)+' purchased / '+(m.subscriptionBalance||0)+' subscription'));}
8
- if(report.checks.some(c=>!c.ok))process.exitCode=1;return report;}
@@ -1,28 +0,0 @@
1
- /* Copyright (c) 2026 Vigthoria Technologies. All rights reserved. Proprietary. */
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import {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
- }
@@ -1,13 +0,0 @@
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;}
@@ -1,17 +0,0 @@
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);}}