@nativestudio/cli 0.3.0-rc.1 → 0.3.0-rc.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMPATIBILITY.json +33 -8
- package/LICENSE +201 -21
- package/components/runtime.json +29 -4
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/chunk-37PAJCKA.js +1 -0
- package/dist/_chunks/{chunk-G42IS5JF.js → chunk-3AVC742O.js} +1 -1
- package/dist/_chunks/chunk-4U4Y2K73.js +1 -0
- package/dist/_chunks/chunk-65FQPXKC.js +1 -0
- package/dist/_chunks/chunk-6DVZBKNV.js +1 -0
- package/dist/_chunks/{chunk-25EDDZQA.js → chunk-6LU6GJKW.js} +1 -1
- package/dist/_chunks/chunk-6N433ZWR.js +1 -0
- package/dist/_chunks/chunk-EGUJ2YRX.js +1 -0
- package/dist/_chunks/{chunk-MSOMVWKN.js → chunk-FU3524Z6.js} +1 -1
- package/dist/_chunks/chunk-GZBWA4YN.js +1 -0
- package/dist/_chunks/chunk-HR34UMPP.js +1 -0
- package/dist/_chunks/chunk-HTUTYIRU.js +1 -0
- package/dist/_chunks/chunk-KB2GVAN7.js +1 -0
- package/dist/_chunks/chunk-L543FEDK.js +1 -0
- package/dist/_chunks/chunk-LISB5W7B.js +1 -0
- package/dist/_chunks/chunk-LUAH3KAS.js +1 -0
- package/dist/_chunks/chunk-M2KVQQ4X.js +1 -0
- package/dist/_chunks/chunk-ODGPV7MM.js +1 -0
- package/dist/_chunks/chunk-PUBMDP4E.js +1 -0
- package/dist/_chunks/chunk-Q57YFNK5.js +1 -0
- package/dist/_chunks/chunk-QAJH4RJQ.js +1 -0
- package/dist/_chunks/chunk-WFRRNWO5.js +1 -0
- package/dist/_chunks/connect-5YMO6MAR.js +1 -0
- package/dist/_chunks/device-management-2OTGEBJQ.js +1 -0
- package/dist/_chunks/device-preflight-XPHFZGLO.js +1 -0
- package/dist/_chunks/devices-inventory-VWNTU5TE.js +1 -0
- package/dist/_chunks/devices-main-VQ4APRVS.js +1 -0
- package/dist/_chunks/{files-TBJVDQWU.js → files-TTIQ7LYJ.js} +1 -1
- package/dist/_chunks/host-main-H7DPLV7B.js +1 -0
- package/dist/_chunks/http-profile-MNJX6OXO.js +1 -0
- package/dist/_chunks/library-main-SAC3V2ML.js +1 -0
- package/dist/_chunks/local-main-D6B3APK6.js +1 -0
- package/dist/_chunks/local-mcp-ONCANLPH.js +1 -0
- package/dist/_chunks/main-PW6HB3NC.js +2 -0
- package/dist/_chunks/mcp-ZIGBYFUW.js +1 -0
- package/dist/_chunks/oauth-HC6TI7HB.js +1 -0
- package/dist/_chunks/render-main-GYWKP72O.js +1 -0
- package/dist/_chunks/source-import-BC5GNCUZ.js +1 -0
- package/dist/_chunks/src-R6DNU336.js +1 -0
- package/dist/_chunks/{stdio-main-JEADWO7U.js → stdio-main-RIJS5REB.js} +1 -1
- package/dist/_chunks/workspace-main-GNSKHKBG.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +1969 -1
- package/dist/_types/cli/local/desktop-device-contract.d.ts +779 -0
- package/dist/_types/cli/local/desktop-device-navigation.d.ts +3 -0
- package/dist/_types/cli/local/desktop-device-owner.d.ts +244 -0
- package/dist/_types/cli/local/desktop-device-state.d.ts +397 -0
- package/dist/_types/cli/local/desktop-library.d.ts +853 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +735 -1
- package/dist/_types/cli/local/ledger.d.ts +64 -10
- package/dist/_types/cli/local/manager.d.ts +1146 -43
- package/dist/_types/cli/local/mcp-tools.d.ts +287 -46
- package/dist/_types/cli/local/releases.d.ts +28 -5
- package/dist/_types/cli/local-management.d.ts +5 -0
- package/dist/_types/cli/local-navigation.d.ts +1 -0
- package/dist/_types/contracts/artifact-discovery.d.ts +76 -4
- package/dist/_types/contracts/audio.d.ts +4 -0
- package/dist/_types/contracts/composition-authoring.d.ts +8 -8
- package/dist/_types/contracts/composition-frame-render.d.ts +4 -4
- package/dist/_types/contracts/composition-render-base.d.ts +5 -4
- package/dist/_types/contracts/composition-render.d.ts +8 -8
- package/dist/_types/contracts/composition-repair.d.ts +10 -10
- package/dist/_types/contracts/composition-source-review.d.ts +12 -12
- package/dist/_types/contracts/delivery-manifest.d.ts +25 -11729
- package/dist/_types/contracts/delivery-operations.d.ts +51 -3909
- package/dist/_types/contracts/delivery-summary.d.ts +2 -2
- package/dist/_types/contracts/delivery-validation.d.ts +23 -0
- package/dist/_types/contracts/device-render.d.ts +77 -0
- package/dist/_types/contracts/editor-intelligence.d.ts +114 -2491
- package/dist/_types/contracts/exploration-recommendation.d.ts +263 -11607
- package/dist/_types/contracts/external-agent-access.d.ts +4 -6
- package/dist/_types/contracts/final-ready.d.ts +22 -22
- package/dist/_types/contracts/final-render.d.ts +1569 -6940
- package/dist/_types/contracts/human-identity.d.ts +13 -0
- package/dist/_types/contracts/index.d.ts +4 -0
- package/dist/_types/contracts/interface/media-output.d.ts +28 -0
- package/dist/_types/contracts/interface/production-snapshot.d.ts +15 -193
- package/dist/_types/contracts/keyframe-generation.d.ts +29 -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 +496 -64
- package/dist/_types/contracts/local-execution/common.d.ts +12 -11
- package/dist/_types/contracts/local-execution/completion.d.ts +41 -45
- package/dist/_types/contracts/local-execution/components.d.ts +45 -0
- package/dist/_types/contracts/local-execution/descriptor.d.ts +38 -0
- package/dist/_types/contracts/local-execution/device-authority.d.ts +31 -0
- package/dist/_types/contracts/local-execution/device-inventory.d.ts +76 -0
- package/dist/_types/contracts/local-execution/device-workspace.d.ts +11 -0
- package/dist/_types/contracts/local-execution/device.d.ts +19 -51
- package/dist/_types/contracts/local-execution/external-generation.d.ts +199 -0
- package/dist/_types/contracts/local-execution/index.d.ts +26 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +2756 -228
- package/dist/_types/contracts/local-execution/library-command.d.ts +620 -0
- package/dist/_types/contracts/local-execution/library-result.d.ts +408 -0
- package/dist/_types/contracts/local-execution/library.d.ts +873 -0
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +242 -42
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +275 -56
- package/dist/_types/contracts/local-execution/management.d.ts +400 -0
- package/dist/_types/contracts/local-execution/media-recipe.d.ts +207 -0
- package/dist/_types/contracts/local-execution/media-validation-request.d.ts +232 -0
- package/dist/_types/contracts/local-execution/media-validation.d.ts +262 -0
- package/dist/_types/contracts/local-execution/object-transfer.d.ts +155 -0
- package/dist/_types/contracts/local-execution/offline.d.ts +59 -0
- package/dist/_types/contracts/local-execution/preview.d.ts +144 -3564
- package/dist/_types/contracts/local-execution/processor-capability.d.ts +39 -0
- package/dist/_types/contracts/local-execution/processor-direct.d.ts +290 -0
- package/dist/_types/contracts/local-execution/processor-recipes.d.ts +1122 -0
- package/dist/_types/contracts/local-execution/processor.d.ts +6173 -0
- package/dist/_types/contracts/local-execution/project-source-direct.d.ts +201 -0
- package/dist/_types/contracts/local-execution/qwen-tts.d.ts +31 -0
- package/dist/_types/contracts/local-execution/recognition.d.ts +170 -0
- package/dist/_types/contracts/local-execution/speech.d.ts +95 -0
- package/dist/_types/contracts/local-execution/tool-selection.d.ts +45 -5
- package/dist/_types/contracts/local-execution/whisper.d.ts +24 -0
- package/dist/_types/contracts/local-execution/work.d.ts +111 -3403
- package/dist/_types/contracts/local-execution/workspace.d.ts +141 -0
- package/dist/_types/contracts/media-category.d.ts +11 -0
- package/dist/_types/contracts/media-observation.d.ts +929 -8
- package/dist/_types/contracts/navigation.d.ts +25 -15
- package/dist/_types/contracts/observation-profile.d.ts +3 -3
- package/dist/_types/contracts/programmatic-composition.d.ts +24 -24
- package/dist/_types/contracts/programmatic-exploration.d.ts +348 -5985
- package/dist/_types/contracts/provider-catalog.d.ts +3 -3
- package/dist/_types/contracts/provider-models.d.ts +16 -8
- package/dist/_types/contracts/provider.d.ts +66 -1
- package/dist/_types/contracts/reference-preview.d.ts +19 -0
- package/dist/_types/contracts/repair-lifecycle.d.ts +52 -384
- package/dist/_types/contracts/repair-plan.d.ts +16 -98
- package/dist/_types/contracts/repair-strategy.d.ts +162 -4481
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +317 -8139
- package/dist/_types/contracts/review-intelligence.d.ts +450 -11420
- package/dist/_types/contracts/rough-cut-manifest.d.ts +8 -3
- package/dist/_types/contracts/rough-cut-profile.d.ts +12 -3
- package/dist/_types/contracts/rough-cut-review.d.ts +134 -12494
- package/dist/_types/contracts/rough-cut.d.ts +1073 -5675
- package/dist/_types/contracts/sound-making-plan.d.ts +3 -2
- package/dist/_types/contracts/speech-cost.d.ts +81 -0
- package/dist/_types/contracts/speech.d.ts +149 -0
- package/dist/_types/contracts/temporal-evidence-operation.d.ts +1 -0
- package/dist/_types/contracts/timeline-audio.d.ts +1 -0
- package/dist/_types/contracts/timeline-manifest.d.ts +2 -0
- package/dist/_types/contracts/timeline-source-sound.d.ts +1 -0
- package/dist/_types/contracts/timeline-v2.d.ts +4 -0
- package/dist/_types/contracts/timeline-version-reader.d.ts +10 -0
- package/dist/_types/contracts/timeline-visual-layers.d.ts +4 -0
- package/dist/_types/contracts/timeline.d.ts +50 -4850
- package/dist/_types/contracts/transcription.d.ts +1 -1
- package/dist/_types/contracts/video-generation.d.ts +33 -0
- package/dist/_types/contracts/visual-layer-render.d.ts +58 -15
- package/dist/_types/contracts/visual-sequence.d.ts +22 -0
- package/dist/_types/contracts/workspace.d.ts +32 -0
- package/dist/_types/sdk/errors.d.ts +8 -3
- package/dist/_types/sdk/local-runtime/components.d.ts +2 -0
- package/dist/_types/sdk/local-runtime/device-client.d.ts +127 -17
- package/dist/_types/sdk/local-runtime/library.d.ts +268 -0
- package/dist/_types/sdk/local-runtime/workspace.d.ts +186 -0
- package/dist/_types/sdk/local-runtime-client.d.ts +1773 -89
- 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 +2 -8
- package/README.md +0 -78
- package/dist/_chunks/chunk-6NVIN2NI.js +0 -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-GJ7BZJLW.js +0 -1
- package/dist/_chunks/chunk-HLKERZIE.js +0 -1
- package/dist/_chunks/chunk-QC7RLTGU.js +0 -1
- package/dist/_chunks/chunk-RUMDDTON.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/main-4SNF5EKE.js +0 -2
- 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]==="host"){const{runHostCli}=await import("./_chunks/host-main-H7DPLV7B.js");const result=await runHostCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}else if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-ONCANLPH.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-D6B3APK6.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-RIJS5REB.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-PW6HB3NC.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{DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia,runDesktopLibraryRequest}from"./_chunks/chunk-4U4Y2K73.js";import{desktopDevicePending,runDesktopDeviceRequest}from"./_chunks/chunk-LUAH3KAS.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./_chunks/chunk-65FQPXKC.js";import"./_chunks/chunk-LISB5W7B.js";import{LocalInstallationManager,captureInstalledTools,ownerClient,socketAbsent,toolPreference,waitStopped}from"./_chunks/chunk-WFRRNWO5.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-EGUJ2YRX.js";import{catalogue,endpoint,newerVersion}from"./_chunks/chunk-HR34UMPP.js";import{LocalClientError,atomicMove,directory,entries,fail,optional,read,sha256,write}from"./_chunks/chunk-KB2GVAN7.js";import{LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema,canonicalLocalJson}from"./_chunks/chunk-GZBWA4YN.js";import"./_chunks/chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./_chunks/chunk-HTUTYIRU.js";import{z as z7}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 digest4=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!==digest4||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest4}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest4=record.digest}return{plan,digest:digest4}}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 z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,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","library"].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}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});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,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(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:join3(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(join3(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(join3(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(join3(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!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(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 z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.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||!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 z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(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=join4(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=join4(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 z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.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=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,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 join5}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();if(!config.catalogueUrl||!config.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");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&&["CONFIGURATION_REQUIRED","DEPENDENCY_CHANNEL_REQUIRED"].includes(error.code)))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;let existing;try{existing=await manager.configuration()}catch(e){if(!(e instanceof LocalClientError&&e.code==="CONFIGURATION_REQUIRED"))throw e}const stateDirectory=existing?.stateDirectory??join5(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join5(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join5(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({...existing,stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:!existing})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}import{z as z8}from"zod";import{join as join6}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";var digest3=z8.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z8.strictObject({id:z8.uuid(),channel:z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z8.string().url(),publicKey:z8.string()}),release:LocalReleaseSchema,installationRevision:z8.int().nonnegative(),expiresAt:z8.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join6(home,"bootstrap-plans"));let intent2,fingerprint2;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;if(configuration&&!configuration.publicKeyFile)fail("DESKTOP_CHANNEL_CHANGED");const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join6(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:randomUUID2(),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()});fingerprint2=sha256(canonicalLocalJson(intent2));await write(join6(root,intent2.id+".json"),canonicalLocalJson({intent:intent2,fingerprint:fingerprint2}),true)}else{const saved=z8.strictObject({intent:intentSchema,fingerprint:digest3}).parse(JSON.parse((await read(join6(root,call.id+".json"),131072)).toString()));intent2=saved.intent;fingerprint2=saved.fingerprint;if(fingerprint2!==call.fingerprint||fingerprint2!==sha256(canonicalLocalJson(intent2))||intent2.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join6(root,intent2.id+".installation.json");const receipt=z8.strictObject({id:z8.uuid(),fingerprint:digest3}).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:fingerprint2,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"library":result=await runDesktopLibraryRequest(home,request);break;case"library-import":result=await runDesktopLibraryImport(home,request);break;case"library-import-prepare":result=await prepareDesktopLibraryImport(request);break;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 join7,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(join7(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join7(await directory(home),"nodes",expected)),target=join7(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join7(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,DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,prepareDesktopLibraryImport,runDesktopLibraryMedia,runDesktopOwnerRequest,runLocalManagement};
|
package/dist/local-navigation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalMcpTools}from"./_chunks/chunk-
|
|
1
|
+
import{LocalMcpTools}from"./_chunks/chunk-ODGPV7MM.js";import{DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-EGUJ2YRX.js";import"./_chunks/chunk-HR34UMPP.js";import"./_chunks/chunk-KB2GVAN7.js";import"./_chunks/chunk-GZBWA4YN.js";import"./_chunks/chunk-VPYAXWXY.js";import"./_chunks/chunk-HTUTYIRU.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")
|
package/package.json
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nativestudio/cli",
|
|
3
|
-
"version": "0.3.0-rc.
|
|
3
|
+
"version": "0.3.0-rc.11",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"license": "
|
|
6
|
-
"description": "NativeStudio account-first Agent CLI, MCP relay and local execution manager",
|
|
5
|
+
"license": "Apache-2.0",
|
|
7
6
|
"engines": {
|
|
8
7
|
"node": ">=24.12 <25"
|
|
9
8
|
},
|
|
@@ -27,10 +26,5 @@
|
|
|
27
26
|
},
|
|
28
27
|
"publishConfig": {
|
|
29
28
|
"access": "public"
|
|
30
|
-
},
|
|
31
|
-
"repository": {
|
|
32
|
-
"type": "git",
|
|
33
|
-
"url": "git+https://github.com/SENLIN746/native-video-studio.git",
|
|
34
|
-
"directory": "apps/remote-cli"
|
|
35
29
|
}
|
|
36
30
|
}
|
package/README.md
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
# NativeStudio CLI
|
|
2
|
-
|
|
3
|
-
One Agent/terminal entry for account login, project navigation, remote stdio MCP
|
|
4
|
-
and explicitly authorized local execution. Node.js 24.12 or later in major24 is
|
|
5
|
-
required. Preview releases use the `next` channel; pin the exact verified version
|
|
6
|
-
shown on the NativeStudio download page. Install `@nativestudio/cli` or run that exact
|
|
7
|
-
version through npx. Local qualification uses the inspected tarball. No separate contracts, SDK or Runtime package is required.
|
|
8
|
-
Cloud Agents supporting remote HTTP MCP can connect without installing npm packages.
|
|
9
|
-
|
|
10
|
-
Use a currently patched Node24 release. The engine floor is API compatibility,
|
|
11
|
-
not a recommendation to run an old security patch.
|
|
12
|
-
|
|
13
|
-
## Sign in, choose scope, connect
|
|
14
|
-
|
|
15
|
-
```sh
|
|
16
|
-
nvs login --server https://studio.example.com
|
|
17
|
-
nvs whoami
|
|
18
|
-
nvs workspaces
|
|
19
|
-
nvs workspace --id WORKSPACE_ID_FROM_RESPONSE
|
|
20
|
-
nvs projects
|
|
21
|
-
nvs project --id PROJECT_ID_FROM_RESPONSE
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
Login opens the browser; the terminal never asks for your password. The server must
|
|
25
|
-
support NativeStudio account handoff. Registration/reset additionally requires its
|
|
26
|
-
configured email service. Account sessions expire; an unavailable server capability
|
|
27
|
-
is not bypassed by this package. Account login is separate from Project Agent consent.
|
|
28
|
-
|
|
29
|
-
Open the returned `connectionPage` and copy its verified MCP connection URL:
|
|
30
|
-
|
|
31
|
-
```sh
|
|
32
|
-
nvs connect --mcp-url PROJECT_CONNECTION_URL_FROM_SETTINGS
|
|
33
|
-
nvs status
|
|
34
|
-
nvs find --query "查找我的制作"
|
|
35
|
-
nvs capabilities search --query "找参考素材" --group materials
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
Project access is read-only by default. Request `--scope 'nvs:read nvs:write'` only
|
|
39
|
-
when needed and explicitly approve the browser consent. Follow native nextActions;
|
|
40
|
-
a recommendation is not execution or acceptance. Existing expert `operations` and
|
|
41
|
-
`call` commands remain available; authorization, revisions and idempotency still apply.
|
|
42
|
-
|
|
43
|
-
Configure the Agent executable as `nvs`, arguments `["mcp"]`. Use the same OS user
|
|
44
|
-
and private client home. Restart its MCP process after updating CLI or selecting a
|
|
45
|
-
new connection. Tokens, passwords, database settings and Provider keys do not belong
|
|
46
|
-
in Agent launch arguments/configuration. `nvs logout` revokes the CLI account session,
|
|
47
|
-
not independent Agent grants or native Jobs. Revoke Project grants in Web Settings.
|
|
48
|
-
|
|
49
|
-
## Local execution and updates
|
|
50
|
-
|
|
51
|
-
`nvs local` provides installation status, explicit configuration, checks, planning,
|
|
52
|
-
apply and recovery. The embedded Runtime is only a code asset cache: its exact bytes
|
|
53
|
-
must match a current catalogue signed by the configured trusted key before use.
|
|
54
|
-
Missing production channel/tool metadata remains unavailable. There is no self-signed
|
|
55
|
-
bootstrap, implicit PATH discovery or activation merely because npm installed code.
|
|
56
|
-
|
|
57
|
-
Check first, inspect the exact plan, then approve that plan's fingerprint. Existing
|
|
58
|
-
Runtime state, SQLite recovery data, pending results and previous working slots stay
|
|
59
|
-
outside npm/npx directories. Updating CLI does not automatically upgrade the daemon.
|
|
60
|
-
External managed media tools use their own signed integrity channel; selecting an
|
|
61
|
-
installed tool is explicit. Platform support depends on the signed catalogue and
|
|
62
|
-
qualification evidence; packaging alone does not certify Windows/Apple Silicon QA.
|
|
63
|
-
|
|
64
|
-
## Recovery and private state
|
|
65
|
-
|
|
66
|
-
Private credentials, connection epochs and receipts live outside the package under
|
|
67
|
-
`~/.nativestudio/client` (or an explicit private `NATIVESTUDIO_CLIENT_HOME`). Failed
|
|
68
|
-
login preserves the prior account/connection. An unresolved token exchange is fenced;
|
|
69
|
-
start a fresh login/connection rather than replay the exchange. UNKNOWN business writes
|
|
70
|
-
must be reconciled through their native Operation or supported explicit idempotency.
|
|
71
|
-
Neither a process timeout nor MCP cancellation cancels an admitted Job automatically.
|
|
72
|
-
|
|
73
|
-
The implementation remains readable under MIT. Packages exclude source maps,
|
|
74
|
-
build-machine paths, raw TypeScript, private credentials and local state. Fixed
|
|
75
|
-
Windows C#/PowerShell helper resources are intentional scoped execution assets.
|
|
76
|
-
`COMPATIBILITY.json` records protocol and component identities. The local navigation
|
|
77
|
-
and management export subpaths are experimental host integrations, not general Agent
|
|
78
|
-
permission to control installation or execute shell commands.
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var NativeStudioSdkError=class extends Error{constructor(code,semanticStatus,outcome,status=null){super(`NativeStudio ${code}`);this.code=code;this.semanticStatus=semanticStatus;this.outcome=outcome;this.status=status;this.name="NativeStudioSdkError"}code;semanticStatus;outcome;status};function sdkInputError(){throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE")}export{NativeStudioSdkError,sdkInputError};
|