@nativestudio/cli 0.3.0-rc.1 → 0.3.0-rc.4
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 +7 -7
- package/README.md +45 -4
- package/components/runtime.json +3 -3
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-25EDDZQA.js → chunk-6LU6GJKW.js} +1 -1
- package/dist/_chunks/chunk-CA54SKBO.js +1 -0
- package/dist/_chunks/chunk-D533YC7J.js +1 -0
- package/dist/_chunks/{chunk-G42IS5JF.js → chunk-DXJQWTLG.js} +1 -1
- package/dist/_chunks/{chunk-MSOMVWKN.js → chunk-FU3524Z6.js} +1 -1
- package/dist/_chunks/chunk-JLOHTDP6.js +1 -0
- package/dist/_chunks/chunk-KB2GVAN7.js +1 -0
- package/dist/_chunks/{chunk-RUMDDTON.js → chunk-KNFUMWDY.js} +1 -1
- package/dist/_chunks/chunk-PBEHCYR7.js +1 -0
- package/dist/_chunks/chunk-RNOIRNC3.js +1 -0
- package/dist/_chunks/chunk-VDQOSVZY.js +1 -0
- package/dist/_chunks/chunk-XZP6RNGC.js +1 -0
- package/dist/_chunks/chunk-YKOJPJZR.js +1 -0
- package/dist/_chunks/{files-TBJVDQWU.js → files-TTIQ7LYJ.js} +1 -1
- package/dist/_chunks/local-main-GSL2FQOG.js +1 -0
- package/dist/_chunks/local-mcp-VYHO4ZE3.js +1 -0
- package/dist/_chunks/{main-4SNF5EKE.js → main-KLXOK7QK.js} +2 -2
- package/dist/_chunks/mcp-P7W623FE.js +1 -0
- package/dist/_chunks/oauth-WJ36KWAC.js +1 -0
- package/dist/_chunks/project-connect-W7V3OALV.js +1 -0
- package/dist/_chunks/render-main-ZW6UJHGN.js +1 -0
- package/dist/_chunks/src-BXLFLNRG.js +1 -0
- package/dist/_chunks/{stdio-main-JEADWO7U.js → stdio-main-4Z2JVCMO.js} +1 -1
- package/dist/_types/cli/local/desktop-contract.d.ts +1455 -0
- package/dist/_types/cli/local/desktop-device-contract.d.ts +1165 -0
- package/dist/_types/cli/local/desktop-device-navigation.d.ts +3 -0
- package/dist/_types/cli/local/desktop-device-owner.d.ts +275 -0
- package/dist/_types/cli/local/desktop-device-state.d.ts +230 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +554 -1
- package/dist/_types/cli/local/ledger.d.ts +62 -10
- package/dist/_types/cli/local/manager.d.ts +515 -22
- package/dist/_types/cli/local/mcp-tools.d.ts +77 -14
- package/dist/_types/cli/local/project-render-tools.d.ts +522 -0
- package/dist/_types/cli/local/releases.d.ts +11 -2
- package/dist/_types/cli/local-management.d.ts +4 -0
- package/dist/_types/cli/local-navigation.d.ts +1 -0
- package/dist/_types/contracts/delivery-manifest.d.ts +63 -27
- package/dist/_types/contracts/delivery-operations.d.ts +21 -9
- package/dist/_types/contracts/device-render.d.ts +10 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +84 -36
- package/dist/_types/contracts/final-render.d.ts +9 -0
- package/dist/_types/contracts/index.d.ts +1 -0
- package/dist/_types/contracts/local-execution/agent-context.d.ts +365 -0
- package/dist/_types/contracts/local-execution/agent-evidence.d.ts +79 -0
- package/dist/_types/contracts/local-execution/agent-grant.d.ts +31 -0
- package/dist/_types/contracts/local-execution/agent-review.d.ts +733 -46
- package/dist/_types/contracts/local-execution/device.d.ts +10 -2
- package/dist/_types/contracts/local-execution/index.d.ts +6 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +1762 -40
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +76 -6
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +115 -13
- package/dist/_types/contracts/local-execution/management.d.ts +394 -0
- package/dist/_types/contracts/local-execution/media-recipe.d.ts +203 -0
- package/dist/_types/contracts/local-execution/offline.d.ts +59 -0
- package/dist/_types/contracts/local-execution/preview.d.ts +7607 -159
- package/dist/_types/contracts/local-execution/work.d.ts +7674 -294
- package/dist/_types/contracts/local-execution/workspace.d.ts +136 -0
- package/dist/_types/contracts/programmatic-exploration.d.ts +42 -18
- package/dist/_types/contracts/repair-strategy.d.ts +42 -18
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +42 -18
- package/dist/_types/contracts/review-intelligence.d.ts +84 -36
- package/dist/_types/contracts/rough-cut-manifest.d.ts +7 -3
- package/dist/_types/contracts/rough-cut-profile.d.ts +12 -3
- package/dist/_types/contracts/rough-cut-review.d.ts +126 -54
- package/dist/_types/contracts/rough-cut.d.ts +85 -32
- package/dist/_types/contracts/visual-layer-render.d.ts +21 -9
- package/dist/_types/sdk/local-runtime/device-client.d.ts +138 -2
- package/dist/_types/sdk/local-runtime/workspace.d.ts +181 -0
- package/dist/_types/sdk/local-runtime-client.d.ts +1298 -60
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/dist/native/JobNative.cs +10 -0
- package/dist/native/JobRunner.cs +24 -3
- package/dist/native/NativeMain.cs +15 -0
- package/package.json +1 -1
- package/dist/_chunks/chunk-E57YVMQ4.js +0 -1
- package/dist/_chunks/chunk-EAZKDCLD.js +0 -1
- package/dist/_chunks/chunk-GIEYSDCG.js +0 -1
- package/dist/_chunks/chunk-HLKERZIE.js +0 -1
- package/dist/_chunks/chunk-QC7RLTGU.js +0 -1
- package/dist/_chunks/chunk-U2UKGYGF.js +0 -1
- package/dist/_chunks/local-main-SOERK22D.js +0 -1
- package/dist/_chunks/local-mcp-JLPXXIDW.js +0 -1
- package/dist/_chunks/mcp-EIMXNRH3.js +0 -1
- package/dist/_chunks/oauth-257CEUQH.js +0 -1
- package/dist/_chunks/project-connect-6MH2QG6G.js +0 -1
- package/dist/_chunks/src-7F6ZEU3U.js +0 -1
package/dist/entry.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-
|
|
2
|
+
if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-VYHO4ZE3.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-GSL2FQOG.js");const result=await runLocalCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}}else if(process.argv[2]==="mcp"){const{runMcpStdio}=await import("./_chunks/stdio-main-4Z2JVCMO.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-KLXOK7QK.js");const result=await runRemoteCli(process.argv.slice(2));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}
|
package/dist/local-management.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalInstallationManager,socketAbsent}from"./_chunks/chunk-U2UKGYGF.js";import{LocalRuntimeDescriptorSchema,canonicalLocalJson,endpoint}from"./_chunks/chunk-EAZKDCLD.js";import"./_chunks/chunk-HLKERZIE.js";import"./_chunks/chunk-VPYAXWXY.js";import{LocalClientError,directory,fail,read,sha256,write}from"./_chunks/chunk-GIEYSDCG.js";import"./_chunks/chunk-6NVIN2NI.js";import{z}from"zod";var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z.string().url().max(4096),publicKey:z.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z.discriminatedUnion("operation",[z.strictObject({operation:z.enum(["status","start","stop","check","configuration","recovery"])}),z.strictObject({operation:z.enum(["prepare","reject"]),version}),z.strictObject({operation:z.literal("configure"),channelFingerprint:fingerprint}),z.strictObject({operation:z.enum(["apply","recover"]),planId:z.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z.string().regex(/^[A-Z_]{1,64}$/)});var DesktopUpdateCheckSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z.array(z.strictObject({version,rejected:z.boolean()})).max(128),notifications:z.boolean()});var DesktopOwnerPlanSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z.strictObject({kind:z.enum(["APPLY","RECOVER"]),planId:z.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z.iso.datetime(),phase:z.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z.boolean(),source:z.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase})}import{createPublicKey}from"node:crypto";import{join}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED"))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;const stateDirectory=join(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop")await manager.stop();result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"prepare":{const plan=await manager.prepare(request.version);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat,readFile,chmod}from"node:fs/promises";import{join as join2,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join2(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join2(await directory(home),"nodes",expected)),target=join2(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join2(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopOwnerRequestSchema,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,runDesktopOwnerRequest,runLocalManagement};
|
|
1
|
+
import{LocalInstallationManager,captureInstalledTools,connectDevice,generateDeviceKey,newerVersion,ownerClient,socketAbsent,toolPreference,waitStopped}from"./_chunks/chunk-XZP6RNGC.js";import{DesktopDeviceRecords,DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-VDQOSVZY.js";import{LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDeviceChallengeSchema,LocalDeviceGrantSchema,LocalDeviceSessionSchema,LocalDeviceViewSchema,LocalDiagnosticsSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalPreviewAdmissionSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema,canonicalLocalJson,catalogue,endpoint}from"./_chunks/chunk-JLOHTDP6.js";import{LocalClientError,atomicMove,directory,entries,fail,optional,read,sha256,write}from"./_chunks/chunk-KB2GVAN7.js";import"./_chunks/chunk-PBEHCYR7.js";import"./_chunks/chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./_chunks/chunk-6NVIN2NI.js";import{z as z8}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest5=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest5||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest5}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest5=record.digest}return{plan,digest:digest5}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z3}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join4,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}import{join as join3}from"node:path";import{z as z2}from"zod";var digest=z2.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z2.strictObject({enabled:z2.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z2.uuid(),deviceRevision:z2.int().positive(),installationFingerprint:digest,projects:z2.array(z2.strictObject({projectId:z2.uuid(),grantId:z2.uuid(),revision:z2.int().positive(),expiresAt:z2.iso.datetime()})).min(1).max(20)});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join3(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;const grants=state.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());return grants.length>0&&grants.every(g=>policy.projects.some(p=>p.projectId===g.projectId&&p.grantId===g.grantId&&p.revision===g.revision&&p.expiresAt===g.expiresAt))}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint,projectIds){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const grants=state.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());if(!grants.length||grants.some(g=>!projectIds.includes(g.projectId)))fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint,projects:grants.map(g=>({projectId:g.projectId,grantId:g.grantId,revision:g.revision,expiresAt:g.expiresAt}))});await write(join3(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join3(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}var id=z3.uuid();var digest2=z3.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z3.strictObject({operation:z3.literal("storage"),call:z3.discriminatedUnion("action",[z3.strictObject({action:z3.literal("status")}),z3.strictObject({action:z3.literal("prepare"),mode:z3.enum(["BACKUP","MIGRATE"]),destination:z3.string().min(1).max(4096)}),z3.strictObject({action:z3.enum(["execute","recover","abandon"]),id,fingerprint:digest2})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view2}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view2)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join4(home,"storage-plans"));const pointer=await optional(join4(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join4(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join4(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join4(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join4(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join4(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join4(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z4}from"zod";var DesktopOfflineRequestSchema=z4.strictObject({operation:z4.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!policy.projects.some(p=>Date.parse(p.expiresAt)>Date.now())||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z5}from"zod";import{join as join5}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z5.string().regex(/^[a-f0-9]{64}$/);var historyItem=z5.strictObject({id:z5.uuid(),projectId:z5.uuid(),productionId:z5.uuid(),kind:z5.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z5.uuid().optional()});var stateSchema=z5.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z5.array(historyItem).max(200)});var DesktopAgentRequestSchema=z5.strictObject({operation:z5.literal("agent"),scope:DesktopDeviceScopeSchema,call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("discover"),binary:z5.string().min(1).max(4096).optional()}),z5.strictObject({action:z5.literal("probe")}),z5.strictObject({action:z5.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z5.strictObject({action:z5.literal("revoke")}),z5.strictObject({action:z5.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z5.strictObject({action:z5.literal("stage"),id:z5.uuid(),mediaFileId:z5.uuid().optional()}),z5.strictObject({action:z5.literal("start"),id:z5.uuid(),expectedRevision:z5.int().positive(),approval:sha}),z5.strictObject({action:z5.literal("inspect"),id:z5.uuid()})])});var DesktopAgentReplySchema=z5.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z5.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z5.boolean()})).max(200),pendingGrant:z5.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join5(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join5(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join5(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join5(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z6}from"zod";var digest3=z6.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z6.strictObject({operation:z6.literal("bootstrap"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.literal("prepare")}),z6.strictObject({action:z6.literal("apply"),id:z6.uuid(),fingerprint:digest3})])});var DesktopBootstrapReplySchema=z6.strictObject({id:z6.uuid(),fingerprint:digest3,version:z6.string().min(1).max(80),host:z6.string().min(1).max(512),bytes:z6.int().positive(),expiresAt:z6.iso.datetime(),installed:z6.boolean()});import{z as z7}from"zod";var DesktopWorkspaceRequestSchema=z7.strictObject({operation:z7.literal("workspace"),call:z7.discriminatedUnion("action",[z7.strictObject({action:z7.enum(["inspect","clean","diagnostics"])}),z7.strictObject({action:z7.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z7.int().nonnegative()}),z7.strictObject({action:z7.literal("activity"),idleSeconds:z7.int().min(0).max(86400),observedAt:z7.iso.datetime()})])});var DesktopWorkspaceReplySchema=z7.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z8.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z8.string().url().max(4096),publicKey:z8.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z8.discriminatedUnion("operation",[DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z8.strictObject({operation:z8.enum(["status","start","stop","check","configuration","recovery"])}),z8.strictObject({operation:z8.enum(["prepare","reject"]),version}),z8.strictObject({operation:z8.literal("tools-prepare"),version,choice:z8.discriminatedUnion("mode",[z8.strictObject({mode:z8.literal("MANAGED")}),z8.strictObject({mode:z8.literal("INSTALLED"),ffmpeg:z8.string().min(1).max(4096),ffprobe:z8.string().min(1).max(4096)})])}),z8.strictObject({operation:z8.literal("configure"),channelFingerprint:fingerprint}),z8.strictObject({operation:z8.enum(["apply","recover"]),planId:z8.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z8.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z8.string().regex(/^[A-Z_]{1,64}$/),toolMode:z8.enum(["MANAGED","INSTALLED"]).nullable().optional()});var DesktopUpdateCheckSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z8.array(z8.strictObject({version,rejected:z8.boolean()})).max(128),notifications:z8.boolean()});var DesktopOwnerPlanSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z8.strictObject({kind:z8.enum(["APPLY","RECOVER"]),toolMode:z8.enum(["MANAGED","INSTALLED"]).optional(),planId:z8.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z8.iso.datetime(),phase:z8.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z8.boolean(),source:z8.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z8.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;const active=(await manager.ledger.current()).value.active;const toolMode=active?.toolsConfigPath?(await toolPreference(active.toolsConfigPath,null)).mode:null;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase,toolMode})}import{createPublicKey}from"node:crypto";import{join as join6}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED"))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;const stateDirectory=join6(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join6(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join6(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}import{createPrivateKey as createPrivateKey2,createPublicKey as createPublicKey2,randomUUID as randomUUID4}from"node:crypto";import{randomUUID as randomUUID2}from"node:crypto";async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device)fail("DEVICE_ENROLLMENT_REQUIRED");const valid=s.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());if(!valid.length)fail("LOCAL_AUTHORIZATION_REQUIRED");const projects=valid.map(g=>({tenantId:g.tenantId,projectId:g.projectId}));const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const reuse=running&&previous&&canonicalLocalJson(previous.projects)===canonicalLocalJson(projects);const expiresAt=new Date(Math.min(Date.now()+24*36e5,...valid.map(g=>Date.parse(g.expiresAt)))).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",projects,expiresAt}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,projects});await manager.start()}const id2=randomUUID2();await manager.grant({projects,expiresAt},records.connectorPath(id2));return records.save(s,{connectorId:id2,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const actual=JSON.parse((await read(c.cloudConfigFile,32768)).toString());if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||canonicalLocalJson(actual.projects)!==canonicalLocalJson(s.connection.projects))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID3}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)<=Date.now())fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.now()/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID3(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint2=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label}:null,grants:s.grants,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="GRANT"){const g=LocalDeviceGrantSchema.parse(result),input2=command.input;if(g.tenantId!==input2.tenantId||g.projectId!==input2.projectId||g.deviceId!==input2.deviceId||g.deviceRevision!==input2.deviceRevision||g.revision!==input2.expectedRevision+1||g.expiresAt!==input2.expiresAt||g.capability!==input2.capability||g.executionPolicy!==input2.executionPolicy||g.approvedByPrincipalId!==s.scope.principalId||g.revokedAt)fail("DEVICE_RESULT_INVALID");return{grants:[...s.grants.filter(v=>v.projectId!==g.projectId),g]}}if(command.kind==="REVOKE_GRANT"){if(result?.semanticStatus!=="SUCCESS")fail("DEVICE_RESULT_INVALID");return{grants:s.grants.map(g=>g.projectId===command.input.projectId?{...g,revision:g.revision+1,revokedAt:new Date().toISOString()}:g),connectorId:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint,call.projectIds);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey2(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID4(),label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(!s.grants.some(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now()))fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID4()}}}else{const grant=s.grants.find(g=>g.projectId===call.projectId);if(call.action==="grant"){const ttl=Date.parse(call.expiresAt)-Date.now();if(ttl<=0||ttl>24*36e5||s.grants.length>=20&&!grant)fail("INVALID_INPUT");command={kind:"GRANT",input:{tenantId:s.scope.tenantId,projectId:call.projectId,requestId:randomUUID4(),deviceId:d.deviceId,deviceRevision:d.revision,expectedRevision:grant?.revision??0,expiresAt:call.expiresAt,...call.executionPolicy?{executionPolicy:call.executionPolicy}:{},capability:call.capability??"ROUGH_CUT_PREVIEW_V1"}}}else{if(!grant||grant.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_GRANT",input:{tenantId:s.scope.tenantId,projectId:call.projectId,requestId:randomUUID4(),grantId:grant.grantId,expectedRevision:grant.revision}}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint2(parsed),phase:"PREPARED"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}import{z as z9}from"zod";import{join as join7}from"node:path";import{randomUUID as randomUUID5}from"node:crypto";var digest4=z9.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z9.strictObject({id:z9.uuid(),channel:z9.strictObject({protocol:z9.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z9.string().url(),publicKey:z9.string()}),release:LocalReleaseSchema,installationRevision:z9.int().nonnegative(),expiresAt:z9.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join7(home,"bootstrap-plans"));let intent2,fingerprint3;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join7(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent2=intentSchema.parse({id:randomUUID5(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint3=sha256(canonicalLocalJson(intent2));await write(join7(root,intent2.id+".json"),canonicalLocalJson({intent:intent2,fingerprint:fingerprint3}),true)}else{const saved=z9.strictObject({intent:intentSchema,fingerprint:digest4}).parse(JSON.parse((await read(join7(root,call.id+".json"),131072)).toString()));intent2=saved.intent;fingerprint3=saved.fingerprint;if(fingerprint3!==call.fingerprint||fingerprint3!==sha256(canonicalLocalJson(intent2))||intent2.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join7(root,intent2.id+".installation.json");const receipt=z9.strictObject({id:z9.uuid(),fingerprint:digest4}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent2.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent2.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent2.channel);await configureDesktopChannel(manager,trust.fingerprint,intent2.channel);const plan=await manager.prepare(intent2.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent2.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent2.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent2.id,fingerprint:fingerprint3,version:intent2.release.descriptor.version,host:new URL(intent2.channel.catalogueUrl).host,bytes:intent2.release.package.byteSize+Object.values(intent2.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent2.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat as lstat3,readFile,chmod as chmod2}from"node:fs/promises";import{join as join8,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat3(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod2(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join8(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join8(await directory(home),"nodes",expected)),target=join8(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join8(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,runDesktopOwnerRequest,runLocalManagement};
|
package/dist/local-navigation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalMcpTools}from"./_chunks/chunk-
|
|
1
|
+
import{LocalMcpTools}from"./_chunks/chunk-RNOIRNC3.js";import{DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-VDQOSVZY.js";import"./_chunks/chunk-JLOHTDP6.js";import"./_chunks/chunk-KB2GVAN7.js";import"./_chunks/chunk-PBEHCYR7.js";import"./_chunks/chunk-VPYAXWXY.js";import"./_chunks/chunk-6NVIN2NI.js";async function openDesktopDeviceTools(raw,home){const scope=DesktopDeviceScopeSchema.parse(raw);return LocalMcpTools.open(await desktopDeviceConnector(home,scope),home)}export{LocalMcpTools,openDesktopDeviceTools};
|
package/dist/native/JobNative.cs
CHANGED
|
@@ -104,6 +104,16 @@ namespace NativeStudio.Platform
|
|
|
104
104
|
}
|
|
105
105
|
catch { CloseHandle(job); throw; }
|
|
106
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
|
+
}
|
|
107
117
|
public static uint[] Processes(IntPtr job)
|
|
108
118
|
{
|
|
109
119
|
int size = 8 + 64 * IntPtr.Size;
|
package/dist/native/JobRunner.cs
CHANGED
|
@@ -15,6 +15,10 @@ namespace NativeStudio.Platform
|
|
|
15
15
|
static readonly object Sync = new object();
|
|
16
16
|
static readonly Dictionary<string, IntPtr> Jobs = new Dictionary<string, IntPtr>();
|
|
17
17
|
static readonly HashSet<string> Cancelled = new HashSet<string>();
|
|
18
|
+
static readonly Dictionary<string, double> Cpus = new Dictionary<string, double>();
|
|
19
|
+
static readonly Dictionary<string, ulong> Memories = new Dictionary<string, ulong>();
|
|
20
|
+
static readonly HashSet<string> Exceeded = new HashSet<string>();
|
|
21
|
+
static ulong memoryBudget = 4294967296UL;
|
|
18
22
|
static IntPtr aggregate;
|
|
19
23
|
static Process parent;
|
|
20
24
|
static bool closed;
|
|
@@ -40,8 +44,18 @@ namespace NativeStudio.Platform
|
|
|
40
44
|
{
|
|
41
45
|
Jobs.Remove(id);
|
|
42
46
|
Cancelled.Remove(id);
|
|
47
|
+
Exceeded.Remove(id);
|
|
48
|
+
Cpus.Remove(id);
|
|
49
|
+
Memories.Remove(id);
|
|
50
|
+
ApplyBudget();
|
|
43
51
|
}
|
|
44
52
|
}
|
|
53
|
+
static void ApplyBudget()
|
|
54
|
+
{
|
|
55
|
+
memoryBudget = Memories.Count == 0 ? 4294967296UL : Memories.Values.Min();
|
|
56
|
+
if (aggregate != IntPtr.Zero && !closed)
|
|
57
|
+
JobNative.Budget(aggregate, Cpus.Count == 0 ? 2 : Cpus.Values.Min(), memoryBudget);
|
|
58
|
+
}
|
|
45
59
|
public static void Cancel(string id)
|
|
46
60
|
{
|
|
47
61
|
lock (Sync)
|
|
@@ -105,10 +119,10 @@ namespace NativeStudio.Platform
|
|
|
105
119
|
}
|
|
106
120
|
catch (ArgumentException) { } // A command already exited.
|
|
107
121
|
}
|
|
108
|
-
if (rss >
|
|
122
|
+
if ((ulong)rss > memoryBudget)
|
|
109
123
|
{
|
|
110
|
-
|
|
111
|
-
|
|
124
|
+
foreach (var id in Cpus.Keys) Exceeded.Add(id);
|
|
125
|
+
JobNative.TerminateJobObject(aggregate, 1);
|
|
112
126
|
}
|
|
113
127
|
}
|
|
114
128
|
Thread.Sleep(100);
|
|
@@ -199,6 +213,11 @@ namespace NativeStudio.Platform
|
|
|
199
213
|
throw new Exception("INPUT_LIMIT");
|
|
200
214
|
int maximum = Convert.ToInt32(r["maxOutputBytes"]);
|
|
201
215
|
long expires = Convert.ToInt64(r["expiresAt"]);
|
|
216
|
+
var budget = r.ContainsKey("limits") ? (IDictionary<string, object>)r["limits"] : null;
|
|
217
|
+
double cpu = budget == null ? 2 : Convert.ToDouble(budget["cpuCores"]);
|
|
218
|
+
ulong memory = budget == null ? 4294967296UL : Convert.ToUInt64(budget["memoryBytes"]);
|
|
219
|
+
if (Double.IsNaN(cpu) || Double.IsInfinity(cpu) || cpu < 0.25 || cpu > 2 || memory < 1048576UL || memory > 4294967296UL)
|
|
220
|
+
throw new Exception("LIMIT");
|
|
202
221
|
if (maximum < 1 || maximum > 524288 || expires <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
|
203
222
|
throw new Exception("LIMIT");
|
|
204
223
|
string cwd = r.ContainsKey("cwd") && r["cwd"] != null ? PrivateAccess.PathOf(NativeMain.Text(r, "cwd")) : null;
|
|
@@ -209,6 +228,7 @@ namespace NativeStudio.Platform
|
|
|
209
228
|
try
|
|
210
229
|
{
|
|
211
230
|
var root = Aggregate();
|
|
231
|
+
lock (Sync) { Cpus[id] = cpu; Memories[id] = memory; ApplyBudget(); }
|
|
212
232
|
job = JobNative.Job(false);
|
|
213
233
|
ownedJob = new SafeFileHandle(job, true);
|
|
214
234
|
lock (Sync)
|
|
@@ -307,6 +327,7 @@ namespace NativeStudio.Platform
|
|
|
307
327
|
}
|
|
308
328
|
}
|
|
309
329
|
uint code;
|
|
330
|
+
lock (Sync) { if (Exceeded.Contains(id)) throw new Exception("RESOURCE_BUDGET_EXCEEDED"); }
|
|
310
331
|
if (!JobNative.GetExitCodeProcess(info.process, out code))
|
|
311
332
|
throw new Exception("EXIT");
|
|
312
333
|
JobNative.Kill(ownedJob); // Dispose every descendant even if it closed its streams.
|
|
@@ -7,6 +7,16 @@ namespace NativeStudio.Platform
|
|
|
7
7
|
{
|
|
8
8
|
public static class NativeMain
|
|
9
9
|
{
|
|
10
|
+
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
|
|
11
|
+
struct LastInput { public uint size; public uint tick; }
|
|
12
|
+
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
|
|
13
|
+
static extern bool GetLastInputInfo(ref LastInput input);
|
|
14
|
+
static int IdleSeconds()
|
|
15
|
+
{
|
|
16
|
+
var input = new LastInput { size = 8 };
|
|
17
|
+
if (!GetLastInputInfo(ref input)) throw new Exception("IDLE_UNAVAILABLE");
|
|
18
|
+
return (int)Math.Min(86400U, unchecked((uint)Environment.TickCount - input.tick) / 1000U);
|
|
19
|
+
}
|
|
10
20
|
static readonly object Output = new object();
|
|
11
21
|
public static readonly JavaScriptSerializer Json = new JavaScriptSerializer { MaxJsonLength = 2097152, RecursionLimit = 32 };
|
|
12
22
|
public static string Text(IDictionary<string, object> r, string key)
|
|
@@ -49,6 +59,11 @@ namespace NativeStudio.Platform
|
|
|
49
59
|
try
|
|
50
60
|
{
|
|
51
61
|
var operation = Text(r, "operation");
|
|
62
|
+
if (operation == "idle")
|
|
63
|
+
{
|
|
64
|
+
Send(new { id = id, ok = true, data = new { seconds = IdleSeconds() } });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
52
67
|
if (operation == "directory")
|
|
53
68
|
PrivateAccess.Directory(Text(r, "path"));
|
|
54
69
|
else if (operation == "check")
|