vigthoria-cli 0.0.0-stage → 2.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,3 @@
1
+ Copyright (c) 2026 Vigthoria Technologies. All rights reserved.
2
+
3
+ Proprietary software. No permission to copy, modify, redistribute, sublicense, or sell this software is granted without an express written agreement from Vigthoria. Third-party components retain their respective licenses.
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # Vigthoria CLI 2.3.7
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Copyright (c) 2026 Vigthoria Technologies. All rights reserved.
4
+
5
+ Install Node.js LTS (24 or newer recommended), then reopen your terminal.
6
+
7
+ Windows PowerShell:
8
+
9
+ ```powershell
10
+ Invoke-WebRequest https://extension.vigthoria.io/install.ps1 -OutFile "$env:TEMP\vigthoria-install.ps1"
11
+ powershell -NoProfile -ExecutionPolicy Bypass -File "$env:TEMP\vigthoria-install.ps1"
12
+ vigthoria.cmd --version
13
+ vigthoria.cmd login
14
+ ```
15
+
16
+ macOS / Linux:
17
+
18
+ ```sh
19
+ curl -fsSL https://extension.vigthoria.io/install.sh -o /tmp/vigthoria-install.sh
20
+ sh /tmp/vigthoria-install.sh --prefix "$HOME/.local"
21
+ export PATH="$HOME/.local/bin:$PATH"
22
+ vigthoria --version
23
+ vigthoria login
24
+ ```
25
+
26
+ The installer verifies SHA-256 and the Vigthoria Ed25519 release signature before installing the pinned package with lifecycle scripts disabled. The npm registry channel contains the same reviewed thin client. When this release is listed on npm, install with `npm install -g vigthoria-cli` and update with `npm update -g vigthoria-cli`. The signed installer remains available independently. Downloaded .tgz files are npm packages; extracting them in Explorer does not install commands.
27
+
28
+ Login prompts for your account email and a hidden password. Automated callers can supply the password through private stdin with `vigthoria login --email EMAIL`. Password arguments are never accepted. Run `vigthoria --help` for supported commands.
29
+
30
+ Workbench installs its verified bundled CLI and private Windows Node runtime automatically. Use Settings → Repair verified CLI if repair is needed. No separate global npm install is required for Workbench.
31
+
32
+ This proprietary thin client provides hosted agent/chat transport, scoped Community repository operations and Continuity connections. Core memory policy, model prompts, planning, ranking and provider credentials remain private on Vigthoria servers. Product access and paid execution are checked by the service. Continuity checkpoint/recall requires its own provisioned connection; owner export/delete remain available after expiry.
33
+
34
+ Repository push and pull preserve approved portable Prompt Engine plans and hash-verified VGP assets. Credentials, runner locks and execution receipts are excluded. Managed editors may provide a private account-owned credential file through VIGTHORIA_AUTH_TOKEN_FILE; it is never exported with the project.
35
+
36
+ ## Current handbooks (19 November 2026)
37
+
38
+ User PDFs: [English](https://landing.vigthoria.io/docs/pdf/VIGTHORIA_CLI_USER_HANDBOOK_EN.pdf) · [Deutsch](https://landing.vigthoria.io/docs/pdf/VIGTHORIA_CLI_USER_HANDBOOK_DE.pdf). Administrator editions are maintained separately for private distribution. CLI 2.3.7 provides branded interactive session setup, workspace/settings selection, coding commands, API diagnostics, scoped API keys, model selection, background jobs and run history. The private engine is never packaged.
39
+
40
+
41
+ ## Restored terminal workflow
42
+
43
+ Paste a full multiline request into the conversation, then press Enter to send it as one task. Supported terminals retain pasted line breaks without starting a request for each line. You can also use `{{{` and `}}}` on separate lines for explicit multiline entry.
44
+
45
+ Run `vigthoria agent` to open the branded session setup. Select the intended project before starting. Use `--workspace /path/to/project --no-setup` for automation, and `--prompt "TASK"` for one request. `/help` lists interactive commands; `/save` saves a private local session, and `chat-resume SESSION_ID` resumes it. `history --local` lists saved sessions. Hosted Continuity remains a separate provisioned connection.
46
+
47
+ `doctor --check-api` and `api test` check authentication, the CLI backend, command adapters and the current account model catalog. `models` lists the local Assistant 9B and the released cloud aliases. `--model MODEL` selects a model explicitly. Canonical Master Admin company accounts use company expense accounting without customer credits. Other accounts use current product authority, saved cloud consent and funded wallet reservations.
48
+
49
+ Use `explain FILE`, `review FILE`, `edit FILE --instruction TEXT`, `fix FILE`, or `generate DESCRIPTION --output FILE`. Operation instructions are resolved on the private server. Review returned changes before applying them; `--apply` explicitly approves a coding command's changes and verification commands. `background`, `history`, `replay` and `cancel` expose the hosted job lifecycle.
50
+
51
+ ## Scoped CLI API keys
52
+
53
+ `api-key create --name workstation --output /private/path/key.txt` creates an expiring key under your authenticated account. The secret is written once to an owner-private file and never printed. Use `api-key login` with hidden terminal input or private stdin; `api-key test` verifies it. `api-key list` shows metadata, and `api-key revoke KEY_ID --yes` revokes a selected key immediately. A scoped key cannot create another key or access unrelated administration routes. It does not carry a model-provider credential or grant spending authority.
54
+
55
+ Distribution uses signed Vigthoria downloads and a separately authenticated npm registry release of the same reviewed archive. The source checkout stays marked private; only the allowlisted staging directory is publishable. The artifact contains only the allowlisted public terminal/transport modules, package metadata, README and proprietary license. Server prompts, planners, policy engines, provider credentials and backend source remain private.
56
+
57
+ `workflow` restores authenticated VigFlow templates and owned workflow lifecycle commands. `preview` and `game run/validate` use the selected project's package scripts without a shell or automatic dependency installation. `device` is a local Android platform-tools broker; Android tooling and a connected device are required for hardware operations. `fork` continues an owned hosted run with the normal file approvals. `update` verifies the signed release feed and artifact before installing a newer public client.
58
+
59
+ ## Guided menus
60
+
61
+ `vigthoria` or `vigthoria menu` opens the command-family picker in a terminal. Use Up/Down and Enter, or type a number and press Enter; Escape goes back. Commands with required values prompt for each value, preserve paths with spaces, and show the selected command before running it. Destructive actions require a separate confirmation. Noninteractive help stays plain text.
62
+
63
+ `vigthoria agent` opens session setup. Session settings use readable labels and explicit On/Off choices. `Choose AI model` loads the current account catalog, explains Automatic routing, and distinguishes cloud models from the Assistant 9B hosted on Vigthoria servers. Selecting a model starts no generation and does not enable cloud consent or change account funding. `config setup`, `config model`, `/settings` and `/model` use the same guided controls.
64
+
65
+ The default header uses a cyan frame, bright white title, lighter subtitle and muted version. Violet and plain themes are available under Session settings. `NO_COLOR` is respected. `commands --json` exposes the public command and action catalog for inspection.
66
+
67
+ This is a hosted client. Legacy local Knowledge, VigBase, API-module discovery, Legion execution and experimental V4 launchers are not included; several advanced 1.x flags and subcommands also remain unavailable. Existing command names do not imply complete 1.x feature parity.
68
+
69
+ ## Your own provider API keys
70
+
71
+ Run `vigthoria provider setup`, or select **Account & API → Provider API keys** in agent setup. OpenAI, Anthropic and OpenRouter keys have a separate hidden entry field. Confirm encrypted account storage, name the key, then select a planning model and a coding model. You may use the same model for both roles. Sign in to Vigthoria first.
72
+
73
+ Your provider key travels over HTTPS to the private Vigthoria backend, is encrypted at rest in an account-owned vault, and is used only with the selected provider’s fixed official API. The public client saves only key IDs and model preferences. The server performs inference; its proprietary prompts, tools and engine remain private. This is hosted key storage, not a local-only vault. Never paste a provider key into the CLI API-key field, a chat prompt, a command argument or a project file.
74
+
75
+ `provider test KEY_ID` verifies authentication and model availability without generating output. `provider models KEY_ID` lists models. `provider use KEY_ID --planner MODEL --executor MODEL` enables the route for foreground and background tasks on this machine. `provider off` selects Vigthoria account models again. Selecting a Vigthoria model explicitly also overrides the provider route. `devtools setup` and `devtools roles` expose the same setup and current role assignments. `/providers` manages the route during a conversation.
76
+
77
+ Provider generation bills your own provider account and does not debit Vigthoria model credits. Product access, run limits and workspace safety still apply. Errors stop the provider route; they never silently fall back to Vigthoria-funded inference. `provider usage` shows request outcomes and available provider usage; the provider’s billing dashboard is authoritative. An uncertain result is never automatically replayed. Remove a saved key with `provider remove KEY_ID --yes`; invalidate it through the provider if revocation is required.
78
+
79
+ Automation can supply a key through private stdin to `provider add openai --name NAME --accept-encrypted-storage` (also `anthropic` or `openrouter`). Do not put the secret in a shell command or history. NVIDIA and custom provider origins are not supported in this release. This restoration does not implement every legacy local-only command family.
80
+
81
+ `background status JOB_ID` shows pending commands. Review them before `background approve JOB_ID APPROVAL_ID --yes`; use `--deny` to refuse. Each approval is bound to the selected owned job and allows that command once. A failed or incomplete background agent cannot be marked complete or applied.
82
+
83
+ ## Project selection and large projects
84
+
85
+ Start in the actual project: `vigthoria agent --workspace /path/to/project`. A parent directory such as `/var/www` cannot be used as a single project. Setup checks the selected directory before starting. Mentioning another folder in a message does not change the project boundary. Use `/workspace PATH` to switch while chatting; this starts a new conversation and keeps your chosen provider.
86
+
87
+ Large foreground projects automatically use bounded local source tools rather than uploading the entire repository. `--local-tools` selects that mode explicitly. File discovery respects Git ignores, excludes symlinks, credentials, virtual environments, dependency/vendor trees, runtime data, logs, backups and binary media. Source files are read in bounded line ranges as the private agent requests them. File edits and local commands use your approval settings. Approved local edits happen during the run and are retained if the connection later fails; an uncertain action is never automatically replayed. Shell commands run with your account’s permissions in the selected project; there is no local OS sandbox.
88
+
89
+ Background jobs still use a bounded source snapshot because they run after the terminal disconnects. They retain the existing transfer bounds. The backend’s private planner and provider vault are not included in the public source-tool transport.
90
+
91
+ Menus now use clearer selection colours, quieter descriptions, readable provider model names sorted by version, and concise connection summaries. The plain theme and NO_COLOR remain supported. CLI/API JSON commands remain available for automation.
92
+
93
+ While an agent works, supported interactive terminals show an animated task panel with the current task and accepted completion count. It pauses for approval and leaves the final result visible. Redirected output, plain terminals and Workbench machine status streams retain readable logs.
94
+
95
+ On-demand file mutations include checksummed original-source receipts. A partial or numbered read preview is never a rollback copy. Rollback preserves complete source bytes and refuses to overwrite a file changed since the rejected edit.
96
+
97
+ Source reads provide a complete, checksum-verified source receipt for private syntax verification even when the visible read is a numbered excerpt. Only requested source files are shared; planning and verification policy stay hosted.
98
+
99
+ ## Client visibility and hosted implementation
100
+
101
+ Installed client code is inspectable. The public package contains terminal rendering, account/API transport, update verification and the local file/command approval broker. It does not contain the proprietary planner, executor, system prompts, model-routing decisions, account funding policy or provider vault. Those run only on Vigthoria servers. Minification, compilation and the proprietary license are not confidentiality boundaries for code delivered to a user.
102
+
103
+ Version 2.3.7 also records timeout/cancellation as unsuccessful even if a stopped local command exits with code zero. Cancellation while an approval prompt is pending cannot start the approved command or apply the pending file mutation. Previously accepted local edits remain available for recovery.
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "vigthoria-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.3.8",
4
+ "description": "Vigthoria CLI — proprietary hosted coding assistant client",
5
+ "type": "module",
6
+ "license": "UNLICENSED",
7
+ "private": false,
8
+ "publishConfig": {
9
+ "registry": "https://registry.npmjs.org/",
10
+ "access": "public"
11
+ },
12
+ "author": "Vigthoria Technologies",
13
+ "engines": {
14
+ "node": ">=20.19.0"
15
+ },
16
+ "bin": {
17
+ "vigthoria": "public-dist/index.mjs",
18
+ "vig": "public-dist/index.mjs",
19
+ "vigthoria-chat": "public-dist/index.mjs"
20
+ },
21
+ "files": [
22
+ "public-dist/*.mjs",
23
+ "LICENSE",
24
+ "README.md"
25
+ ]
26
+ }
@@ -0,0 +1,38 @@
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.');}
@@ -0,0 +1,48 @@
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);}}
@@ -0,0 +1,14 @@
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
+ }
@@ -0,0 +1,121 @@
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}))}))};}
@@ -0,0 +1,49 @@
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
+ }
@@ -0,0 +1,12 @@
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
+ }
@@ -0,0 +1,16 @@
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
+ }
@@ -0,0 +1,8 @@
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;}