@nativestudio/cli 0.3.0-rc.14 → 0.3.0-rc.15
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/COMPATIBILITY.json +11 -11
- package/components/runtime.json +7 -7
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-2AI3WF2O.js → chunk-5UJEP7FY.js} +1 -1
- package/dist/_chunks/chunk-AAGFHT2D.js +1 -0
- package/dist/_chunks/{chunk-ROBBF33U.js → chunk-BBTZJB2G.js} +1 -1
- package/dist/_chunks/chunk-BX2SNMA4.js +1 -0
- package/dist/_chunks/chunk-CFZNDURD.js +1 -0
- package/dist/_chunks/{chunk-3AVC742O.js → chunk-FX5UVDTH.js} +1 -1
- package/dist/_chunks/{chunk-U7ECMITP.js → chunk-H6EZKOYR.js} +1 -1
- package/dist/_chunks/chunk-I5KYSPUJ.js +1 -0
- package/dist/_chunks/chunk-KOCUZ3AE.js +1 -0
- package/dist/_chunks/{chunk-RDIMORUT.js → chunk-NPDLPC5B.js} +1 -1
- package/dist/_chunks/{chunk-RK2P3UVF.js → chunk-NQVUVPW5.js} +1 -1
- package/dist/_chunks/{chunk-VD3OQ743.js → chunk-O47YYPL7.js} +1 -1
- package/dist/_chunks/{chunk-6LY4JYSG.js → chunk-OVIR77ET.js} +1 -1
- package/dist/_chunks/{chunk-VDNNFVTZ.js → chunk-OW6R4MAQ.js} +1 -1
- package/dist/_chunks/{chunk-VKLS4QK5.js → chunk-PB2HLRXG.js} +1 -1
- package/dist/_chunks/chunk-RUPH3HZ2.js +1 -0
- package/dist/_chunks/chunk-SAPEOZ2V.js +1 -0
- package/dist/_chunks/chunk-SKAVQ4UW.js +1 -0
- package/dist/_chunks/{chunk-C62JAWRQ.js → chunk-TTB7CYC5.js} +1 -1
- package/dist/_chunks/chunk-U5FT4VBR.js +1 -0
- package/dist/_chunks/chunk-VOGKKZQH.js +1 -0
- package/dist/_chunks/chunk-YV447AB5.js +1 -0
- package/dist/_chunks/{chunk-W6C63ZN7.js → chunk-ZADAXKKY.js} +1 -1
- package/dist/_chunks/{chunk-S74X4KIC.js → chunk-ZOODOQBH.js} +1 -1
- package/dist/_chunks/{connect-6UH7ZFAC.js → connect-RIODOO3C.js} +1 -1
- package/dist/_chunks/{device-management-H3NIDIPY.js → device-management-VECG3RA4.js} +1 -1
- package/dist/_chunks/{device-preflight-LHFLPVAB.js → device-preflight-73KVSHZG.js} +1 -1
- package/dist/_chunks/{devices-inventory-I2E3Q4DA.js → devices-inventory-E6TE4H7T.js} +1 -1
- package/dist/_chunks/{devices-main-VV2VYU4T.js → devices-main-7JHMJNGV.js} +1 -1
- package/dist/_chunks/{files-TTIQ7LYJ.js → files-72BEXD7E.js} +1 -1
- package/dist/_chunks/{host-main-3JFGVU5P.js → host-main-KDORT44Q.js} +1 -1
- package/dist/_chunks/http-profile-QINBH2FP.js +1 -0
- package/dist/_chunks/{library-main-CTBW7DAI.js → library-main-AWUEMZFQ.js} +1 -1
- package/dist/_chunks/local-main-BNFNAPRG.js +1 -0
- package/dist/_chunks/{local-mcp-XB6E3V2W.js → local-mcp-HU6MII3G.js} +1 -1
- package/dist/_chunks/main-BSMCHALI.js +2 -0
- package/dist/_chunks/mcp-3VZZFXNG.js +1 -0
- package/dist/_chunks/oauth-QBJ62PIA.js +1 -0
- package/dist/_chunks/observe-entry-D7F6OQ7Y.js +1 -0
- package/dist/_chunks/remote-client-XIJ6RQLU.js +1 -0
- package/dist/_chunks/{render-main-VTM6WGFP.js → render-main-O3IN6EFV.js} +1 -1
- package/dist/_chunks/{source-import-KKV2UWJO.js → source-import-Y2Z3BVWY.js} +1 -1
- package/dist/_chunks/src-3S6CAUSJ.js +1 -0
- package/dist/_chunks/{stdio-main-Y7N4NVKU.js → stdio-main-T4WMBNKB.js} +1 -1
- package/dist/_chunks/workspace-main-KWFTVTZG.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +1 -1
- package/dist/_types/cli/local/desktop-device-contract.d.ts +2 -2
- package/dist/_types/cli/local/desktop-device-owner.d.ts +1 -1
- package/dist/_types/cli/local/desktop-owner.d.ts +1 -1
- package/dist/_types/contracts/index.d.ts +2 -0
- package/dist/_types/contracts/lifecycle-event-projections.d.ts +15 -0
- package/dist/_types/contracts/lifecycle-events.d.ts +53 -1
- package/dist/_types/contracts/production-feedback.d.ts +452 -0
- package/dist/_types/contracts/shares.d.ts +135 -0
- package/dist/_types/contracts/workspace.d.ts +21 -0
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/dist/native/helper.exe +0 -0
- package/dist/native/helper.json +1 -0
- package/package.json +1 -1
- package/dist/_chunks/chunk-5DY7LSZZ.js +0 -1
- package/dist/_chunks/chunk-6LU6GJKW.js +0 -1
- package/dist/_chunks/chunk-77IAHNM2.js +0 -1
- package/dist/_chunks/chunk-FU3524Z6.js +0 -1
- package/dist/_chunks/chunk-HY7NXJYX.js +0 -1
- package/dist/_chunks/chunk-KB2GVAN7.js +0 -1
- package/dist/_chunks/chunk-PUNG4ND7.js +0 -1
- package/dist/_chunks/chunk-SV3NF7GO.js +0 -1
- package/dist/_chunks/chunk-TLPI6P7L.js +0 -1
- package/dist/_chunks/chunk-ZRSYOFMX.js +0 -1
- package/dist/_chunks/http-profile-NIQDCFPU.js +0 -1
- package/dist/_chunks/local-main-227MNGEC.js +0 -1
- package/dist/_chunks/main-W6NNZFLK.js +0 -2
- package/dist/_chunks/mcp-EXQ5UAHB.js +0 -1
- package/dist/_chunks/oauth-HC6TI7HB.js +0 -1
- package/dist/_chunks/src-OIY5TBQT.js +0 -1
- package/dist/_chunks/workspace-main-Y7ZVBRJJ.js +0 -1
- package/dist/native/Bootstrap.ps1 +0 -90
- package/dist/native/JobNative.cs +0 -137
- package/dist/native/JobRunner.cs +0 -381
- package/dist/native/NativeMain.cs +0 -161
- package/dist/native/PipeBridge.cs +0 -260
- package/dist/native/PrivateAccess.cs +0 -152
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{privateAccess}from"./chunk-KB2GVAN7.js";import{open,constants}from"node:fs/promises";import{resolve}from"node:path";var limit=18*1024*1024;async function readInput(path,stdin){let bytes;if(path==="-"){const chunks=[];let size=0;for await(const chunk of stdin){size+=chunk.byteLength;if(size>limit)throw Error();chunks.push(Buffer.from(chunk))}bytes=Buffer.concat(chunks)}else{const handle=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>limit)throw Error();bytes=Buffer.alloc(limit+1);let used=0;while(used<bytes.byteLength){const read=await handle.read(bytes,used,bytes.byteLength-used,null);if(!read.bytesRead)break;used+=read.bytesRead}if(used>limit)throw Error();bytes=bytes.subarray(0,used)}finally{await handle.close()}}const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!value||typeof value!=="object"||Array.isArray(value))throw Error();return value}async function readCredential(options,environment){if(options.has("--token-file")===options.has("--token-env"))throw Error();let token;const key=options.get("--token-env");if(key){if(!/^[A-Z][A-Z0-9_]{0,127}$/.test(key))throw Error();token=environment[key]??""}else{if(process.platform==="win32")await privateAccess(resolve(options.get("--token-file")),"file");const handle=await open(options.get("--token-file"),constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await handle.stat();if(!stat.isFile()||process.platform!=="win32"&&(stat.mode&63)!==0||stat.size>8192)throw Error();const bytes=Buffer.alloc(8193);const{bytesRead}=await handle.read(bytes,0,bytes.length,0);if(bytesRead>8192)throw Error();token=bytes.subarray(0,bytesRead).toString("utf8").trim()}finally{await handle.close()}}if(!/^[A-Za-z0-9._~-]{1,8192}$/.test(token))throw Error();return"Bearer "+token}export{readInput,readCredential};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-5DY7LSZZ.js";import{remoteFetch,secureEndpoint}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:remoteFetch});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client}),close:()=>client.close()}}catch{await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{privateAccess,privateDirectory,write}from"./chunk-KB2GVAN7.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{randomBytes}from"node:crypto";import{open,unlink,constants}from"node:fs/promises";import{dirname,resolve}from"node:path";var FileOAuthProvider=class _FileOAuthProvider{constructor(path,data){this.path=path;this.data=data}path;data;static async create(path,resource,redirect,scope){secureEndpoint(resource);secureEndpoint(redirect);if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const data={version:1,resource,redirect,scope,state:randomBytes(24).toString("base64url")};await write(resolve(path),JSON.stringify(data),true);return new _FileOAuthProvider(path,data)}static async load(path){if(process.platform==="win32")await privateAccess(resolve(path),"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);let data;try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&63)!==0)||stat.size>65536)throw Error();const bytes=Buffer.alloc(65537);const{bytesRead}=await file.read(bytes,0,bytes.length,0);if(bytesRead>65536)throw Error();data=JSON.parse(bytes.subarray(0,bytesRead).toString("utf8"))}finally{await file.close()}if(![1,2].includes(data.version)||typeof data.state!=="string"||data.state.length<16)throw Error();if(data.pendingExchange!==void 0&&!["CODE","REFRESH"].includes(data.pendingExchange))throw Error();if(data.version===2!==(data.pendingExchange!==void 0))throw Error();secureEndpoint(data.resource);secureEndpoint(data.redirect);if(!["nvs:read","nvs:read nvs:write"].includes(data.scope))throw Error();return new _FileOAuthProvider(path,data)}async save(){if(process.platform==="win32")await privateDirectory(dirname(resolve(this.path)));await write(resolve(this.path),JSON.stringify(this.data))}get redirectUrl(){return this.data.redirect}get clientMetadata(){return{client_name:"NativeStudio CLI",redirect_uris:[this.data.redirect],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],scope:this.data.scope,application_type:"native"}}state(){return this.data.state}clientInformation(){return this.data.client}async saveClientInformation(value){this.data.client=value;await this.save()}tokens(){return this.data.token}async saveTokens(value){this.data.token=value;this.data.expiresAt=Date.now()+(value.expires_in??600)*1e3;this.data.version=1;delete this.data.pendingExchange;await this.save()}async redirectToAuthorization(url){this.data.authorizationUrl=url.href;await this.save()}async saveCodeVerifier(value){this.data.verifier=value;await this.save()}codeVerifier(){if(!this.data.verifier)throw Error();return this.data.verifier}async saveDiscoveryState(value){this.data.discovery=value;await this.save()}discoveryState(){return this.data.discovery}};async function withProfileLock(path,action){if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const file=await open(path+".lock","wx",384);try{return await action()}finally{await file.close();await unlink(path+".lock")}}export{FileOAuthProvider,withProfileLock};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{tenantConnection}from"./chunk-SV3NF7GO.js";import{FileOAuthProvider,withProfileLock}from"./chunk-FU3524Z6.js";import{remoteResponse,secureEndpoint}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";async function apiMetadata(url){let response;try{response=await remoteResponse(url,{headers:{accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!response.ok)return void 0;const parts=[];let size=0;for await(const part of response.body??[]){size+=part.byteLength;if(size>16384)return void 0;parts.push(part)}const data=JSON.parse(Buffer.concat(parts).toString());return data&&typeof data==="object"&&!Array.isArray(data)?data:void 0}catch{return void 0}finally{await response?.body?.cancel().catch(()=>{})}}async function profileHttpOrigin(path,resource){return withProfileLock(path,async()=>{const provider=await FileOAuthProvider.load(path);const deny=()=>{throw new NativeStudioSdkError("API_ORIGIN_UNTRUSTED","BLOCKED","NO_WRITE")};if(provider.data.resource!==resource)deny();if(provider.data.pendingExchange)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");tenantConnection(resource);const endpoint=secureEndpoint(resource);const metadataUrl=endpoint.origin+"/.well-known/oauth-protected-resource"+endpoint.pathname;const fresh=await apiMetadata(metadataUrl);if(fresh&&fresh.resource!==resource)deny();const metadata=fresh??provider.data.discovery?.resourceMetadata;const configured=metadata?.nativestudio_api_origin;if(configured===void 0){if(fresh&&provider.data.discovery){const saved={...provider.data.discovery.resourceMetadata,resource};Reflect.deleteProperty(saved,"nativestudio_api_origin");provider.data.discovery.resourceMetadata=saved;provider.data.discovery.resourceMetadataUrl=metadataUrl;await provider.save()}return endpoint.origin}try{if(typeof configured!=="string")return deny();const sourceUrl=metadata===fresh?metadataUrl:provider.data.discovery?.resourceMetadataUrl;if(typeof sourceUrl!=="string"||secureEndpoint(sourceUrl).origin!==endpoint.origin||metadata?.resource!==resource||configured.length>2048)deny();const api=secureEndpoint(configured);if(api.pathname!=="/"||endpoint.protocol==="https:"&&api.protocol!=="https:")deny();if(metadata===fresh&&provider.data.discovery){provider.data.discovery.resourceMetadata={...provider.data.discovery.resourceMetadata,resource,nativestudio_api_origin:api.origin};provider.data.discovery.resourceMetadataUrl=metadataUrl;await provider.save()}return api.origin}catch{return deny()}})}export{profileHttpOrigin};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{execFile,spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,win32,isAbsolute}from"node:path";var nativeAssetNames=["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"];var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory2=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/cli/package.json")));const hash=createHash("sha256");for(const name of nativeAssetNames){hash.update(name+"\n");hash.update(await readFile(join(directory2,name)))}const sourceDigest=hash.digest("hex"),system=process.env.SystemRoot??process.env.SYSTEMROOT;if(!system||!win32.isAbsolute(system)||system.startsWith("\\\\"))throw Error("WINDOWS_SYSTEM_UNAVAILABLE");const shell=join(system,"System32/WindowsPowerShell/v1.0/powershell.exe"),script=(await readFile(join(directory2,"Bootstrap.ps1"))).toString("utf8");const result=await new Promise((resolve,reject)=>{const child=execFile(shell,["-NoLogo","-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(script,"utf16le").toString("base64")],{timeout:15e3,maxBuffer:32768,windowsHide:true},(error,stdout)=>error?reject(Error("WINDOWS_HELPER_UNAVAILABLE")):resolve(stdout));child.stdin.on("error",()=>{});child.stdin.end(JSON.stringify({directory:directory2,sourceDigest}))});const value=JSON.parse(result);if(value.sourceDigest!==sourceDigest||!/^[a-f0-9]{64}$/.test(value.sha256)||!win32.isAbsolute(value.path))throw Error("WINDOWS_HELPER_INVALID");const path=await realpath(value.path),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size>2*1024*1024||createHash("sha256").update(await readFile(path)).digest("hex")!==value.sha256)throw Error("WINDOWS_HELPER_INVALID");return path}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(["EXISTS","RESOURCE_BUDGET_EXCEEDED"].includes(value.error??"")?value.error:"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}async function syncDirectory(path){if(process.platform==="win32")return;const d=await open(path,"r");try{await d.sync()}finally{await d.close()}}async function atomicMove(source,target,exclusive=false){if(dirname(source)!==dirname(target))throw Error("LOCAL_ATOMIC_MOVE_INVALID");if(process.platform==="win32"){try{await windowsRequest({operation:"move",source,target,exclusive})}catch(error){if(error.message==="EXISTS")throw Object.assign(Error("EXISTS"),{code:"EEXIST"});throw error}}else{if(exclusive){await link(source,target);await unlink(source)}else await rename(source,target);await syncDirectory(dirname(target))}}async function assertExecutable(path){const s=await lstat2(path);if(!isAbsolute2(path)||!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw Error("LOCAL_EXECUTABLE_INVALID");if(process.platform==="win32"){if(!path.toLowerCase().endsWith(".exe"))throw Error("LOCAL_EXECUTABLE_INVALID");await windowsRequest({operation:"executable",path})}else if(!(s.mode&73)||s.mode&18)throw Error("LOCAL_EXECUTABLE_INVALID")}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{constants}from"node:fs";import{open as open2,realpath as realpath2,rename as rename2,unlink as unlink2,link as link2,readdir}from"node:fs/promises";import{isAbsolute as isAbsolute3,join as join3,dirname as dirname2}from"node:path";import{randomUUID as randomUUID2,createHash as createHash3}from"node:crypto";var sha256=v=>createHash3("sha256").update(v).digest("hex");var sha512=v=>createHash3("sha512").update(v).digest("hex");var LocalClientError=class extends Error{constructor(code){super("NativeStudio local "+code);this.code=code}code};function fail(code){throw new LocalClientError(code)}async function directory(path){if(!isAbsolute3(path))fail("LOCATION_UNSUPPORTED");try{await privateDirectory(path,true)}catch{fail("PRIVATE_LOCATION_REQUIRED")}const root=await realpath2(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))fail("PRIVATE_LOCATION_REQUIRED");return root}async function read(path,maximum=65536,ledger=false){try{await privateAccess(path,"file")}catch(e){if(e.code==="ENOENT")throw e;fail("PRIVATE_FILE_REQUIRED")}const f=await open2(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const s=await f.stat();if(!s.isFile()||process.platform!=="win32"&&(s.uid!==process.getuid?.()||s.mode&63)||s.size>maximum||(ledger?s.nlink>2:s.nlink!==1))fail("PRIVATE_FILE_REQUIRED");const bytes=Buffer.alloc(Math.min(maximum+1,s.size+1));let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>s.size)fail("FILE_CHANGED");if(used>maximum)fail("FILE_LIMIT");return bytes.subarray(0,used)}finally{await f.close()}}async function write(path,value,exclusive=false){const temporary=join3(dirname2(path),".tmp-"+randomUUID2());const f=await open2(temporary,"wx",384);try{await f.writeFile(value);await f.sync()}finally{await f.close()}try{if(process.platform==="win32")await atomicMove(temporary,path,exclusive);else if(exclusive)await link2(temporary,path);else{try{await read(path,64*1024*1024)}catch(e){if(e.code!=="ENOENT")throw e}await rename2(temporary,path)}}finally{await unlink2(temporary).catch(e=>{if(e.code!=="ENOENT")throw e})}await syncDirectory(dirname2(path))}async function entries(path){const values=await readdir(path);if(values.length>1e4)fail("HISTORY_LIMIT");return values}async function optional(path){try{return JSON.parse((await read(path)).toString())}catch(e){if(e.code==="ENOENT")return null;throw e}}async function verifyBackup(path,stateDirectory){const base=await realpath2(join3(stateDirectory,"backups")),actual=await realpath2(path);if(dirname2(actual)!==base||!/[0-9a-f-]{36}\.sqlite$/.test(actual))fail("JOURNAL_BACKUP_REQUIRED");try{await privateAccess(actual,"file")}catch{fail("JOURNAL_BACKUP_REQUIRED")}const f=await open2(actual,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await f.stat(),header=Buffer.alloc(16);if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size<100)fail("JOURNAL_BACKUP_REQUIRED");const n=await f.read(header,0,16,0);if(n.bytesRead!==16||header.toString()!=="SQLite format 3\0")fail("JOURNAL_BACKUP_REQUIRED")}finally{await f.close()}}export{localSocketPath,privateAccess,privateDirectory,atomicMove,assertExecutable,sha256,sha512,LocalClientError,fail,directory,read,write,entries,optional,verifyBackup};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function secureEndpoint(endpoint){const url=new URL(endpoint);if(url.username||url.password||url.search||url.hash||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw Error();return url}var remoteResponse=(input,init)=>fetch(input,{...init,redirect:"error",signal:init?.signal?AbortSignal.any([init.signal,AbortSignal.timeout(3e4)]):AbortSignal.timeout(3e4)});var remoteFetch=async(input,init)=>{const response=await remoteResponse(input,init);if(!response.body)return response;const reader=response.body.getReader(),chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>32*1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}return new Response(Buffer.concat(chunks),{status:response.status,headers:response.headers})};export{secureEndpoint,remoteResponse,remoteFetch};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{FileOAuthProvider,withProfileLock}from"./chunk-FU3524Z6.js";import{directory,optional,privateDirectory,write}from"./chunk-KB2GVAN7.js";import{CliAccountExchangeSchema,CliAccountIdentitySchema,CliAccountSessionSchema,CliAccountStartSchema,CliAccountStartedSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema}from"./chunk-TLPI6P7L.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{join}from"node:path";import{z as z2}from"zod";import{z}from"zod";function accountServerOrigin(value){const url=new URL(value);if(url.pathname!=="/"||url.search||url.hash||url.username||url.password||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw new NativeStudioSdkError("ACCOUNT_SERVER_ORIGIN_REQUIRED","INVALID_INPUT","NO_WRITE");return url.origin}var NativeStudioAccountClient=class{constructor(options){this.options=options;this.serverOrigin=accountServerOrigin(options.serverOrigin);if(options.accessToken&&!/^nvsh_[A-Za-z0-9_-]{43}$/.test(options.accessToken))throw new NativeStudioSdkError("INVALID_ACCOUNT_CREDENTIAL","INVALID_INPUT","NO_WRITE")}options;serverOrigin;async request(action,schema,options={}){if(options.credential&&!this.options.accessToken)throw new NativeStudioSdkError("ACCOUNT_LOGIN_REQUIRED","INVALID_INPUT","NO_WRITE");const write2=options.body!==void 0;let response;try{response=await(this.options.fetch??fetch)(`${this.serverOrigin}/api/cli-account/${action}${options.query?"?"+options.query:""}`,{method:write2?"POST":"GET",cache:"no-store",redirect:"error",credentials:"omit",signal:AbortSignal.any([AbortSignal.timeout(15e3),...options.signal?[options.signal]:[]]),headers:{...write2?{"content-type":"application/json"}:{},...options.credential?{authorization:"Bearer "+this.options.accessToken}:{}},...write2?{body:JSON.stringify(options.body)}:{}})}catch{throw new NativeStudioSdkError("ACCOUNT_TRANSPORT_FAILED","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}if(!response.ok){await response.body?.cancel();throw new NativeStudioSdkError(response.status===401?"ACCOUNT_SESSION_EXPIRED_OR_REVOKED":"ACCOUNT_REQUEST_REJECTED","BLOCKED",write2&&response.status>=500?"UNKNOWN":"REJECTED",response.status)}try{if(!(response.headers.get("content-type")??"").startsWith("application/json"))throw Error();const reader=response.body?.getReader();if(!reader)throw Error();const chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}const bytes=new Uint8Array(size);let offset=0;for(const part of chunks){bytes.set(part,offset);offset+=part.length}return schema.parse(JSON.parse(new TextDecoder().decode(bytes)))}catch{throw new NativeStudioSdkError("ACCOUNT_RESPONSE_INVALID","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}}async metadata(signal){return this.request("metadata",z.strictObject({protocol:z.literal("NVS_CLI_ACCOUNT_V1"),serverOrigin:z.literal(this.serverOrigin)}),{signal})}start(input,signal){return this.request("start",CliAccountStartedSchema,{body:CliAccountStartSchema.parse(input),signal})}exchange(input,signal){return this.request("exchange",CliAccountSessionSchema,{body:CliAccountExchangeSchema.parse(input),signal})}me(signal){return this.request("me",CliAccountIdentitySchema,{credential:true,signal})}logout(signal){return this.request("logout",z.strictObject({changed:z.literal(true)}),{credential:true,body:{},signal})}async projects(input,signal){const value=z.strictObject({tenantId:z.uuid(),limit:z.number().int().min(1).max(100).optional(),next:z.string().min(1).max(8192).optional()}).parse(input);const result=await this.request("projects",ProjectLibraryPageSchema,{credential:true,signal,query:new URLSearchParams({tenantId:value.tenantId,...value.limit?{limit:String(value.limit)}:{},...value.next?{next:value.next}:{}})});if(result.items.some(p=>p.tenantId!==value.tenantId))throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}async project(input,signal){const value=z.strictObject({tenantId:z.uuid(),projectId:z.uuid()}).parse(input);const result=await this.request("project",ProjectWorkspaceSchema,{credential:true,signal,query:new URLSearchParams(value)});if(result.project.id!==value.projectId||result.project.tenantId!==value.tenantId)throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}};var AccountStateSchema=z2.strictObject({version:z2.literal(1),epoch:z2.uuid(),serverOrigin:z2.string().refine(v=>{try{return accountServerOrigin(v)===v}catch{return false}}),principalId:z2.uuid(),expiresAt:z2.iso.datetime(),workspaceId:z2.uuid().nullable(),projectId:z2.uuid().nullable(),state:z2.enum(["ACTIVE","REVOKE_PENDING","SIGNED_OUT"]),accessToken:z2.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/).nullable()}).refine(v=>v.state==="SIGNED_OUT"===(v.accessToken===null)&&(!v.projectId||Boolean(v.workspaceId)));function accountError(code,outcome="NO_WRITE"){throw new NativeStudioSdkError(code,outcome==="UNKNOWN"?"INTERNAL_OPERATIONAL_FAILURE":["ACCOUNT_LOGIN_INPUT_INVALID","ACCOUNT_COMMAND_INPUT_INVALID"].includes(code)?"INVALID_INPUT":"BLOCKED",outcome)}async function readAccount(root){const value=await optional(join(root,"account.json"));if(value===null)return null;const parsed=AccountStateSchema.safeParse(value);if(!parsed.success)accountError("ACCOUNT_STATE_INVALID");return parsed.data}async function saveAccount(root,value){const account=AccountStateSchema.parse(value);await write(join(root,"account.json"),JSON.stringify(account))}async function withAccountLock(root,action){try{return await withProfileLock(join(root,"account.json"),action)}catch(error){if(error.code==="EEXIST")accountError("ACCOUNT_COMMAND_BUSY");throw error}}function requireAccount(value){if(!value)accountError("ACCOUNT_LOGIN_REQUIRED");if(value.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");if(value.state!=="ACTIVE"||Date.parse(value.expiresAt)<=Date.now())accountError("ACCOUNT_LOGIN_REQUIRED");return value}import{homedir}from"node:os";import{isAbsolute,join as join2}from"node:path";import{realpath}from"node:fs/promises";function connectionError(code){throw new NativeStudioSdkError(code,"INVALID_INPUT","NO_WRITE")}async function clientHome(environment,create=false){const path=environment.NATIVESTUDIO_CLIENT_HOME??join2(homedir(),".nativestudio","client");if(!isAbsolute(path))connectionError("CLIENT_HOME_ABSOLUTE_REQUIRED");if(create)return directory(path);await privateDirectory(path);const root=await realpath(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))connectionError("CLIENT_HOME_PRIVATE_REQUIRED");return root}import{join as join3}from"node:path";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var tenantPath=new RegExp(`^/mcp/external/v1/tenants/(${uuid})$`,"i");function tenantConnection(resource){const url=secureEndpoint(resource),match=tenantPath.exec(url.pathname);if(!match)connectionError("TENANT_MCP_URL_REQUIRED");return{resource:url.href,tenantId:match[1].toLowerCase()}}async function saveConnection(root,profile,expectedEpoch){return withAccountLock(root,()=>saveConnectionLocked(root,profile,expectedEpoch))}async function saveConnectionLocked(root,profile,expectedEpoch){if(!/^profile-[0-9a-f-]{36}\.json$/.test(profile))throw Error();const provider=await FileOAuthProvider.load(join3(root,profile));const scope=tenantConnection(provider.data.resource);if(!provider.data.token?.access_token||provider.data.pendingExchange)throw Error();const account=await readAccount(root);if(account?.epoch!==expectedEpoch)connectionError("ACCOUNT_CHANGED_DURING_CONNECTION");if(account&&(account.state!=="ACTIVE"||account.workspaceId!==scope.tenantId))connectionError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");await write(join3(root,"connection.json"),JSON.stringify({version:3,profile,...scope,...account?{accountEpoch:account.epoch}:{}}));return{scope:provider.data.token.scope??provider.data.scope,expiresAt:provider.data.expiresAt}}async function loadConnection(environment){let root;try{root=await clientHome(environment)}catch(e){if(e.code==="ENOENT")return null;throw e}const value=await optional(join3(root,"connection.json"));if(value===null)return null;if(value.version!==3||typeof value.profile!=="string"||!/^profile-[0-9a-f-]{36}\.json$/.test(value.profile)||typeof value.resource!=="string")connectionError("CONNECTION_INVALID");const scope=tenantConnection(value.resource);if(scope.tenantId!==value.tenantId||value.projectId!==void 0)connectionError("CONNECTION_SCOPE_MISMATCH");const account=await readAccount(root);if(value.accountEpoch!==void 0&&(!account||typeof value.accountEpoch!=="string"))connectionError("CONNECTION_ACCOUNT_MISMATCH");if(account&&(account.state!=="ACTIVE"||value.accountEpoch!==account.epoch||scope.tenantId!==account.workspaceId))connectionError("CONNECTION_ACCOUNT_MISMATCH");const profile=join3(root,value.profile),provider=await FileOAuthProvider.load(profile);if(provider.data.resource!==scope.resource||!provider.data.token?.access_token)connectionError("CONNECTION_PROFILE_MISMATCH");return{...scope,profile,scope:provider.data.token.scope??provider.data.scope,requestedScope:provider.data.scope,expiresAt:provider.data.expiresAt,exchangeUnresolved:Boolean(provider.data.pendingExchange)}}var authentication=["--profile","--origin","--mcp-url","--token-env","--token-file"];async function defaultConnection(options,environment,tenant){if(authentication.some(key=>options.has(key)))return;const connection=await loadConnection(environment);if(!connection)connectionError("TENANT_CONNECTION_REQUIRED");if(options.has("--tenant")&&options.get("--tenant")!==connection.tenantId)connectionError("CONNECTION_SCOPE_MISMATCH");options.set("--profile",connection.profile);if(tenant)options.set("--tenant",connection.tenantId)}async function connectionStatus(environment){const value=await loadConnection(environment);return{exitCode:0,output:value?{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"TENANT_MCP",accountSessionVerified:false,verification:"LOCAL_METADATA_ONLY",resource:value.resource,tenantId:value.tenantId,scope:value.scope,requestedScope:value.requestedScope,expiresAt:value.expiresAt,credentialState:value.exchangeUnresolved?"EXCHANGE_UNRESOLVED":typeof value.expiresAt==="number"&&value.expiresAt>Date.now()+3e4?"CACHED":"REFRESH_REQUIRED",nextSteps:value.exchangeUnresolved?["Wait for the active authorization command. If it returned OAUTH_OUTCOME_UNKNOWN, run nvs connect --mcp-url <workspace-connection-url>."]:["nvs find --query <intent>","nvs capabilities","nvs mcp"]}:{semanticStatus:"NEEDS_INPUT",connected:false,credentialPurpose:"TENANT_MCP",accountSessionVerified:false,nextSteps:["Open Agent access in the workspace settings, then authorize the workspace once.","nvs connect --mcp-url <workspace-connection-url>"]}}}export{accountServerOrigin,NativeStudioAccountClient,accountError,readAccount,saveAccount,withAccountLock,requireAccount,connectionError,clientHome,tenantConnection,saveConnection,loadConnection,defaultConnection,connectionStatus};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ContinuationSchema,DeliveryOutputProfileSchema,HumanLinksSchema,PrincipalIdSchema,ProductionIdSchema,ProjectIdSchema,QueryLimitSchema,QueryPageInfoSchema,TenantIdSchema}from"./chunk-6UYY5KHI.js";import{z}from"zod";var HumanEmailSchema=z.string().trim().max(254).toLowerCase().pipe(z.email()).refine(v=>/^[\x21-\x7e]+$/.test(v),"Use an ASCII email address");var HumanPasswordSchema=z.string().max(512).superRefine((v,c)=>{const points=[...v];const control=points.some(c2=>c2.codePointAt(0)<32||c2.codePointAt(0)===127);if(points.length<15||points.length>128||control)c.addIssue({code:"custom",message:"Password must contain 15\u2013128 characters"})});var HumanCodePurposeSchema=z.enum(["REGISTER","RESET_PASSWORD","LINK_EMAIL"]);var HumanCodeRequestSchema=z.strictObject({email:HumanEmailSchema,purpose:HumanCodePurposeSchema});var HumanCodeRequestedSchema=z.strictObject({accepted:z.literal(true),challengeId:z.uuid(),retryAfterSeconds:z.literal(60),expiresInSeconds:z.literal(600)});var proof={challengeId:z.uuid(),email:HumanEmailSchema,code:z.string().regex(/^\d{6}$/),password:HumanPasswordSchema};var HumanRegisterSchema=z.strictObject({...proof,displayName:z.string().trim().min(1).max(80)});var HumanResetSchema=z.strictObject(proof);var HumanLoginSchema=z.strictObject({email:HumanEmailSchema,password:z.string().max(512),rememberMe:z.boolean().optional()});var HumanTenantSchema=z.strictObject({id:z.uuid(),displayName:z.string().max(200)});var HumanAccountSchema=z.strictObject({principalId:z.uuid(),displayName:z.string().max(200),email:HumanEmailSchema.nullable(),tenants:z.array(HumanTenantSchema).max(100)});var HumanDesktopSessionSchema=z.strictObject({tenantId:z.uuid(),scopeKey:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.int().positive(),sessionExpiresAt:z.int().positive().optional(),rememberMe:z.boolean(),account:HumanAccountSchema.omit({tenants:true})}).refine(({rememberMe,expiresAt,sessionExpiresAt})=>sessionExpiresAt===void 0||rememberMe&&sessionExpiresAt>=expiresAt,"Desktop persistence requires consent and the session deadline");var ShortHumanSessionSchema=z.strictObject({accessToken:z.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/),expiresAt:z.iso.datetime(),account:HumanAccountSchema});var HumanRefreshTokenSchema=z.string().regex(/^nvshr_[A-Za-z0-9_-]{43}$/);var HumanRefreshSchema=z.strictObject({refreshToken:HumanRefreshTokenSchema});var HumanSessionSchema=ShortHumanSessionSchema.extend({refreshToken:HumanRefreshTokenSchema.optional(),sessionId:z.uuid().optional(),sessionExpiresAt:z.iso.datetime().optional()}).refine(session=>{const{refreshToken,sessionId,sessionExpiresAt,expiresAt}=session;if(!refreshToken)return sessionId===void 0&&sessionExpiresAt===void 0;return!!sessionId&&!!sessionExpiresAt&&Date.parse(expiresAt)<=Date.parse(sessionExpiresAt)},"Persistent session requires its exact identity and absolute expiry");var HumanIdentityAvailabilitySchema=z.strictObject({passwordLogin:z.boolean(),emailVerification:z.boolean()});var HumanIdentityFailureSchema=z.strictObject({code:z.enum(["INVALID_INPUT","INVALID_CREDENTIALS","INVALID_CODE","RATE_LIMITED","MAIL_UNAVAILABLE","UNAVAILABLE","UNAUTHENTICATED","CONFLICT"])});var CliAccountRedirectSchema=z.string().max(256).refine(value=>{try{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&Number(url.port)>0&&!url.username&&!url.password&&!url.search&&!url.hash&&/^\/account-callback\/[a-f0-9-]{36}$/.test(url.pathname)&&url.href===value}catch{return false}},"Owned loopback account callback required");var proofKey=z.string().regex(/^[A-Za-z0-9_-]{43}$/);var CliAccountRequestIdSchema=z.uuid();var CliAccountStartSchema=z.strictObject({redirectUri:CliAccountRedirectSchema,state:proofKey,codeChallenge:proofKey});var CliAccountStartedSchema=z.strictObject({requestId:z.uuid(),expiresAt:z.iso.datetime()});var CliAccountPreviewSchema=CliAccountStartedSchema.extend({redirectUri:CliAccountRedirectSchema});var CliAccountDecisionSchema=z.strictObject({requestId:z.uuid(),approved:z.boolean(),expectedPrincipalId:z.uuid()});var CliAccountExchangeSchema=z.strictObject({requestId:z.uuid(),code:proofKey,codeVerifier:proofKey,redirectUri:CliAccountRedirectSchema});var CliAccountSessionSchema=ShortHumanSessionSchema.extend({credentialPurpose:z.literal("CLI_ACCOUNT")});var CliAccountIdentitySchema=z.strictObject({credentialPurpose:z.literal("CLI_ACCOUNT"),account:HumanAccountSchema});import{z as z2}from"zod";var ProductionLifecycleSchema=z2.enum(["ACTIVE","COMPLETED","FAILED","CANCELLED"]);var ProductionPhaseSchema=z2.enum(["INTAKE","PLANNING","PREPARING_GENERATION","GENERATING","SHOT_REVIEW","ASSEMBLING","ROUGH_CUT_REVIEW","FINAL_READY","FINAL_RENDERING","DELIVERY_VALIDATION"]);var ProductionConditionSchema=z2.enum(["RUNNABLE","RUNNING","WAITING_PROVIDER","WAITING_HUMAN","BLOCKED","RETRYING"]);var CreateProductionInputSchema=z2.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,principalId:PrincipalIdSchema});var ProductionStateSchema=z2.object({lifecycle:ProductionLifecycleSchema,phase:ProductionPhaseSchema,condition:ProductionConditionSchema,revision:z2.int().positive(),blockingReason:z2.string().min(1).nullable(),waitingReason:z2.string().min(1).nullable()});var ProductionSchema=z2.object({humanLinks:HumanLinksSchema.optional(),id:ProductionIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema,activeBriefVersion:z2.int().positive().nullable().default(null),activeStoryVersion:z2.int().positive().nullable().default(null),activeSceneShotPlanVersion:z2.int().positive().nullable().default(null),createdByPrincipalId:PrincipalIdSchema,createdAt:z2.iso.datetime({offset:true}),updatedAt:z2.iso.datetime({offset:true})});import{z as z3}from"zod";var ProjectLifecycleSchema=z3.enum(["ACTIVE","ARCHIVED"]);var CreateProjectInputSchema=z3.object({tenantId:TenantIdSchema,principalId:PrincipalIdSchema,idempotencyKey:z3.string().trim().min(1).max(200),name:z3.string().trim().min(1).max(200)});var CreateProjectRequestSchema=CreateProjectInputSchema.omit({principalId:true}).strict();var ProjectSchema=z3.object({id:ProjectIdSchema,tenantId:TenantIdSchema,name:z3.string().min(1),lifecycle:ProjectLifecycleSchema,defaultActiveProductionId:ProductionIdSchema.nullable(),revision:z3.int().positive(),createdByPrincipalId:PrincipalIdSchema,createdAt:z3.iso.datetime({offset:true}),updatedAt:z3.iso.datetime({offset:true})});var CreatedProjectResultSchema=z3.object({project:ProjectSchema,production:ProductionSchema});import{z as z4}from"zod";var ProjectLibraryQuerySchema=z4.strictObject({tenantId:TenantIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProjectLibraryScopeSchema=z4.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var ProjectLibraryPageSchema=z4.strictObject({items:z4.array(ProjectSchema).max(100),page:QueryPageInfoSchema});var ProjectWorkspaceSchema=z4.strictObject({project:ProjectSchema,productions:z4.array(ProductionSchema).max(100),possiblyTruncated:z4.boolean()});var SourceLibraryQuerySchema=ProjectLibraryQuerySchema.extend({projectId:ProjectIdSchema.optional()});var SourceLibraryItemSchema=z4.strictObject({artifactId:z4.uuid(),representationId:z4.uuid(),projectId:ProjectIdSchema,kind:z4.enum(["REFERENCE_IMAGE","REFERENCE_VIDEO","PRODUCT_INFORMATION"]),originalName:z4.string().max(255),checksumSha256:z4.string().regex(/^[0-9a-f]{64}$/),contentType:z4.enum(["image/png","image/jpeg","image/webp","text/plain","application/json","video/mp4"]),byteSize:z4.int().positive().max(8388608),width:z4.int().positive().nullable(),height:z4.int().positive().nullable(),createdAt:z4.iso.datetime({offset:true})});var SourceLibraryPageSchema=z4.strictObject({items:z4.array(SourceLibraryItemSchema).max(100),page:QueryPageInfoSchema});var SourceLibraryMediaSchema=ProjectLibraryScopeSchema.extend({artifactId:z4.uuid()});var StudioInputContentSchema=z4.strictObject({schemaVersion:z4.literal(1),productionId:z4.uuid(),projectTitle:z4.string().trim().min(1).max(200),name:z4.string().trim().max(300),intent:z4.string().trim().min(1).max(2e3),aspectRatio:z4.enum(["16:9","9:16"]),targetDurationSeconds:z4.int().min(30).max(60),outputProfile:DeliveryOutputProfileSchema,sourceArtifactIds:z4.array(z4.uuid()).max(12)});export{HumanTenantSchema,CliAccountStartSchema,CliAccountStartedSchema,CliAccountExchangeSchema,CliAccountSessionSchema,CliAccountIdentitySchema,ProductionStateSchema,ProductionSchema,CreateProjectRequestSchema,ProjectSchema,CreatedProjectResultSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema,SourceLibraryQuerySchema,SourceLibraryItemSchema,SourceLibraryPageSchema,SourceLibraryMediaSchema,StudioInputContentSchema};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{NativeStudioLocalRuntimeClient,asset,catalogue,newerVersion,select}from"./chunk-U7ECMITP.js";import{assertExecutable,directory,entries,fail,localSocketPath,optional,privateAccess,read,sha256,sha512,verifyBackup,write}from"./chunk-KB2GVAN7.js";import{LocalCompositionBrowserSelectionSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeComponentSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,RuntimeCaptionAssets,canonicalLocalJson,importedNormalizationValidationProfile,localLibraryProfile,tenantRenderValidationProfile,whisperCppRecognitionProfile}from"./chunk-PDQYFIQQ.js";import{z}from"zod";import{constants,createReadStream}from"node:fs";import{open,realpath}from"node:fs/promises";import{isAbsolute}from"node:path";import{createHash}from"node:crypto";async function toolPreference(previous,cloud,explicit){if(explicit)return LocalToolChoiceSchema.parse(explicit);const raw=previous?JSON.parse((await read(previous,32768)).toString()):cloud?JSON.parse((await read(cloud,32768)).toString()).tools:null;const selected=raw?LocalToolSelectionSchema.parse(raw):null;return selected?.mode==="INSTALLED"?{...selected,mode:"INSTALLED"}:{mode:"MANAGED",...selected?.cpuSpeech?{cpuSpeech:selected.cpuSpeech}:{}}}async function captureInstalledTools(input,host=process){const paths=z.strictObject({mode:z.literal("INSTALLED").optional(),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096),compositionBrowser:z.string().min(1).max(4096).optional(),captionAssetsDirectory:z.string().min(1).max(4096).optional(),whisper:z.strictObject({binary:z.string().min(1).max(4096),model:z.string().min(1).max(4096)}).optional()}).parse(input);if(paths.compositionBrowser&&(host.platform!=="linux"||host.arch!=="x64"))fail("COMPOSITION_BROWSER_PLATFORM_UNAVAILABLE");if(paths.whisper&&(host.platform!=="darwin"||host.arch!=="arm64"))fail("LOCAL_PROFILE_UNAVAILABLE");async function capture(candidate,executable=true){if(!isAbsolute(candidate))fail("TOOL_PATH_INVALID");const path=await realpath(candidate);if(executable)await assertExecutable(path);const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await file.stat();if(!before.isFile()||before.size<1||before.size>256*1024*1024)fail("TOOL_PATH_INVALID");const h=createHash("sha256");let count=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){count+=chunk.length;if(count>before.size)fail("TOOL_CHANGED");h.update(chunk)}const after=await file.stat();if(count!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs)fail("TOOL_CHANGED");return{path,digest:h.digest("hex")}}finally{await file.close()}}const compositionBrowser=paths.compositionBrowser?await capture(paths.compositionBrowser):void 0;if(compositionBrowser&&!LocalCompositionBrowserSelectionSchema.safeParse(compositionBrowser).success)fail("COMPOSITION_BROWSER_INTEGRITY_INVALID");const model=paths.whisper?await capture(paths.whisper.model,false):void 0;if(model&&model.digest!==whisperCppRecognitionProfile.modelSha256)fail("LOCAL_ASR_IDENTITY_MISMATCH");const binary=paths.whisper?await capture(paths.whisper.binary):void 0;if(paths.captionAssetsDirectory&&!isAbsolute(paths.captionAssetsDirectory))fail("CAPTION_ASSET_LOCATION_INVALID");return LocalToolChoiceSchema.parse({mode:"INSTALLED",ffmpeg:await capture(paths.ffmpeg),ffprobe:await capture(paths.ffprobe),...compositionBrowser?{compositionBrowser}:{},...paths.captionAssetsDirectory?{captionAssetsDirectory:await realpath(paths.captionAssetsDirectory)}:{},...binary&&model?{whisper:{binaryPath:binary.path,binarySha256:binary.digest,modelPath:model.path}}:{}})}var requiredRuntimeFiles=["package.json","dist/entry.js","dist/supervisor.mjs","dist/parent-lifetime.mjs","dist/execution-identity.json"];var allowedRuntimeFiles=new Set([...requiredRuntimeFiles,"README.md","LICENSE","dist/THIRD_PARTY_NOTICES.md","dist/BUNDLED_DEPENDENCIES.json","dist/agent-supervisor.mjs","dist/kokoro-worker.mjs","dist/capture.mjs","dist/hyperframe.manifest.json","dist/hyperframe.runtime.iife.js","dist/hyperframe-gsap.js","dist/hyperframe-dependencies.json","dist/hyperframe-notices.txt","dist/captions/NotoSansSC.ttf","dist/captions/NativeStudioSC-Regular.ttf","dist/captions/OFL.txt",...["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open as open2}from"node:fs/promises";import{dirname,join,delimiter}from"node:path";import{z as z2}from"zod";var runtimeEnvironment=()=>({...Object.fromEntries(["HOME","USER","LOGNAME","TMPDIR","CODEX_HOME","SystemRoot","SYSTEMROOT","USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP"].flatMap(k=>process.env[k]?[[k,process.env[k]]]:[])),PATH:dirname(process.execPath)+(process.platform==="win32"?"":delimiter+["/usr/bin","/bin"].join(delimiter)),LANG:"C",LC_ALL:"C",UV_THREADPOOL_SIZE:"2",NVS_INSTALL_OWNER:"MANAGED"});async function verifySlot(root,slot){if(requiredRuntimeFiles.some(name=>!Object.hasOwn(slot.files,name)))fail("SLOT_FILES_MISSING");for(const[name,hash]of Object.entries(slot.files)){if(!allowedRuntimeFiles.has(name))fail("SLOT_PATH_INVALID");if(sha256(await read(join(root,name),64*1024*1024))!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probeEntry(root,option,args=[]){return new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),option,...args],{env:runtimeEnvironment(),stdio:["ignore","pipe","ignore"],shell:false});const parts=[];let size=0;const timer=setTimeout(()=>child.kill("SIGKILL"),1e4);child.stdout.on("data",b=>{size+=b.length;if(size>65536)child.kill("SIGKILL");else parts.push(b)});child.on("error",reject);child.on("close",code=>{clearTimeout(timer);if(code!==0||size>65536)reject(Error("Runtime descriptor unavailable"));else resolve(Buffer.concat(parts))})})}async function probeProfile(root,slot,option,profile){await verifySlot(root,slot);try{const digest=(await probeEntry(root,option)).toString().trim();return digest===sha256(canonicalLocalJson(profile))}catch{return false}}function probeTenantMediaValidation(root,slot){return probeProfile(root,slot,"--tenant-media-validation-profile",tenantRenderValidationProfile)}function probeTenantMediaProcessing(root,slot){return probeProfile(root,slot,"--tenant-media-processing-profile",importedNormalizationValidationProfile)}async function probeLocalLibrary(root,slot){await verifySlot(root,slot);try{return(await probeEntry(root,"--local-library-profile")).toString().trim()===sha256(canonicalLocalJson(localLibraryProfile))}catch{return false}}async function probeTenantComposition(root,slot){if(process.platform!=="linux"||process.arch!=="x64"||!slot.toolsConfigPath)return false;const selected=LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString()));if(selected.mode!=="INSTALLED"||!selected.compositionBrowser)return false;await verifySlot(root,slot);try{const result=await probeEntry(root,"--tenant-composition-capability",["--tools-config",slot.toolsConfigPath]);return result.toString().trim()===selected.compositionBrowser.digest}catch{return false}}async function probeTenantSpeech(root,slot){if(process.platform!=="darwin")return false;await verifySlot(root,slot);try{return/^[a-f0-9]{64}$/.test((await probeEntry(root,"--tenant-speech-capability")).toString().trim())}catch{return false}}async function probeTenantTranscription(root,slot){if(process.platform!=="darwin"||process.arch!=="arm64"||!slot.toolsConfigPath)return false;await verifySlot(root,slot);try{return/^[a-f0-9]{64}$/.test((await probeEntry(root,"--tenant-transcription-capability",["--tools-config",slot.toolsConfigPath])).toString().trim())}catch{return false}}async function probeTenantQwenGeneration(root,slot,kind){await verifySlot(root,slot);return probeEntry(root,`--tenant-qwen-${kind}-capability`).then(value=>value.toString().trim()==="QWEN_"+kind.toUpperCase()+"_V1",()=>false)}async function probe(root,expected){const bytes=await probeEntry(root,"--describe");const descriptor=LocalRuntimeDescriptorSchema.parse(JSON.parse(bytes.toString()));if(canonicalLocalJson(descriptor)!==canonicalLocalJson(expected))fail("RUNTIME_DESCRIPTOR_MISMATCH");return descriptor}async function ownerClient(stateDirectory){await directory(stateDirectory);return new NativeStudioLocalRuntimeClient({stateDirectory,authorization:async()=>"Bearer "+(await read(join(stateDirectory,"control-token"),128)).toString()})}async function runningInventory(client,root,slot){const inventory=await client.inventory(),status=await client.status();if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(slot.descriptor)||status.versions.find(v=>v.component==="RUNTIME")?.executablePath!==join(root,"dist/entry.js"))fail("RUNTIME_ALREADY_RUNNING");return inventory}async function launch(root,slot,stateDirectory,cloudConfig,toolsConfig){await verifySlot(root,slot);await probe(root,slot.descriptor);await directory(stateDirectory);const existing=await ownerClient(stateDirectory);try{return await runningInventory(existing,root,slot)}catch(e){if(e instanceof Error&&e.message.includes("RUNTIME_ALREADY_RUNNING"))throw e}const log=await open2(join(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:runtimeEnvironment(),detached:true,windowsHide:true,stdio:["ignore",log.fd,log.fd],shell:false});let spawnError=false;child.once("error",()=>{spawnError=true});child.unref();await log.close();const deadline=Date.now()+15e3;while(Date.now()<deadline){if(spawnError||child.exitCode!==null)fail("RUNTIME_START_FAILED");try{return await runningInventory(existing,root,slot)}catch{}await new Promise(r=>setTimeout(r,100))}child.kill("SIGTERM");fail("RUNTIME_START_UNCONFIRMED")}async function waitStopped(stateDirectory){const client=await ownerClient(stateDirectory),deadline=Date.now()+1e4;while(Date.now()<deadline){try{await client.inventory()}catch{const{lstat:lstat3}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat3(localSocketPath(stateDirectory))}catch(e){if(e.code==="ENOENT")return}const{createConnection}=await import("node:net");const closed=await new Promise(resolve=>{const s=createConnection(localSocketPath(stateDirectory));s.once("connect",()=>{s.destroy();resolve(false)});s.once("error",e=>resolve(["ECONNREFUSED","ENOENT"].includes(e.code??"")));s.setTimeout(300,()=>{s.destroy();resolve(false)})});if(closed)return}await new Promise(r=>setTimeout(r,100))}fail("RUNTIME_STOP_UNCONFIRMED")}async function socketAbsent(stateDirectory){const{createConnection}=await import("node:net");return new Promise(resolve=>{const socket=createConnection(localSocketPath(stateDirectory));socket.once("connect",()=>{socket.destroy();resolve(false)});socket.once("error",error=>resolve(["ECONNREFUSED","ENOENT"].includes(error.code??"")));socket.setTimeout(500,()=>{socket.destroy();resolve(false)})})}async function probeTools(root,stateDirectory,selection){const{execFile}=await import("node:child_process");const diagnostic=z2.strictObject({tool:z2.enum(["FFMPEG","FFPROBE"]),stage:z2.enum(["IDENTITY","VERSION","ENCODERS","DECODERS","FILTERS","DEMUXERS","MUXERS","FINAL_IDENTITY"]),cause:z2.enum(["IDENTITY_INVALID","VERSION_INVALID","CAPABILITY_MISSING","PROCESS_FAILED","TIMEOUT","CANCELLED"])});const failures=[];for(let attempt=0;attempt<2;attempt++){const result=await new Promise((resolve,reject)=>execFile(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:runtimeEnvironment(),timeout:5e4,maxBuffer:65536},(error,stdout,stderr)=>error?reject(Error("Tool probe failed")):resolve({stdout,stderr})));const report=LocalDoctorReportSchema.parse(JSON.parse(result.stdout));let failure;for(const line of result.stderr.split("\n")){try{const parsed=diagnostic.safeParse(JSON.parse(line).toolProbe);if(parsed.success)failure=parsed.data}catch{}}if(failure)failures.push(failure);if(failures.length)await write(join(stateDirectory,"tool-qualification.json"),JSON.stringify({checkedAt:new Date().toISOString(),availability:report.availability,failures}));if(report.availability==="AVAILABLE")return report;if(!failure||!["TIMEOUT","PROCESS_FAILED"].includes(failure.cause))break}fail("TOOL_QUALIFICATION_FAILED")}async function verifyManagedMedia(previous,reuse){if(!previous)fail("MANAGED_TOOLS_UNAVAILABLE");const current=LocalToolSelectionSchema.parse(JSON.parse((await read(previous,32768)).toString()));if(current.mode!=="MANAGED"||canonicalLocalJson({schemaVersion:1,ffmpeg:current.ffmpeg,ffprobe:current.ffprobe})!==canonicalLocalJson(reuse))fail("MANAGED_TOOLS_CHANGED");const files=await captureInstalledTools({ffmpeg:reuse.ffmpeg.path,ffprobe:reuse.ffprobe.path});if(files.mode!=="INSTALLED"||canonicalLocalJson(files.ffmpeg)!==canonicalLocalJson(reuse.ffmpeg)||canonicalLocalJson(files.ffprobe)!==canonicalLocalJson(reuse.ffprobe))fail("MANAGED_TOOLS_CHANGED");return{mode:"MANAGED",ffmpeg:current.ffmpeg,ffprobe:current.ffprobe}}import{randomUUID}from"node:crypto";import{lstat}from"node:fs/promises";import{join as join2}from"node:path";import{constants as constants2}from"node:fs";import{open as open3}from"node:fs/promises";import{createHash as createHash2}from"node:crypto";async function bytesAt(base,name,maximum){const f=await open3(new URL(name,base),constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const stat=await f.stat();if(!stat.isFile()||stat.size<1||stat.size>maximum)fail("BUNDLED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let used=0;while(used<bytes.length){const{bytesRead}=await f.read(bytes,used,bytes.length-used,null);if(!bytesRead)break;used+=bytesRead}if(used!==stat.size)fail("BUNDLED_COMPONENT_CHANGED");return bytes.subarray(0,used)}finally{await f.close()}}async function readEmbeddedRuntime(base,manifestDigest){const raw=await bytesAt(base,"components/runtime.json",32768);if(sha256(raw)!==manifestDigest)fail("BUNDLED_COMPONENT_CHANGED");const component=LocalRuntimeComponentSchema.parse(JSON.parse(raw.toString()));const product=JSON.parse((await bytesAt(base,"package.json",32768)).toString());if(product.name!=="@nativestudio/cli"||product.version!==component.version)fail("BUNDLED_COMPONENT_IDENTITY_INVALID");const bytes=await bytesAt(base,"components/runtime.tgz",64*1024*1024);if(bytes.length!==component.byteSize||createHash2("sha512").update(bytes).digest("hex")!==component.sha512)fail("BUNDLED_COMPONENT_INTEGRITY_INVALID");const descriptor=LocalRuntimeDescriptorSchema.parse({...component.descriptor,platform:{os:process.platform,architecture:process.arch}});return{component,bytes,descriptor,trustFingerprint:manifestDigest}}async function embeddedRuntime(version){if(false)return null;const base=new URL(".",import.meta.resolve("@nativestudio/cli/package.json"));const value=await readEmbeddedRuntime(base,"3d1ab069c88c9fc8c9c353cc6e5e46010eadc82708550e4d5041cde545ad5a00");return version&&version!=="latest"&&version!==value.component.version?null:value}async function installationSource(c,version,bundled,dependencies){if(!bundled){const trusted2=await catalogue(c);return{release:select(trusted2.signed,version,c.rejectedVersions),origin:trusted2.origin,catalogueFingerprint:trusted2.fingerprint,trustFingerprint:trusted2.trustFingerprint,expiresAt:trusted2.signed.catalogue.expiresAt}}const core=await embeddedRuntime(version);if(!core||c.rejectedVersions.includes(core.descriptor.version))fail("BUNDLED_VERSION_UNAVAILABLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==core.descriptor.node.major||minor<core.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");const trusted=dependencies?await catalogue(c):null;const remote=trusted?select(trusted.signed,core.descriptor.version):null;if(remote&&(remote.package.sha512!==core.component.sha512||remote.package.byteSize!==core.component.byteSize||canonicalLocalJson(remote.descriptor)!==canonicalLocalJson(core.descriptor)||remote.resources&&(remote.resources.captions.sha512!==core.component.resources.captions.sha512||remote.resources.captions.byteSize!==core.component.resources.captions.byteSize)))fail("BUNDLED_COMPONENT_RELEASE_MISMATCH");return{release:{descriptor:core.descriptor,package:{source:"CLI",byteSize:core.component.byteSize,sha512:core.component.sha512},tools:remote?.tools??null,...remote?.resources?{resources:remote.resources}:{}},origin:trusted?.origin??"",catalogueFingerprint:trusted?.fingerprint??null,trustFingerprint:trusted?sha256(canonicalLocalJson([core.trustFingerprint,trusted.trustFingerprint])):core.trustFingerprint,expiresAt:trusted?.signed.catalogue.expiresAt??new Date(Date.now()+18e5).toISOString()}}async function approvedSource(c,plan){const source=await installationSource(c,plan.release.descriptor.version,"source"in plan.release.package,plan.catalogueFingerprint!==null);if(Date.parse(plan.expiresAt)<=Date.now()||source.trustFingerprint!==plan.trustFingerprint||canonicalLocalJson(source.release)!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");return source}function needsDependencyChannel(c,choice,haveCaptions=false){return!!choice&&(choice.mode==="MANAGED"&&!choice.reuseMedia||choice.mode==="INSTALLED"&&!choice.captionAssetsDirectory&&!haveCaptions&&!!c.catalogueUrl&&!!c.publicKeyFile)}function toolIdentity(tools){return[tools.ffmpeg.digest,tools.ffprobe.digest,...tools.cpuSpeech?[canonicalLocalJson({...tools.cpuSpeech,voiceIds:[...tools.cpuSpeech.voiceIds].sort((a,b)=>a-b)})]:[],...tools.mode==="INSTALLED"&&tools.compositionBrowser?[tools.compositionBrowser.digest]:[],...tools.mode==="INSTALLED"&&tools.whisper?[tools.whisper.binarySha256,whisperCppRecognitionProfile.modelSha256]:[]].join(":")}async function identity(path,cloud){if(!path)return null;const raw=JSON.parse((await read(path,32768)).toString());const tools=LocalToolSelectionSchema.parse(cloud?raw.tools:raw);return toolIdentity(tools)}async function effective(path,cloud){return path?identity(path,false):identity(cloud,true)}function supportedRenderer(expected,digest){return expected.rendererDigest===digest||!!expected.compatibleRenderers?.some(r=>r.rendererDigest===digest)}async function assertPendingCompatible(raw,expected,previous,next,cloud){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingRenderers.some(d=>!supportedRenderer(expected,d)))fail("NATIVE_RECOVERY_REQUIRED");if(i.pendingExecutions+i.pendingRequests===0)return;if(i.descriptor.profileDigest!==expected.profileDigest&&!expected.compatibleRenderers?.some(r=>r.profileDigest===i.descriptor.profileDigest))fail("NATIVE_RECOVERY_REQUIRED");const before=await effective(previous,cloud);const after=await effective(next,cloud);if(!before||before!==after)fail("NATIVE_RECOVERY_REQUIRED")}async function assertPendingToolIdentity(raw,previous,cloud,next){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingExecutions+i.pendingRequests>0&&await effective(previous,cloud)!==next)fail("NATIVE_RECOVERY_REQUIRED")}async function assertNoStoppedJournal(state){for(const suffix of["","-wal","-shm","-journal"]){try{await lstat(join2(state,"journal.sqlite"+suffix))}catch(e){if(e.code==="ENOENT")continue;throw e}fail("RUNTIME_STATUS_REQUIRED")}}async function prepareInstallation(manager,version,raw,bundled=false){const c=await manager.configuration(),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const explicit=raw===void 0?void 0:LocalToolChoiceSchema.parse(raw),source=await installationSource(c,version,bundled,needsDependencyChannel(c,explicit,Object.entries(RuntimeCaptionAssets).every(([name,hash])=>current.active?.files["dist/captions/"+name]===hash))),release=source.release,preference=await toolPreference(current.active?.toolsConfigPath??null,c.cloudConfigFile,explicit),toolSelection=explicit||preference.mode==="INSTALLED"||release.tools?preference:void 0;if(toolSelection?.mode==="MANAGED"){if(toolSelection.reuseMedia)await verifyManagedMedia(current.active?.toolsConfigPath??null,toolSelection.reuseMedia);else if(!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE")}let runtimeRevision=null;try{const inventory=await(await ownerClient(c.stateDirectory)).inventory();runtimeRevision=inventory.runtimeRevision;const previous=current.active?.toolsConfigPath??null;await assertPendingCompatible(inventory,release.descriptor,previous,previous,c.cloudConfigFile);const desired=preference.mode==="INSTALLED"?preference:preference.reuseMedia??release.tools;if(desired)await assertPendingToolIdentity(inventory,previous,c.cloudConfigFile,preference.mode==="INSTALLED"?toolIdentity(preference):preference.reuseMedia?toolIdentity({mode:"MANAGED",ffmpeg:preference.reuseMedia.ffmpeg,ffprobe:preference.reuseMedia.ffprobe,...preference.cpuSpeech?{cpuSpeech:preference.cpuSpeech}:{}}):release.tools.ffmpeg.sha256+":"+release.tools.ffprobe.sha256+(preference.cpuSpeech?":"+canonicalLocalJson({...preference.cpuSpeech,voiceIds:[...preference.cpuSpeech.voiceIds].sort((a,b)=>a-b)}):""))}catch(e){if(e instanceof Error&&e.message.includes("NATIVE_RECOVERY_REQUIRED"))throw e;if(!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await assertNoStoppedJournal(c.stateDirectory)}const body={protocol:"NVS_LOCAL_UPDATE_PLAN_V1",planId:randomUUID(),installationRevision:current.revision,runtimeRevision,catalogueFingerprint:source.catalogueFingerprint,trustFingerprint:source.trustFingerprint,release,...toolSelection?{toolSelection}:{},createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(source.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join2(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}import{randomUUID as randomUUID2}from"node:crypto";import{join as join3,dirname as dirname2}from"node:path";import{z as z3}from"zod";async function grant(manager,raw,output){const i=z3.strictObject({tenantId:z3.uuid(),deviceId:z3.uuid(),expiresAt:z3.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname2(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join3(manager.ledger.root,"grants",randomUUID2()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,tenantId:i.tenantId,deviceId:i.deviceId,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-TTIQ7LYJ.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join3(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z3.strictObject({tenantId:z3.uuid(),deviceId:z3.uuid(),expiresAt:z3.iso.datetime({offset:true}),output:z3.string().min(1)}).parse(await optional(join3(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",tenantId:g.tenantId,deviceId:g.deviceId,expiresAt:g.expiresAt});await write(g.output,canonicalLocalJson(connector));renewed++}catch{blocked++}}return{renewed,blocked}}import{randomUUID as randomUUID4}from"node:crypto";import{join as join9}from"node:path";import{z as z5}from"zod";import{z as z4}from"zod";import{join as join4}from"node:path";var slotSchema=z4.strictObject({id:z4.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z4.string().nullable().default(null),files:z4.record(z4.string().min(1).max(100),z4.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z4.strictObject({id:z4.uuid(),planId:z4.uuid(),fingerprint:z4.string().regex(/^[0-9a-f]{64}$/),phase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z4.string().nullable(),failedPhase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z4.strictObject({revision:z4.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z4.strictObject({previous:z4.string().nullable(),value:installationSchema,digest:z4.string().regex(/^[0-9a-f]{64}$/)});var InstallationLedger=class _InstallationLedger{constructor(root){this.root=root}root;static async open(path){const root=await directory(path);for(const name of["revisions","plans","slots","grants"])await directory(join4(root,name));return new _InstallationLedger(root)}static async openExisting(root){try{await privateAccess(root,"directory");await privateAccess(join4(root,"revisions"),"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _InstallationLedger(root)}async current(){const names2=(await entries(join4(this.root,"revisions"))).filter(n=>/^\d{12}\.json$/.test(n)).sort();let previous=null,value={revision:0,active:null,transition:null};for(const[i,name]of names2.entries()){const raw=JSON.parse((await read(join4(this.root,"revisions",name),262144,true)).toString());const r=recordSchema.parse(raw);const expected=sha256(canonicalLocalJson({previous:raw.previous,value:raw.value}));if(r.value.revision!==i+1||r.previous!==previous||r.digest!==expected)fail("INSTALLATION_HISTORY_INVALID");previous=r.digest;value=r.value}return{value,digest:previous}}async commit(expected,next){const current=await this.current();if(current.value.revision!==expected.revision)fail("REVISION_CONFLICT");const value=installationSchema.parse({...next,revision:expected.revision+1});const record={previous:current.digest,value,digest:sha256(canonicalLocalJson({previous:current.digest,value}))};try{await write(join4(this.root,"revisions",String(value.revision).padStart(12,"0")+".json"),canonicalLocalJson(record),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return value}slotPath(slot){return join4(this.root,"slots",slot.id)}};import{constants as constants3}from"node:fs";import{open as open4,chmod}from"node:fs/promises";import{join as join5,isAbsolute as isAbsolute2}from"node:path";import{gunzipSync}from"node:zlib";function packageFiles(bytes,allowed2,directories){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024});const files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0)){if(!data.subarray(offset).every(b=>b===0))fail("PACKAGE_FORMAT_INVALID");break}const text=(a,b)=>header.subarray(a,b).toString().replace(/\0.*$/s,"");const number=(a,b)=>{const v=text(a,b).trim();if(!/^[0-7]+$/.test(v))fail("PACKAGE_FORMAT_INVALID");return parseInt(v,8)};const sum=number(148,156);let actual=0;for(let i=0;i<512;i++)actual+=i>=148&&i<156?32:header[i];if(actual!==sum||!text(257,263).startsWith("ustar"))fail("PACKAGE_FORMAT_INVALID");const prefix=text(345,500),path=(prefix?prefix+"/":"")+text(0,100),size=number(124,136),kind=text(156,157);if(!Number.isSafeInteger(size)||size<0||offset+512+size>data.length)fail("PACKAGE_FORMAT_INVALID");if(kind==="5"){if(!directories.test(path)||size!==0)fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowed2.has(path.slice(8))||files.has(path.slice(8)))fail("PACKAGE_PATH_INVALID");files.set(path.slice(8),data.subarray(offset+512,offset+512+size))}offset+=512+Math.ceil(size/512)*512}return files}var names=Object.keys(RuntimeCaptionAssets);var allowed=new Set(names.map(n=>"dist/captions/"+n));async function captionDirectory(path){if(!isAbsolute2(path))fail("CAPTION_ASSET_LOCATION_INVALID");const files=new Map;for(const name of names){const f=await open4(join5(path,name),constants3.O_RDONLY|constants3.O_NOFOLLOW|constants3.O_NONBLOCK);try{const s=await f.stat();if(!s.isFile()||s.size<1||s.size>20*1024*1024)fail("CAPTION_ASSET_INVALID");const bytes=Buffer.alloc(s.size+1);let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used!==s.size||sha256(bytes.subarray(0,used))!==RuntimeCaptionAssets[name])fail("CAPTION_ASSET_INVALID");files.set("dist/captions/"+name,bytes.subarray(0,used))}finally{await f.close()}}return files}async function managedCaptions(ledger,resource,origin){const path=join5(await directory(join5(ledger.root,"resources")),resource.sha512+".tgz");let bytes;let downloaded=false;try{bytes=await read(path,resource.byteSize)}catch(e){if(e.code!=="ENOENT")throw e;bytes=await asset(resource,origin);downloaded=true}if(bytes.length!==resource.byteSize||sha512(bytes)!==resource.sha512)fail("CAPTION_RESOURCE_INTEGRITY_INVALID");const files=packageFiles(bytes,allowed,/^package(?:\/dist(?:\/captions)?)?\/?$/);if(files.size!==names.length)fail("CAPTION_ASSET_INVALID");for(const name of names)if(sha256(files.get("dist/captions/"+name))!==RuntimeCaptionAssets[name])fail("CAPTION_ASSET_INVALID");if(downloaded){try{await write(path,bytes,true)}catch(e){if(e.code!=="EEXIST")throw e;const existing=await read(path,resource.byteSize);if(existing.length!==resource.byteSize||sha512(existing)!==resource.sha512)fail("CAPTION_RESOURCE_INTEGRITY_INVALID")}}return files}async function stageResources(ledger,candidate,previous,plan,origin){const root=ledger.slotPath(candidate);const present=[...allowed].filter(p=>candidate.files[p]);if(present.length){await captionDirectory(join5(root,"dist/captions"));return candidate}const choice=plan.toolSelection;let files;if(choice?.mode==="INSTALLED"&&choice.captionAssetsDirectory)files=await captionDirectory(choice.captionAssetsDirectory);else if(previous&&[...allowed].some(p=>previous.files[p]))files=await captionDirectory(join5(ledger.slotPath(previous),"dist/captions"));else if(plan.release.resources)files=await managedCaptions(ledger,plan.release.resources.captions,origin);if(!files)return candidate;await directory(join5(root,"dist/captions"));const hashes={...candidate.files};for(const[path,bytes]of files){await write(join5(root,path),bytes,true);await chmod(join5(root,path),256);hashes[path]=sha256(bytes)}return{...candidate,files:hashes}}import{randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod3}from"node:fs/promises";import{join as join7}from"node:path";import{chmod as chmod2}from"node:fs/promises";import{join as join6}from"node:path";async function unpack(bytes,root,expectedVersion){const files=packageFiles(bytes,allowedRuntimeFiles,/^package(?:\/dist(?:\/(?:native|captions))?)?\/?$/);if(!requiredRuntimeFiles.every(p=>files.has(p)))fail("PACKAGE_FILES_MISSING");const manifest=JSON.parse(files.get("package.json").toString());const deps=manifest.dependencies;if(manifest.name!=="@nativestudio/local-runtime"||manifest.version!==expectedVersion||manifest.type!=="module"||Object.keys(deps??{}).length||Object.keys(manifest.optionalDependencies??{}).length||["preinstall","install","postinstall","prepare"].some(name=>Object.hasOwn(manifest.scripts??{},name))||!["dist/entry.js","./dist/entry.js"].includes(manifest.bin?.["nvs-runtime"]??"")||Object.keys(manifest.bin??{}).length!==1)fail("PACKAGE_IDENTITY_INVALID");const hashes={};await directory(join6(root,"dist"));if([...files.keys()].some(p=>p.startsWith("dist/native/")))await directory(join6(root,"dist/native"));if([...files.keys()].some(p=>p.startsWith("dist/captions/")))await directory(join6(root,"dist/captions"));for(const[path,contents]of files){await write(join6(root,path),contents,true);await chmod2(join6(root,path),path.endsWith("entry.js")?320:256);hashes[path]=sha256(contents)}return hashes}async function stage(ledger,release,origin){const id=randomUUID3(),root=await directory(join7(ledger.root,"slots",id));const bundled=await embeddedRuntime(release.descriptor.version);if(bundled&&(bundled.component.byteSize!==release.package.byteSize||bundled.component.sha512!==release.package.sha512))fail("BUNDLED_COMPONENT_RELEASE_MISMATCH");if("source"in release.package&&!bundled)fail("BUNDLED_VERSION_UNAVAILABLE");const bytes=bundled?.bytes??("url"in release.package?await asset(release.package,origin):fail("BUNDLED_VERSION_UNAVAILABLE")),files=await unpack(bytes,root,release.descriptor.version);const slot={id,files,descriptor:release.descriptor,toolsConfigPath:null};await probe(root,slot.descriptor);return slot}async function managedTools(release,origin,stateDirectory,selectionId,cpuSpeech){if(!release.tools)return null;const result={};for(const name of["ffmpeg","ffprobe"]){const a=release.tools[name],dir=await directory(join7(stateDirectory,"tools",a.sha256)),path2=join7(dir,name+(process.platform==="win32"?".exe":""));try{if(sha256(await read(path2,256*1024*1024))!==a.sha256)fail("TOOL_INTEGRITY_INVALID")}catch(e){if(e.code!=="ENOENT")throw e;const bytes=await asset(a,origin);if(sha256(bytes)!==a.sha256)fail("TOOL_INTEGRITY_INVALID");await write(path2,bytes,true);await chmod3(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe,...cpuSpeech?{cpuSpeech}:{}};const path=join7(await directory(join7(stateDirectory,"tool-selections")),selectionId+".json");await write(path,JSON.stringify(selection));return path}async function selectedTools(release,origin,state,slotId,cloudConfig,previousSelection,explicit){const preference=await toolPreference(previousSelection,cloudConfig,explicit);if(preference.mode==="INSTALLED"){const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");const selection={...preference};delete selection.captionAssetsDirectory;await write(path,JSON.stringify(selection),true);return path}if(preference.mode==="MANAGED"&&preference.reuseMedia){const media=await verifyManagedMedia(previousSelection,preference.reuseMedia);const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");await write(path,JSON.stringify({...media,...preference.cpuSpeech?{cpuSpeech:preference.cpuSpeech}:{}}),true);return path}if(explicit?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");return await managedTools(release,origin,state,slotId,preference.cpuSpeech)??previousSelection}import{lstat as lstat2,opendir}from"node:fs/promises";import{join as join8}from"node:path";async function containsLibraryFiles(root){let visited=0;async function walk(path,depth){if(depth>8||++visited>1e4)fail("NATIVE_RECOVERY_REQUIRED");const info=await lstat2(path);if(info.isFile()){await privateAccess(path,"file");return true}if(!info.isDirectory()||info.isSymbolicLink())fail("NATIVE_RECOVERY_REQUIRED");await privateAccess(path,"directory");const directory2=await opendir(path,{bufferSize:16});for await(const entry of directory2)if(await walk(join8(path,entry.name),depth+1))return true;return false}const library=join8(root,"library");try{await lstat2(library)}catch(error){if(error.code==="ENOENT")return false;throw error}try{return await walk(library,0)}catch(error){if(error.code==="ENOENT")fail("NATIVE_RECOVERY_REQUIRED");throw error}}async function assertLibraryCompatible(configuration,root,slot){let configured=false;if(configuration.cloudConfigFile){try{const value=JSON.parse((await read(configuration.cloudConfigFile,32768)).toString());if(!value||typeof value!=="object"||Array.isArray(value))fail("NATIVE_RECOVERY_REQUIRED");const capabilities=value.processorCapabilities;if(capabilities!==void 0&&!Array.isArray(capabilities))fail("NATIVE_RECOVERY_REQUIRED");configured=Array.isArray(capabilities)&&capabilities.some(kind=>kind==="LOCAL_MEDIA_INSPECT"||kind==="LOCAL_MEDIA_PUBLISH")}catch(error){if(error instanceof SyntaxError)fail("NATIVE_RECOVERY_REQUIRED");throw error}}if(!configured&&!await containsLibraryFiles(configuration.stateDirectory))return;if(!await probeLocalLibrary(root,slot))fail("NATIVE_RECOVERY_REQUIRED")}var configurationSchema=z5.strictObject({stateDirectory:z5.string().min(1).max(4096),catalogueUrl:z5.string().url().nullable().default(null),publicKeyFile:z5.string().min(1).max(4096).nullable().default(null),cloudConfigFile:z5.string().nullable().default(null),notifications:z5.boolean().default(true),rejectedVersions:z5.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])}).refine(c=>!!c.catalogueUrl===!!c.publicKeyFile,"Release channel requires URL and key together");var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}static async openExisting(root){const ledger=await InstallationLedger.openExisting(root);return ledger?new _LocalInstallationManager(ledger):null}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join9(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join9(this.ledger.root,"configuration.json"));if(!value)fail("CONFIGURATION_REQUIRED");return configurationSchema.parse(value)}async status(){const s=(await this.ledger.current()).value;let c;try{c=await this.configuration()}catch(error){if(error instanceof Error&&error.message.includes("CONFIGURATION_REQUIRED"))return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,running:null,phase:s.transition?.phase??"IDLE",nextActions:[{surface:"CLI",operation:"local.configure",availability:"AVAILABLE",reason:"INSTALL_REQUIRED"}]};throw error}let running=null;try{running=await(await ownerClient(c.stateDirectory)).status()}catch{}return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,entryPath:s.active?join9(this.ledger.slotPath(s.active),"dist/entry.js"):null,installOwner:"MANAGED",phase:s.transition?.phase??"IDLE",running,nextActions:[{surface:"CLI",operation:s.transition?"local.update.reconcile":s.active?"local.start":"local.install",availability:"AVAILABLE",reason:s.transition?"RECOVERY_REQUIRED":s.active?"READY":"INSTALL_REQUIRED"}]}}async reject(version){LocalRuntimeDescriptorSchema.shape.version.parse(version);const c=await this.configuration();await this.configure({...c,rejectedVersions:[...new Set([...c.rejectedVersions,version])]});return{rejected:true,version,selectedVersion:(await this.ledger.current()).value.active?.descriptor.version??null}}async check(){const c=await this.configuration();if(!c.catalogueUrl)return{installation:await this.status(),channel:"UNCONFIGURED",available:[],notifications:c.notifications,rejectedVersions:c.rejectedVersions};const v=await catalogue(c);return{installation:await this.status(),catalogueFingerprint:v.fingerprint,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),notifications:c.notifications,rejectedVersions:c.rejectedVersions}}prepare(version,choice){return prepareInstallation(this,version,choice)}prepareBundled(version,choice){return prepareInstallation(this,version,choice,true)}async plan(id){if(!z5.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join9(this.ledger.root,"plans",id+".json"))).toString()));const{fingerprint,...body}=p;if(sha256(canonicalLocalJson(body))!==fingerprint)fail("PLAN_CHANGED");return p}async transition(s,phase,patch={}){if(!s.transition)fail("TRANSITION_REQUIRED");return this.ledger.commit(s,{active:s.active,transition:{...s.transition,...patch,phase}})}async apply(id,approval){const plan=await this.plan(id),c=await this.configuration();if(approval!==plan.fingerprint)fail("USER_APPROVAL_REQUIRED");const source=await approvedSource(c,plan);let s=(await this.ledger.current()).value;if(s.revision!==plan.installationRevision||s.transition)fail("REVISION_CONFLICT");if(plan.runtimeRevision!==null){const i=await(await ownerClient(c.stateDirectory)).inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(plan.release.descriptor,d)))fail("REVISION_CONFLICT")}if(plan.runtimeRevision===null){if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory)}s=await this.ledger.commit(s,{active:s.active,transition:{id:randomUUID4(),planId:id,fingerprint:approval,phase:"STAGING",previous:s.active,candidate:null,backupPath:null,failedPhase:null}});try{let candidate=await stage(this.ledger,plan.release,source.origin);candidate=await stageResources(this.ledger,candidate,s.active,plan,source.origin);await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);const tools=await selectedTools(plan.release,source.origin,c.stateDirectory,candidate.id,c.cloudConfigFile,s.active?.toolsConfigPath??null,plan.toolSelection);candidate={...candidate,toolsConfigPath:tools};if(tools)await probeTools(this.ledger.slotPath(candidate),c.stateDirectory,tools);s=await this.transition(s,"STAGED",{candidate});if(plan.runtimeRevision!==null){const client=await ownerClient(c.stateDirectory),i=await client.inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(candidate.descriptor,d)))fail("REVISION_CONFLICT");await assertPendingCompatible(i,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile);await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);s=await this.transition(s,"DRAINING");const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:plan.runtimeRevision});if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,c.stateDirectory);s=await this.transition(s,"ACTIVATING",{backupPath:result.backupPath});await waitStopped(c.stateDirectory);await assertPendingCompatible("inventory"in result?result.inventory:null,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile)}else{if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory);s=await this.transition(s,"ACTIVATING")}await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);s=await this.ledger.commit(s,{active:candidate,transition:{...s.transition,phase:"VERIFYING"}});await this.startSlot(candidate,c);s=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{activated:true,revision:s.revision,version:candidate.descriptor.version}}catch(error){const actual=(await this.ledger.current()).value;if(actual.transition?.planId===id)await this.transition(actual,"ROLLBACK_REQUIRED",{failedPhase:actual.transition.phase});throw error}}async startSlot(slot,c){await assertLibraryCompatible(c,this.ledger.slotPath(slot),slot);return launch(this.ledger.slotPath(slot),slot,c.stateDirectory,c.cloudConfigFile??void 0,slot.toolsConfigPath??void 0)}async start(){const s=(await this.ledger.current()).value;if(s.transition)fail("ACTIVATION_IN_PROGRESS");if(!s.active)fail("INSTALL_REQUIRED");const c=await this.configuration(),inventory=await this.startSlot(s.active,c);const clients=await this.reconnect();let updateNotice={status:"DISABLED"};if(c.notifications&&c.catalogueUrl){try{const v=await catalogue(c,AbortSignal.timeout(1500));updateNotice={status:"CHECKED",versions:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&newerVersion(r.descriptor.version,s.active.descriptor.version)&&!c.rejectedVersions.includes(r.descriptor.version)).map(r=>r.descriptor.version)}}catch{updateNotice={status:"UNAVAILABLE"}}}return{...inventory,clients,updateNotice}}async stop(){const c=await this.configuration(),client=await ownerClient(c.stateDirectory),i=await client.inventory();const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:i.runtimeRevision});await waitStopped(c.stateDirectory);return result}async reconcile(id,approval){const s=(await this.ledger.current()).value,c=await this.configuration();if(!s.transition||s.transition.planId!==id||s.transition.fingerprint!==approval)fail("USER_APPROVAL_REQUIRED");if(s.active?.id===s.transition.previous?.id&&["STAGING","STAGED"].includes(s.transition.failedPhase??s.transition.phase)){const next2=await this.ledger.commit(s,{active:s.transition.previous,transition:null});return{rolledBack:true,revision:next2.revision,version:next2.active?.descriptor.version??null}}const candidate=s.transition.candidate;if(candidate){await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);try{const i=await runningInventory(await ownerClient(c.stateDirectory),this.ledger.slotPath(candidate),candidate);if(canonicalLocalJson(i.descriptor)===canonicalLocalJson(candidate.descriptor)){await verifySlot(this.ledger.slotPath(candidate),candidate);const next2=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{recovered:true,revision:next2.revision,version:candidate.descriptor.version}}}catch{}}const previous=s.transition.previous;if(previous)await assertLibraryCompatible(c,this.ledger.slotPath(previous),previous);await waitStopped(c.stateDirectory);const next=await this.ledger.commit(s,{active:previous,transition:null});if(previous)await this.startSlot(previous,c);await this.reconnect();return{rolledBack:true,revision:next.revision,version:previous?.descriptor.version??null}}grant(raw,output){return grant(this,raw,output)}reconnect(){return reconnect(this)}};export{toolPreference,captureInstalledTools,embeddedRuntime,runtimeEnvironment,verifySlot,probeTenantMediaValidation,probeTenantMediaProcessing,probeLocalLibrary,probeTenantComposition,probeTenantSpeech,probeTenantTranscription,probeTenantQwenGeneration,ownerClient,waitStopped,socketAbsent,LocalInstallationManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{profileHttpOrigin}from"./chunk-HY7NXJYX.js";import"./chunk-SV3NF7GO.js";import"./chunk-FU3524Z6.js";import"./chunk-KB2GVAN7.js";import"./chunk-TLPI6P7L.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import"./chunk-HTUTYIRU.js";export{profileHttpOrigin};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{prepareInstalledCpuSpeech}from"./chunk-2AI3WF2O.js";import{connectDevice,generateDeviceKey}from"./chunk-RK2P3UVF.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-ZRSYOFMX.js";import{NativeStudioLocalDeviceClient}from"./chunk-U7ECMITP.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import{LocalClientError}from"./chunk-KB2GVAN7.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioAgentClient}from"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import{EnrollLocalDeviceSchema,LocalAgentGrantSchema,LocalManagementCommandSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";import{homedir}from"node:os";import{join,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));const disclosures=["review metadata",...grant.imageDisclosureApproved?["original image pixels"]:[],...grant.mediaDisclosureApproved?["normalized image pixels or sampled video frames and technical audio statistics"]:[]];return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:`Approving this fingerprint permits remote OpenAI inference for these Projects until expiry and allows disclosure of ${disclosures.join(", ")}. Preview does not invoke a model.`}}}const evidence=flags.get("--evidence");if(evidence&&!["IMAGE_PIXELS","METADATA_ONLY","MEDIA"].includes(evidence))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);const studioFor=tenantId=>new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId,authorization:()=>readCredential(flags,process.env)});let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":{const context=await readInput(need("--input"),stdin);output=await client.prepareAgentReview(evidence==="MEDIA"?localAgentMediaSnapshot(context):localAgentSnapshotFromContext(context,evidence==="IMAGE_PIXELS"));break}case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=studioFor(snapshot.basis.scope.tenantId);const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-media-fetch":{const view=await client.inspectAgentReview(need("--id"));const{basis,evidence:expected,media}=view.plan.snapshot;if(!expected)throw Error();if(view.evidenceReceipt){output=view;break}if(view.phase!=="PREPARED")throw Error();const source=await studioFor(basis.scope.tenantId).immutableMedia({projectId:basis.scope.projectId,representationId:media.representationId,checksumSha256:media.checksumSha256,byteSize:expected.byteSize});output=await client.stageAgentImage(view.plan.id,source.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentMediaProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command==="library"){mutation=["import","access","resume-access"].includes(rest[0]??"");return await(await import("./library-main-CTBW7DAI.js")).runLocalLibrary(rest,stdin)}if(command==="device-preflight"){for(let i=0;i<rest.length;i+=2){const name=rest[i],value=rest[i+1];if(!name||!["--kind","--home","--project"].includes(name)||!value||value.startsWith("--")||options.has(name))throw Error();options.set(name,value)}return(await import("./device-preflight-LHFLPVAB.js")).devicePreflight(options.get("--kind"),{...process.env,...options.has("--home")&&{NATIVESTUDIO_CLIENT_HOME:resolve2(options.get("--home"))}},options.get("--project"))}if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|revoke-device|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact|latest> \u2014 uses this CLI's bundled code; update CLI first for newer code; latest resolves once into an exact saved plan","speech-prepare --input <json with optional voiceIds> \u2014 prepare pinned CPU speech resources and return the original tools update plan","tools-prepare --version <exact|latest> --input <private-json with mode MANAGED or INSTALLED, exact ffmpeg/ffprobe paths, optional compositionBrowser and captionAssetsDirectory>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","device-preflight --kind preview|final|<processor-kind> [--project <uuid>] [--home <private-client-home>] \u2014 read current setup and action qualification","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-library]","library import|list|get|read|access|sync|resume-access|import-receipt|usage --input <json|-> [--file <exact-media>] [--home <client-home>] \u2014 private Owner library; import never uploads","agent-grant-plan|agent-probe|agent-grant|agent-revoke \u2014 installed Codex CLI with explicitly authorized remote OpenAI inference","review-prepare --input <private-context> [--evidence METADATA_ONLY|IMAGE_PIXELS|MEDIA]","review-media-fetch --id <draft> --origin <cloud-origin> --token-file <member-token> \u2014 read exact stored bytes for a MEDIA draft","review-image-fetch|review-inspect|review-proposal \u2014 use --id <draft>","review-start --id <draft> --revision <current> --approve <plan-fingerprint>"],note:"Release check and update planning only inspect metadata. speech-prepare explicitly fetches optional CPU resources. Apply uses the exact saved fingerprint. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const manager=await LocalInstallationManager.open(resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client")));let output;mutation=["configure","speech-prepare","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepareBundled(required("--version"));break;case"speech-prepare":output=await prepareInstalledCpuSpeech(manager,await readInput(required("--input"),stdin));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepareBundled(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-SV3NF7GO.js";import"./chunk-FU3524Z6.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import{write}from"./chunk-KB2GVAN7.js";import"./chunk-TLPI6P7L.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get",skill:"workspace.caller"};var auth=new Set(["--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"]);var fields={find:{"--query":"search","--project":"projectId","--limit":"limit","--next":"next","--attention":"attention"},overview:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},next:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},resume:{"--production":"productionId","--operation":"operationId"},search:{"--query":"query","--project":"projectId","--group":"group","--family":"family","--limit":"limit","--next":"next"},describe:{"--tool":"tool","--project":"projectId","--reference":"schemaCursor"},groups:{"--project":"projectId"},skill:{}};var NavigationCliCommands=new Set([...Object.keys(aliases),"capabilities"]);async function runNavigationCli(argv,stdin,call){const kind=argv[0]==="capabilities"?argv[1]?.startsWith("--")||!argv[1]?"groups":argv[1]:argv[0];const operation=argv[0]==="capabilities"?{groups:"studio.capability.groups",search:"studio.capability.search",describe:"studio.capability.describe"}[kind]:aliases[kind];const offset=argv[0]==="capabilities"&&argv[1]===kind?2:1;if(!operation||!fields[kind])throw Error("INVALID_INPUT");const forwarded=["call",operation],body={},seen=new Set;let input;for(let i=offset;i<argv.length;i+=2){const flag=argv[i],value=argv[i+1];if(!value||value.startsWith("--")||seen.has(flag))throw Error("INVALID_INPUT");seen.add(flag);if(auth.has(flag))forwarded.push(flag,value);else if(flag==="--input"&&kind!=="skill")input=value;else{const key=fields[kind][flag];if(!key)throw Error("INVALID_INPUT");body[key]=flag==="--limit"?Number(value):value}}if(input&&Object.keys(body).length)throw Error("INVALID_INPUT");forwarded.push("--input",input??"-");const generated=async function*(){yield Buffer.from(JSON.stringify(body))};const result=await call(forwarded,input?stdin:generated());return kind==="skill"&&result.exitCode===0?{...result,output:result.output.skill}:result}import{randomBytes,randomUUID,createHash,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function accountSignals(timeout,run){const cancelled=new AbortController,signal=AbortSignal.any([AbortSignal.timeout(timeout),cancelled.signal]);const stop=()=>cancelled.abort();process.once("SIGINT",stop);process.once("SIGTERM",stop);try{return await run(signal)}finally{process.off("SIGINT",stop);process.off("SIGTERM",stop)}}async function runAccountLogin(argv,environment,hooks={}){const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--server","--browser","--timeout-ms"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_LOGIN_INPUT_INVALID");options.set(key,value)}const configured=options.get("--server")??environment.NATIVESTUDIO_STUDIO_ORIGIN;if(!configured)return{exitCode:2,output:{semanticStatus:"NEEDS_INPUT",error:{code:"ACCOUNT_SERVER_REQUIRED",outcome:"NO_WRITE"},nextSteps:["nvs login --server <Studio-origin> (no Project required)"]}};const origin=accountServerOrigin(configured),browser=options.get("--browser")??"auto",timeout=options.get("--timeout-ms")??"180000";if(!["auto","manual"].includes(browser)||!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)accountError("ACCOUNT_LOGIN_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(Number(timeout),async signal=>{if((await readAccount(root))?.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");const client=new NativeStudioAccountClient({serverOrigin:origin});await client.metadata(signal);const verifier=randomBytes(32).toString("base64url"),state=randomBytes(32).toString("base64url"),path="/account-callback/"+randomUUID();let finish,receiving=false,sent=false;const callback=new Promise(done=>{finish=done});const server=createServer({maxHeaderSize:8192,headersTimeout:5e3,requestTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address(),host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(receiving||req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||!req.url.startsWith(path+"?")||req.url.length>2048){res.writeHead(400).end("Invalid account callback.");return}const url=new URL(req.url,`http://${host}`),received=url.searchParams.get("state");const keys=[...url.searchParams.keys()];if(url.pathname!==path||new Set(keys).size!==keys.length||keys.some(k=>!["state","iss","code","error"].includes(k))||!received||Buffer.byteLength(received)!==Buffer.byteLength(state)||!timingSafeEqual(Buffer.from(received),Buffer.from(state))||url.searchParams.get("iss")!==origin||(url.searchParams.has("error")?url.searchParams.get("error")!=="access_denied"||url.searchParams.has("code"):!/^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("code")??""))){res.writeHead(400).end("Invalid account callback.");return}receiving=true;res.end("Account confirmation received. Return to NativeStudio CLI.");finish(url.searchParams.get("code"))});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});const attempt=join(root,"account-login-attempt.json");let attemptFile;try{await new Promise((done,fail)=>{server.once("error",fail);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirectUri=`http://127.0.0.1:${address.port}${path}`;const started=await client.start({redirectUri,state,codeChallenge:createHash("sha256").update(verifier).digest("base64url")},signal);const url=`${origin}/cli-authorize?requestId=${started.requestId}`;signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(url,signal);else{process.stderr.write(`CLI account login request: ${started.requestId}
|
|
2
|
-
`);if(browser==="manual")loginLink(url);else await openLoginBrowser(url,signal)}const code=await callback;if(!code)accountError(signal.aborted?signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED":"ACCOUNT_LOGIN_DENIED");const marker={version:1,serverOrigin:origin,requestId:started.requestId,state:"EXCHANGE_UNRESOLVED"};attemptFile=join(root,`account-login-attempt-${started.requestId}.json`);await write(attemptFile,JSON.stringify(marker),true);await write(attempt,JSON.stringify(marker));signal.throwIfAborted();sent=true;const session=await client.exchange({requestId:started.requestId,redirectUri,code,codeVerifier:verifier},signal);if(Date.parse(session.expiresAt)<=Date.now()||Date.parse(session.expiresAt)>Date.now()+36e5+3e4)accountError("ACCOUNT_SESSION_INVALID","UNKNOWN");await saveAccount(root,{version:1,epoch:randomUUID(),state:"ACTIVE",serverOrigin:origin,accessToken:session.accessToken,expiresAt:session.expiresAt,principalId:session.account.principalId,workspaceId:null,projectId:null});await write(attempt,JSON.stringify({...marker,state:"COMPLETED"}));await write(attemptFile,JSON.stringify({...marker,state:"COMPLETED"}));return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",serverOrigin:origin,expiresAt:session.expiresAt,account:session.account,nextSteps:["nvs workspaces","nvs workspace --id <workspace-id>","nvs projects"]}}}catch(error){if(sent){if(error instanceof NativeStudioSdkError&&error.outcome!=="UNKNOWN"){await write(attempt,JSON.stringify({version:1,state:"REJECTED"}));if(attemptFile)await write(attemptFile,JSON.stringify({version:1,state:"REJECTED"}));throw error}accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN")}if(error instanceof NativeStudioSdkError&&error.outcome==="UNKNOWN")accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN");if(signal.aborted)accountError(signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(done=>server.close(()=>done()))}}))}import{randomUUID as randomUUID2}from"node:crypto";import{z}from"zod";var AccountCommands=new Set(["whoami","workspaces","workspace","projects","project","logout"]);async function runAccountCommand(argv,environment){const command=argv[0],options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--id","--limit","--next"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_COMMAND_INPUT_INVALID");options.set(key,value)}if(["workspace","project"].includes(command??"")?options.size!==1||!options.has("--id"):command==="projects"?options.has("--id"):options.size!==0)accountError("ACCOUNT_COMMAND_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(15e3,async signal=>{const stored=await readAccount(root);if(command==="logout"){if(!stored||stored.state==="SIGNED_OUT")return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:false}};const client2=new NativeStudioAccountClient({serverOrigin:stored.serverOrigin,accessToken:stored.accessToken});const pending={...stored,state:"REVOKE_PENDING",workspaceId:null,projectId:null};await saveAccount(root,pending);try{await client2.logout(signal);await saveAccount(root,{...pending,state:"SIGNED_OUT",accessToken:null})}catch{accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN")}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:true,nextSteps:["nvs login --server <Studio-origin>"]}}}const account=requireAccount(stored),client=new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken});if(command==="whoami"||command==="workspaces"||command==="workspace"){const value2=await client.me(signal);if(value2.account.principalId!==account.principalId)accountError("ACCOUNT_IDENTITY_MISMATCH");if(command==="workspace"){const id=z.uuid().parse(options.get("--id"));if(!value2.account.tenants.some(t=>t.id===id))accountError("WORKSPACE_NOT_AUTHORIZED");await saveAccount(root,{...account,workspaceId:id,projectId:account.workspaceId===id?account.projectId:null,epoch:account.workspaceId===id?account.epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:id,nextSteps:["nvs projects"]}}}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",verification:"LIVE_NATIVE_ACCOUNT",...command==="workspaces"?{workspaces:value2.account.tenants}:{account:value2.account,workspaceId:account.workspaceId,projectId:account.projectId,expiresAt:account.expiresAt},nextSteps:["nvs workspace --id <workspace-id>"]}}}if(!account.workspaceId)accountError("WORKSPACE_SELECTION_REQUIRED");if(command==="projects"){const limit=options.has("--limit")?z.coerce.number().int().min(1).max(100).parse(options.get("--limit")):void 0;const value2=await client.projects({tenantId:account.workspaceId,limit,next:options.get("--next")},signal);if(value2.items.some(p=>p.tenantId!==account.workspaceId))accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");return{exitCode:0,output:{semanticStatus:"SUCCESS",...value2,nextSteps:["nvs project --id <project-id>"]}}}if(command!=="project")accountError("ACCOUNT_COMMAND_INPUT_INVALID");const projectId=z.uuid().parse(options.get("--id")),value=await client.project({tenantId:account.workspaceId,projectId},signal);if(value.project.id!==projectId||value.project.tenantId!==account.workspaceId)accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");if(value.project.lifecycle!=="ACTIVE")accountError("PROJECT_ARCHIVED");await saveAccount(root,{...account,projectId});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Use the existing workspace connection; run nvs connect if this workspace is not connected.","nvs status"]}}}))}var exits={SUCCESS:0,ACCEPTED:0,INVALID_INPUT:2,NOT_FOUND:3,BLOCKED:4,CAPABILITY_UNAVAILABLE:4,REVISION_CONFLICT:5};async function runRemoteCli(argv,environment=process.env,stdin=process.stdin){try{if(argv[0]==="connect")return await(await import("./connect-6UH7ZFAC.js")).runConnect(argv,environment);if(argv[0]==="login")return await runAccountLogin(argv,environment);if(argv[0]==="render")return await(await import("./render-main-VTM6WGFP.js")).renderCommand(argv.slice(1),environment);if(argv[0]==="devices")return await(await import("./devices-main-VV2VYU4T.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-KKV2UWJO.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-Y7ZVBRJJ.js")).workspaceCommand(argv,environment);return business??await runAccountCommand(argv,environment)}if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-HC6TI7HB.js")).runOAuthCommand(argv,stdin);if(!argv.length||argv.length===1&&["help","--help"].includes(argv[0]))return{exitCode:0,output:{product:"NativeStudio CLI",start:["nvs login --server <Studio-origin> \u2014 sign in/register your account in the browser; no project required.","nvs workspaces; nvs workspace --id <id>; nvs projects; nvs project --id <id>","nvs connect (authorizes the selected workspace once; supports its Projects and devices)","nvs status","nvs skill \u2014 read the configured SKILL download URL through the existing connection","nvs find --query <intent>"],navigation:["nvs capabilities","nvs overview --production <uuid>","nvs next --production <uuid>","nvs resume --production <uuid> --operation <op_original>"],agentConnection:{command:"nvs",args:["mcp"],note:"Uses the private saved connection; no token in Agent configuration."},commands:["login --server <Studio-origin> | whoami | logout \u2014 independent account session","workspaces | workspace --id <id> | projects [--limit <n>] [--next <cursor>] | project --id <id>","connect [--mcp-url <workspace-connection-url>] \u2014 authorize the workspace once for its Projects and devices","status","skill \u2014 read the configured SKILL download URL/status; no automatic download","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","devices inventory [--device <uuid>] [--after <uuid>] [--limit <1..50>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read Workspace device registration and connection facts; no project required","devices list --kind preview|final|library|<processor-kind> [--project <uuid>] [--device <uuid>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read candidates for this Project task; connection alone does not imply eligibility","devices enroll|revoke|receipt --input <json|-> \u2014 uses the saved tenant OAuth and original native command","render preview|final --production <uuid> --request <stable-uuid> [--project <uuid>] [--device <uuid>] [--validation-mode TENANT_TRUSTED_VALIDATOR] \u2014 tenant device only; saves original receipt","render status|download --kind preview|final --production <uuid> --render <uuid> [--project <uuid>] [--output <file>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates","host help \u2014 enroll/prove/connect an execution device using the external Agent's existing MCP session; discover the separate SKILL URL with nvs skill or workspace_caller.skill"],advanced:["operations","mcp --profile <private-file> | --mcp-url <endpoint> --token-env <NAME>|--token-file <private-file>","call <operation> --input <file|-> --tenant <uuid> --token-env <NAME> --origin <https-origin>","call <operation> --input <file|-> --tenant <uuid> --token-file <private-file> --mcp-url <https-endpoint>","auth-start --profile <new-private-file> --mcp-url <resource> --callback <receiver-url>","auth-complete --profile <private-file> --input <callback-json-file|->","call <operation> --profile <private-file> --tenant <uuid> --input <file|->","import project|original --input <intent.json|-> --file <media> --tenant <uuid> --origin <https-origin> --token-file <private-file>"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{NativeStudioAgentClient,sdkOperations,sdkMcpTools,sdkCarrierDifferences,assertCarrierCoverage}=await import("./src-OIY5TBQT.js");if(argv.length===1&&argv[0]==="operations"){assertCarrierCoverage(sdkOperations,sdkCarrierDifferences);return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null,mcp:sdkMcpTools[name2],carrierDifference:Object.hasOwn(sdkCarrierDifferences,name2)?sdkCarrierDifferences[name2]:null}))}}}const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();if(name==="rough-cut.media-ticket"||name==="final-render.media-ticket")throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile","--transport"];for(let i=0;i<args.length;i+=2){const key2=args[i],value=args[i+1];if(!key2||!allowed.includes(key2)||!value||value.startsWith("--")||options.has(key2))throw Error();options.set(key2,value)}await defaultConnection(options,environment,true);if(!options.has("--input")||!options.has("--tenant")||(options.has("--profile")?options.has("--origin")||options.has("--mcp-url")||options.has("--token-file")||options.has("--token-env"):options.has("--origin")===options.has("--mcp-url")))throw Error();const key=name;const transport=options.get("--transport");if(transport&&!["http","mcp"].includes(transport))throw Error();if(!options.has("--profile")&&transport&&transport!==(options.has("--origin")?"http":"mcp"))throw Error();const input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-HC6TI7HB.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;const profileHttp=profile&&(transport==="http"||!transport&&sdkMcpTools[key]===null);if(!profileHttp&&(profile||options.has("--mcp-url"))){const{connectRemoteMcp}=await import("./mcp-EXQ5UAHB.js");const connection=await connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,tenantId);try{output=await connection.studio.call(key,input)}finally{await connection.close()}}else{const studio=new NativeStudioAgentClient({tenantId,baseUrl:profileHttp?await(await import("./http-profile-NIQDCFPU.js")).profileHttpOrigin(options.get("--profile"),profile.resource):options.get("--origin"),authorization:()=>authorization});output=await studio.call(key,input)}const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <workspace-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/project before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE",...e?.issues.length?{issues:e.issues}:{}},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["TENANT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <workspace-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{connectRemoteMcp}from"./chunk-77IAHNM2.js";import"./chunk-2UYKJ6YN.js";import"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import"./chunk-HTUTYIRU.js";export{connectRemoteMcp};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{profileAuthorization,runOAuthCommand}from"./chunk-3AVC742O.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-PUNG4ND7.js";import"./chunk-HTUTYIRU.js";export{profileAuthorization,runOAuthCommand};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{CapabilityDescribeSchema,CapabilityGroupsSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,assertCarrierCoverage,navigationGroup,queryPages,sdkCarrierDifferences,sdkImageMediaTools,sdkMcpTools,sdkOperations,waitForOperation}from"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import{FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema}from"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-HTUTYIRU.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,assertCarrierCoverage,navigationGroup,queryPages,sdkCarrierDifferences,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,waitForOperation};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{workspaceCommand,workspaceProject}from"./chunk-S74X4KIC.js";import"./chunk-SV3NF7GO.js";import"./chunk-3AVC742O.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-77IAHNM2.js";import"./chunk-2UYKJ6YN.js";import"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import"./chunk-HTUTYIRU.js";export{workspaceCommand,workspaceProject};
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
$ErrorActionPreference = 'Stop'
|
|
2
|
-
[Console]::InputEncoding = New-Object Text.UTF8Encoding($false)
|
|
3
|
-
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
|
4
|
-
try {
|
|
5
|
-
$raw = [Console]::In.ReadToEnd()
|
|
6
|
-
if ($raw.Length -gt 32768) { throw 'INPUT_LIMIT' }
|
|
7
|
-
$request = $raw | ConvertFrom-Json
|
|
8
|
-
$names = @('Bootstrap.ps1','NativeMain.cs','PrivateAccess.cs','PipeBridge.cs','JobNative.cs','JobRunner.cs')
|
|
9
|
-
$directory = [IO.Path]::GetFullPath($request.directory)
|
|
10
|
-
$hash = [Security.Cryptography.SHA256]::Create()
|
|
11
|
-
foreach ($name in $names) {
|
|
12
|
-
$file = Join-Path $directory $name
|
|
13
|
-
if (([IO.File]::GetAttributes($file) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'REPARSE' }
|
|
14
|
-
$prefix = [Text.Encoding]::UTF8.GetBytes($name + "`n")
|
|
15
|
-
[void]$hash.TransformBlock($prefix,0,$prefix.Length,$prefix,0)
|
|
16
|
-
$bytes = [IO.File]::ReadAllBytes($file)
|
|
17
|
-
if ($bytes.Length -gt 262144) { throw 'SOURCE_LIMIT' }
|
|
18
|
-
[void]$hash.TransformBlock($bytes,0,$bytes.Length,$bytes,0)
|
|
19
|
-
}
|
|
20
|
-
[void]$hash.TransformFinalBlock([byte[]]@(),0,0)
|
|
21
|
-
$digest = ([BitConverter]::ToString($hash.Hash)).Replace('-','').ToLowerInvariant()
|
|
22
|
-
if ($digest -ne $request.sourceDigest) { throw 'SOURCE_CHANGED' }
|
|
23
|
-
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
24
|
-
function Check-Private([string]$path) {
|
|
25
|
-
$item = Get-Item -LiteralPath $path -Force
|
|
26
|
-
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'REPARSE' }
|
|
27
|
-
$acl = $item.GetAccessControl()
|
|
28
|
-
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'OWNER' }
|
|
29
|
-
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
|
|
30
|
-
if ($rule.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and
|
|
31
|
-
$rule.IdentityReference.Value -notin @($sid.Value,'S-1-5-18','S-1-5-32-544')) { throw 'ACL' }
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
function Private-Directory([string]$path) {
|
|
35
|
-
if ([IO.Directory]::Exists($path)) { Check-Private $path; return }
|
|
36
|
-
$acl = New-Object Security.AccessControl.DirectorySecurity
|
|
37
|
-
$acl.SetOwner($sid)
|
|
38
|
-
$acl.SetAccessRuleProtection($true,$false)
|
|
39
|
-
$rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow')
|
|
40
|
-
$acl.AddAccessRule($rule)
|
|
41
|
-
[void][IO.Directory]::CreateDirectory($path,$acl)
|
|
42
|
-
Check-Private $path
|
|
43
|
-
}
|
|
44
|
-
$base = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'NativeStudio-platform'
|
|
45
|
-
Private-Directory $base
|
|
46
|
-
$cache = Join-Path $base $digest
|
|
47
|
-
Private-Directory $cache
|
|
48
|
-
$mutex = New-Object Threading.Mutex($false,('Local\NVS-compile-' + $sid.Value + '-' + $digest))
|
|
49
|
-
$locked = $false
|
|
50
|
-
try {
|
|
51
|
-
try { $locked = $mutex.WaitOne(10000) } catch [Threading.AbandonedMutexException] { $locked = $true }
|
|
52
|
-
if (-not $locked) { throw 'BUSY' }
|
|
53
|
-
$record = Join-Path $cache 'helper.json'
|
|
54
|
-
if ([IO.File]::Exists($record)) {
|
|
55
|
-
Check-Private $record
|
|
56
|
-
$value = [IO.File]::ReadAllText($record) | ConvertFrom-Json
|
|
57
|
-
if ($value.sourceDigest -ne $digest -or $value.file -notmatch '^helper-[0-9a-f-]{36}\.exe$') { throw 'CACHE' }
|
|
58
|
-
$executable = Join-Path $cache $value.file
|
|
59
|
-
Check-Private $executable
|
|
60
|
-
$actual = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
61
|
-
if ($actual -ne $value.sha256) { throw 'CACHE_CHANGED' }
|
|
62
|
-
} else {
|
|
63
|
-
$file = 'helper-' + [Guid]::NewGuid().ToString() + '.exe'
|
|
64
|
-
$executable = Join-Path $cache $file
|
|
65
|
-
$sources = @($names | Where-Object { $_.EndsWith('.cs') } | ForEach-Object { Join-Path $directory $_ })
|
|
66
|
-
$compiler = New-Object CodeDom.Compiler.CompilerParameters
|
|
67
|
-
$compiler.GenerateExecutable = $true
|
|
68
|
-
$compiler.OutputAssembly = $executable
|
|
69
|
-
$compiler.CompilerOptions = '/platform:x64 /optimize+ /langversion:5'
|
|
70
|
-
$compiler.ReferencedAssemblies.AddRange(@('System.dll','System.Core.dll','System.Web.dll','System.Web.Extensions.dll','System.Security.dll'))
|
|
71
|
-
Add-Type -Path $sources -CompilerParameters $compiler
|
|
72
|
-
Check-Private $executable
|
|
73
|
-
$actual = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
74
|
-
$value = @{ sourceDigest=$digest; file=$file; sha256=$actual }
|
|
75
|
-
$temporary = Join-Path $cache ([Guid]::NewGuid().ToString() + '.json')
|
|
76
|
-
$bytes = [Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Compress))
|
|
77
|
-
$stream = New-Object IO.FileStream($temporary,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
|
|
78
|
-
try { $stream.Write($bytes,0,$bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() }
|
|
79
|
-
[IO.File]::Move($temporary,$record)
|
|
80
|
-
Check-Private $record
|
|
81
|
-
}
|
|
82
|
-
@{ path=$executable; sha256=$actual; sourceDigest=$digest } | ConvertTo-Json -Compress
|
|
83
|
-
} finally {
|
|
84
|
-
if ($locked) { $mutex.ReleaseMutex() }
|
|
85
|
-
$mutex.Dispose()
|
|
86
|
-
}
|
|
87
|
-
} catch {
|
|
88
|
-
[Console]::Error.WriteLine('WINDOWS_HELPER_UNAVAILABLE')
|
|
89
|
-
exit 1
|
|
90
|
-
}
|
package/dist/native/JobNative.cs
DELETED
|
@@ -1,137 +0,0 @@
|
|
|
1
|
-
using System;
|
|
2
|
-
using System.Runtime.InteropServices;
|
|
3
|
-
using System.Text;
|
|
4
|
-
using Microsoft.Win32.SafeHandles;
|
|
5
|
-
namespace NativeStudio.Platform
|
|
6
|
-
{
|
|
7
|
-
public static class JobNative
|
|
8
|
-
{
|
|
9
|
-
[StructLayout(LayoutKind.Sequential)]
|
|
10
|
-
public struct SecurityAttributes
|
|
11
|
-
{
|
|
12
|
-
public int size; public IntPtr descriptor; public int inherit;
|
|
13
|
-
}
|
|
14
|
-
[StructLayout(LayoutKind.Sequential)]
|
|
15
|
-
public struct StartupInfo
|
|
16
|
-
{
|
|
17
|
-
public int size; public string reserved, desktop, title;
|
|
18
|
-
public uint x, y, xSize, ySize, xChars, yChars, fill, flags; public ushort show, reservedSize;
|
|
19
|
-
public IntPtr reservedBytes, input, output, error;
|
|
20
|
-
}
|
|
21
|
-
[StructLayout(LayoutKind.Sequential)]
|
|
22
|
-
public struct ProcessInfo
|
|
23
|
-
{
|
|
24
|
-
public IntPtr process, thread; public uint processId, threadId;
|
|
25
|
-
}
|
|
26
|
-
[StructLayout(LayoutKind.Sequential)]
|
|
27
|
-
public struct BasicLimits
|
|
28
|
-
{
|
|
29
|
-
public long processTime, jobTime; public uint flags; public UIntPtr minWorking, maxWorking;
|
|
30
|
-
public uint active; public UIntPtr affinity; public uint priority, scheduling;
|
|
31
|
-
}
|
|
32
|
-
[StructLayout(LayoutKind.Sequential)]
|
|
33
|
-
public struct Counters
|
|
34
|
-
{
|
|
35
|
-
public ulong readOps, writeOps, otherOps, readBytes, writeBytes, otherBytes;
|
|
36
|
-
}
|
|
37
|
-
[StructLayout(LayoutKind.Sequential)]
|
|
38
|
-
public struct ExtendedLimits
|
|
39
|
-
{
|
|
40
|
-
public BasicLimits basic; public Counters io; public UIntPtr processMemory, jobMemory, peakProcess, peakJob;
|
|
41
|
-
}
|
|
42
|
-
[StructLayout(LayoutKind.Sequential)]
|
|
43
|
-
public struct CpuLimits
|
|
44
|
-
{
|
|
45
|
-
public uint flags, rate;
|
|
46
|
-
}
|
|
47
|
-
[DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr CreateJobObject(IntPtr sa, string name);
|
|
48
|
-
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr job, int type, IntPtr value, uint size);
|
|
49
|
-
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool QueryInformationJobObject(IntPtr job, int type, IntPtr value, uint size, out uint length);
|
|
50
|
-
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
51
|
-
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateJobObject(IntPtr job, uint code);
|
|
52
|
-
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateProcess(IntPtr process, uint code);
|
|
53
|
-
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CreateProcess(string application, StringBuilder command, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr environment, string directory, ref StartupInfo startup, out ProcessInfo info);
|
|
54
|
-
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool CreatePipe(out IntPtr read, out IntPtr write, ref SecurityAttributes sa, uint size);
|
|
55
|
-
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetHandleInformation(IntPtr handle, uint mask, uint flags);
|
|
56
|
-
[DllImport("kernel32.dll")] public static extern uint ResumeThread(IntPtr thread);
|
|
57
|
-
[DllImport("kernel32.dll")] public static extern uint WaitForSingleObject(IntPtr handle, uint ms);
|
|
58
|
-
[DllImport("kernel32.dll")] public static extern bool GetExitCodeProcess(IntPtr process, out uint code);
|
|
59
|
-
[DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr handle);
|
|
60
|
-
[DllImport("kernel32.dll", EntryPoint = "TerminateJobObject", SetLastError = true)]
|
|
61
|
-
static extern bool TerminateOwnedJob(SafeFileHandle job, uint code);
|
|
62
|
-
public static void Kill(SafeFileHandle job)
|
|
63
|
-
{
|
|
64
|
-
if (job == null)
|
|
65
|
-
return;
|
|
66
|
-
try
|
|
67
|
-
{
|
|
68
|
-
TerminateOwnedJob(job, 1);
|
|
69
|
-
}
|
|
70
|
-
catch (ObjectDisposedException) { }
|
|
71
|
-
}
|
|
72
|
-
public static void Set<T>(IntPtr job, int kind, T data)
|
|
73
|
-
{
|
|
74
|
-
int size = Marshal.SizeOf(typeof(T));
|
|
75
|
-
IntPtr memory = Marshal.AllocHGlobal(size);
|
|
76
|
-
try
|
|
77
|
-
{
|
|
78
|
-
Marshal.StructureToPtr(data, memory, false);
|
|
79
|
-
if (!SetInformationJobObject(job, kind, memory, (uint)size))
|
|
80
|
-
throw new Exception("JOB_LIMIT");
|
|
81
|
-
}
|
|
82
|
-
finally { Marshal.FreeHGlobal(memory); }
|
|
83
|
-
}
|
|
84
|
-
public static IntPtr Job(bool aggregate)
|
|
85
|
-
{
|
|
86
|
-
var job = CreateJobObject(IntPtr.Zero, null);
|
|
87
|
-
if (job == IntPtr.Zero)
|
|
88
|
-
throw new Exception("JOB_CREATE");
|
|
89
|
-
try
|
|
90
|
-
{
|
|
91
|
-
var limits = new ExtendedLimits();
|
|
92
|
-
limits.basic.flags = 0x2000; // KILL_ON_JOB_CLOSE; no breakaway.
|
|
93
|
-
if (aggregate)
|
|
94
|
-
{
|
|
95
|
-
limits.basic.flags |= 0x200 | 8 | 0x20;
|
|
96
|
-
limits.jobMemory = new UIntPtr(4294967296UL);
|
|
97
|
-
limits.basic.active = 64;
|
|
98
|
-
limits.basic.priority = 0x4000;
|
|
99
|
-
}
|
|
100
|
-
Set(job, 9, limits);
|
|
101
|
-
if (aggregate)
|
|
102
|
-
Set(job, 15, new CpuLimits { flags = 5, rate = (uint)Math.Min(10000, Math.Max(1, 20000 / Environment.ProcessorCount)) });
|
|
103
|
-
return job;
|
|
104
|
-
}
|
|
105
|
-
catch { CloseHandle(job); throw; }
|
|
106
|
-
}
|
|
107
|
-
public static void Budget(IntPtr job, double cores, ulong memory)
|
|
108
|
-
{
|
|
109
|
-
var limits = new ExtendedLimits();
|
|
110
|
-
limits.basic.flags = 0x2000 | 0x200 | 8 | 0x20;
|
|
111
|
-
limits.jobMemory = new UIntPtr(memory);
|
|
112
|
-
limits.basic.active = 64;
|
|
113
|
-
limits.basic.priority = 0x4000;
|
|
114
|
-
Set(job, 9, limits);
|
|
115
|
-
Set(job, 15, new CpuLimits { flags = 5, rate = (uint)Math.Min(10000, Math.Max(1, cores * 10000 / Environment.ProcessorCount)) });
|
|
116
|
-
}
|
|
117
|
-
public static uint[] Processes(IntPtr job)
|
|
118
|
-
{
|
|
119
|
-
int size = 8 + 64 * IntPtr.Size;
|
|
120
|
-
IntPtr memory = Marshal.AllocHGlobal(size);
|
|
121
|
-
try
|
|
122
|
-
{
|
|
123
|
-
uint length;
|
|
124
|
-
if (!QueryInformationJobObject(job, 3, memory, (uint)size, out length))
|
|
125
|
-
throw new Exception("JOB_INSPECT");
|
|
126
|
-
int count = Marshal.ReadInt32(memory, 4);
|
|
127
|
-
if (count < 0 || count > 64)
|
|
128
|
-
throw new Exception("JOB_LIMIT");
|
|
129
|
-
var ids = new uint[count];
|
|
130
|
-
for (int i = 0; i < count; i++)
|
|
131
|
-
ids[i] = unchecked((uint)Marshal.ReadIntPtr(memory, 8 + i * IntPtr.Size).ToInt64());
|
|
132
|
-
return ids;
|
|
133
|
-
}
|
|
134
|
-
finally { Marshal.FreeHGlobal(memory); }
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|