@nativestudio/cli 0.0.0-stage → 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 +45 -0
- package/LICENSE +201 -0
- package/components/runtime.json +31 -0
- package/components/runtime.tgz +0 -0
- package/dist/BUNDLED_DEPENDENCIES.json +1 -0
- package/dist/_chunks/chunk-2UYKJ6YN.js +1 -0
- package/dist/_chunks/chunk-37PAJCKA.js +1 -0
- package/dist/_chunks/chunk-3AVC742O.js +1 -0
- 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-6LU6GJKW.js +1 -0
- package/dist/_chunks/chunk-6N433ZWR.js +1 -0
- package/dist/_chunks/chunk-EGUJ2YRX.js +1 -0
- package/dist/_chunks/chunk-FU3524Z6.js +1 -0
- 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-JFC6ZIGA.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-PUNG4ND7.js +1 -0
- package/dist/_chunks/chunk-Q57YFNK5.js +1 -0
- package/dist/_chunks/chunk-QAJH4RJQ.js +1 -0
- package/dist/_chunks/chunk-VDNNFVTZ.js +3 -0
- package/dist/_chunks/chunk-VPYAXWXY.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-TTIQ7LYJ.js +1 -0
- 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-RIJS5REB.js +1 -0
- package/dist/_chunks/workspace-main-GNSKHKBG.js +1 -0
- package/dist/_types/cli/local/desktop-channel.d.ts +18 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +2176 -0
- 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-node.d.ts +1 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +766 -0
- package/dist/_types/cli/local/ledger.d.ts +363 -0
- package/dist/_types/cli/local/manager.d.ts +1695 -0
- package/dist/_types/cli/local/mcp-tools.d.ts +660 -0
- package/dist/_types/cli/local/releases.d.ts +123 -0
- package/dist/_types/cli/local-management.d.ts +16 -0
- package/dist/_types/cli/local-navigation.d.ts +4 -0
- package/dist/_types/contracts/accepted-shot.d.ts +27 -0
- package/dist/_types/contracts/accepted-visual-source.d.ts +120 -0
- package/dist/_types/contracts/agent-execution-lifecycle.d.ts +749 -0
- package/dist/_types/contracts/agent-execution-oauth.d.ts +71 -0
- package/dist/_types/contracts/agent-execution-registration.d.ts +240 -0
- package/dist/_types/contracts/agent-execution-selection.d.ts +107 -0
- package/dist/_types/contracts/agent-host-execution.d.ts +706 -0
- package/dist/_types/contracts/agent-host-generic-transport.d.ts +12 -0
- package/dist/_types/contracts/agent-host.d.ts +226 -0
- package/dist/_types/contracts/artifact-discovery.d.ts +242 -0
- package/dist/_types/contracts/artifact.d.ts +188 -0
- package/dist/_types/contracts/audio.d.ts +335 -0
- package/dist/_types/contracts/brief.d.ts +178 -0
- package/dist/_types/contracts/caption-render.d.ts +20 -0
- package/dist/_types/contracts/caption-transcript.d.ts +102 -0
- package/dist/_types/contracts/captions.d.ts +420 -0
- package/dist/_types/contracts/clip-framing.d.ts +14 -0
- package/dist/_types/contracts/clip-transition.d.ts +6 -0
- package/dist/_types/contracts/composition-authoring-guide.d.ts +160 -0
- package/dist/_types/contracts/composition-authoring.d.ts +744 -0
- package/dist/_types/contracts/composition-finding-locality.d.ts +24 -0
- package/dist/_types/contracts/composition-frame-render.d.ts +226 -0
- package/dist/_types/contracts/composition-making.d.ts +390 -0
- package/dist/_types/contracts/composition-observation.d.ts +239 -0
- package/dist/_types/contracts/composition-render-base.d.ts +293 -0
- package/dist/_types/contracts/composition-render-observation.d.ts +278 -0
- package/dist/_types/contracts/composition-render.d.ts +406 -0
- package/dist/_types/contracts/composition-repair.d.ts +451 -0
- package/dist/_types/contracts/composition-source-review.d.ts +1042 -0
- package/dist/_types/contracts/consistency-profile.d.ts +845 -0
- package/dist/_types/contracts/continuity-evaluation.d.ts +48 -0
- package/dist/_types/contracts/delivery-completion.d.ts +210 -0
- package/dist/_types/contracts/delivery-manifest.d.ts +72 -0
- package/dist/_types/contracts/delivery-operations.d.ts +1151 -0
- package/dist/_types/contracts/delivery-output-profile.d.ts +12 -0
- package/dist/_types/contracts/delivery-summary.d.ts +220 -0
- package/dist/_types/contracts/delivery-validation.d.ts +206 -0
- package/dist/_types/contracts/device-render.d.ts +77 -0
- package/dist/_types/contracts/director-proposal.d.ts +1067 -0
- package/dist/_types/contracts/editor-intelligence.d.ts +3374 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +519 -0
- package/dist/_types/contracts/external-agent-access.d.ts +93 -0
- package/dist/_types/contracts/final-ready.d.ts +301 -0
- package/dist/_types/contracts/final-render-profile.d.ts +59 -0
- package/dist/_types/contracts/final-render.d.ts +2810 -0
- package/dist/_types/contracts/foundation.d.ts +1 -0
- package/dist/_types/contracts/generation-contract.d.ts +268 -0
- package/dist/_types/contracts/generation-cost.d.ts +70 -0
- package/dist/_types/contracts/health.d.ts +6 -0
- package/dist/_types/contracts/human-identity.d.ts +162 -0
- package/dist/_types/contracts/hyperframe-profile.d.ts +5 -0
- package/dist/_types/contracts/ids.d.ts +41 -0
- package/dist/_types/contracts/index.d.ts +126 -0
- package/dist/_types/contracts/interface/common.d.ts +56 -0
- package/dist/_types/contracts/interface/execution-output.d.ts +99 -0
- package/dist/_types/contracts/interface/index.d.ts +7 -0
- package/dist/_types/contracts/interface/media-output.d.ts +90 -0
- package/dist/_types/contracts/interface/operation.d.ts +61 -0
- package/dist/_types/contracts/interface/output.d.ts +15 -0
- package/dist/_types/contracts/interface/production-snapshot.d.ts +654 -0
- package/dist/_types/contracts/interface/query.d.ts +315 -0
- package/dist/_types/contracts/keyframe-generation.d.ts +378 -0
- package/dist/_types/contracts/keyframe-reference.d.ts +31 -0
- package/dist/_types/contracts/keyframe-review.d.ts +753 -0
- package/dist/_types/contracts/lifecycle-event-projections.d.ts +191 -0
- package/dist/_types/contracts/lifecycle-events.d.ts +156 -0
- package/dist/_types/contracts/listening-evidence.d.ts +37 -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 +992 -0
- package/dist/_types/contracts/local-execution/canonical.d.ts +2 -0
- package/dist/_types/contracts/local-execution/common.d.ts +49 -0
- package/dist/_types/contracts/local-execution/completion.d.ts +124 -0
- 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 +102 -0
- package/dist/_types/contracts/local-execution/external-generation.d.ts +199 -0
- package/dist/_types/contracts/local-execution/index.d.ts +37 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +3730 -0
- 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 +519 -0
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +929 -0
- 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 +243 -0
- 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 +55 -0
- package/dist/_types/contracts/local-execution/whisper.d.ts +24 -0
- package/dist/_types/contracts/local-execution/work.d.ts +149 -0
- package/dist/_types/contracts/local-execution/workspace.d.ts +141 -0
- package/dist/_types/contracts/matrix-parameter-rule.d.ts +23 -0
- package/dist/_types/contracts/media-category.d.ts +11 -0
- package/dist/_types/contracts/media-export.d.ts +23 -0
- package/dist/_types/contracts/media-observation.d.ts +2080 -0
- package/dist/_types/contracts/model-capability-matrix.d.ts +118 -0
- package/dist/_types/contracts/native-tool-authority-failure.d.ts +38 -0
- package/dist/_types/contracts/native-tool-authority.d.ts +110 -0
- package/dist/_types/contracts/native-tool-execution.d.ts +287 -0
- package/dist/_types/contracts/native-tool-gateway.d.ts +41 -0
- package/dist/_types/contracts/native-video-audio.d.ts +62 -0
- package/dist/_types/contracts/navigation-context.d.ts +253 -0
- package/dist/_types/contracts/navigation-groups.d.ts +51 -0
- package/dist/_types/contracts/navigation.d.ts +248 -0
- package/dist/_types/contracts/observation-profile.d.ts +99 -0
- package/dist/_types/contracts/planning-input.d.ts +177 -0
- package/dist/_types/contracts/principal.d.ts +26 -0
- package/dist/_types/contracts/production-creation.d.ts +66 -0
- package/dist/_types/contracts/production-termination.d.ts +51 -0
- package/dist/_types/contracts/production.d.ts +111 -0
- package/dist/_types/contracts/programmatic-composition.d.ts +762 -0
- package/dist/_types/contracts/programmatic-exploration.d.ts +1822 -0
- package/dist/_types/contracts/programmatic-video-review.d.ts +894 -0
- package/dist/_types/contracts/project-library.d.ts +173 -0
- package/dist/_types/contracts/project.d.ts +93 -0
- package/dist/_types/contracts/provider-catalog.d.ts +421 -0
- package/dist/_types/contracts/provider-models.d.ts +3388 -0
- package/dist/_types/contracts/provider.d.ts +207 -0
- package/dist/_types/contracts/reference-preview.d.ts +55 -0
- package/dist/_types/contracts/repair-lifecycle.d.ts +2564 -0
- package/dist/_types/contracts/repair-plan.d.ts +646 -0
- package/dist/_types/contracts/repair-strategy.d.ts +1432 -0
- package/dist/_types/contracts/review-intelligence-evidence.d.ts +136 -0
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +883 -0
- package/dist/_types/contracts/review-intelligence.d.ts +573 -0
- package/dist/_types/contracts/review1-repair-source.d.ts +452 -0
- package/dist/_types/contracts/review1-repair-strategy.d.ts +491 -0
- package/dist/_types/contracts/review1-repair.d.ts +36 -0
- package/dist/_types/contracts/rough-cut-manifest.d.ts +352 -0
- package/dist/_types/contracts/rough-cut-profile.d.ts +46 -0
- package/dist/_types/contracts/rough-cut-review.d.ts +459 -0
- package/dist/_types/contracts/rough-cut.d.ts +1260 -0
- package/dist/_types/contracts/scene-shot-plan.d.ts +882 -0
- package/dist/_types/contracts/sdk-discovery.d.ts +66 -0
- package/dist/_types/contracts/shot-direction.d.ts +113 -0
- package/dist/_types/contracts/shot-preparation-basis.d.ts +356 -0
- package/dist/_types/contracts/shot-preparation.d.ts +2285 -0
- package/dist/_types/contracts/shot-sound-instruction.d.ts +58 -0
- package/dist/_types/contracts/sound-making-plan.d.ts +1586 -0
- package/dist/_types/contracts/source-sound-policy.d.ts +10 -0
- package/dist/_types/contracts/source-workspace.d.ts +62 -0
- package/dist/_types/contracts/speech-cost.d.ts +81 -0
- package/dist/_types/contracts/speech.d.ts +573 -0
- package/dist/_types/contracts/story.d.ts +98 -0
- package/dist/_types/contracts/temporal-evidence-operation.d.ts +380 -0
- package/dist/_types/contracts/temporal-evidence-reference.d.ts +18 -0
- package/dist/_types/contracts/temporal-evidence.d.ts +248 -0
- package/dist/_types/contracts/tenant.d.ts +7 -0
- package/dist/_types/contracts/timeline-audio.d.ts +98 -0
- package/dist/_types/contracts/timeline-graphics.d.ts +80 -0
- package/dist/_types/contracts/timeline-manifest.d.ts +704 -0
- package/dist/_types/contracts/timeline-source-sound.d.ts +353 -0
- package/dist/_types/contracts/timeline-v2.d.ts +1267 -0
- package/dist/_types/contracts/timeline-version-reader.d.ts +2955 -0
- package/dist/_types/contracts/timeline-visual-layers.d.ts +1249 -0
- package/dist/_types/contracts/timeline.d.ts +142 -0
- package/dist/_types/contracts/transcription.d.ts +80 -0
- package/dist/_types/contracts/video-generation.d.ts +676 -0
- package/dist/_types/contracts/video-review.d.ts +1871 -0
- package/dist/_types/contracts/visual-exploration.d.ts +1586 -0
- package/dist/_types/contracts/visual-layer-render.d.ts +2820 -0
- package/dist/_types/contracts/visual-layer.d.ts +112 -0
- package/dist/_types/contracts/visual-sequence.d.ts +143 -0
- package/dist/_types/contracts/workspace.d.ts +32 -0
- package/dist/_types/contracts/writer-proposal.d.ts +268 -0
- package/dist/_types/sdk/errors.d.ts +14 -0
- package/dist/_types/sdk/local-runtime/components.d.ts +2 -0
- package/dist/_types/sdk/local-runtime/device-client.d.ts +187 -0
- 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 +2616 -0
- package/dist/entry.js +2 -0
- package/dist/local-management.d.ts +1 -0
- package/dist/local-management.js +1 -0
- package/dist/local-navigation.d.ts +1 -0
- package/dist/local-navigation.js +1 -0
- package/dist/native/Bootstrap.ps1 +90 -0
- package/dist/native/JobNative.cs +137 -0
- package/dist/native/JobRunner.cs +381 -0
- package/dist/native/NativeMain.cs +161 -0
- package/dist/native/PipeBridge.cs +260 -0
- package/dist/native/PrivateAccess.cs +152 -0
- package/package.json +27 -3
- package/README.md +0 -3
package/dist/entry.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
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}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./_types/cli/local-management.js";
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./_types/cli/local-navigation.js";
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
$ErrorActionPreference = 'Stop'
|
|
2
|
+
[Console]::InputEncoding = New-Object Text.UTF8Encoding($false)
|
|
3
|
+
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
|
4
|
+
try {
|
|
5
|
+
$raw = [Console]::In.ReadToEnd()
|
|
6
|
+
if ($raw.Length -gt 32768) { throw 'INPUT_LIMIT' }
|
|
7
|
+
$request = $raw | ConvertFrom-Json
|
|
8
|
+
$names = @('Bootstrap.ps1','NativeMain.cs','PrivateAccess.cs','PipeBridge.cs','JobNative.cs','JobRunner.cs')
|
|
9
|
+
$directory = [IO.Path]::GetFullPath($request.directory)
|
|
10
|
+
$hash = [Security.Cryptography.SHA256]::Create()
|
|
11
|
+
foreach ($name in $names) {
|
|
12
|
+
$file = Join-Path $directory $name
|
|
13
|
+
if (([IO.File]::GetAttributes($file) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'REPARSE' }
|
|
14
|
+
$prefix = [Text.Encoding]::UTF8.GetBytes($name + "`n")
|
|
15
|
+
[void]$hash.TransformBlock($prefix,0,$prefix.Length,$prefix,0)
|
|
16
|
+
$bytes = [IO.File]::ReadAllBytes($file)
|
|
17
|
+
if ($bytes.Length -gt 262144) { throw 'SOURCE_LIMIT' }
|
|
18
|
+
[void]$hash.TransformBlock($bytes,0,$bytes.Length,$bytes,0)
|
|
19
|
+
}
|
|
20
|
+
[void]$hash.TransformFinalBlock([byte[]]@(),0,0)
|
|
21
|
+
$digest = ([BitConverter]::ToString($hash.Hash)).Replace('-','').ToLowerInvariant()
|
|
22
|
+
if ($digest -ne $request.sourceDigest) { throw 'SOURCE_CHANGED' }
|
|
23
|
+
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
24
|
+
function Check-Private([string]$path) {
|
|
25
|
+
$item = Get-Item -LiteralPath $path -Force
|
|
26
|
+
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'REPARSE' }
|
|
27
|
+
$acl = $item.GetAccessControl()
|
|
28
|
+
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'OWNER' }
|
|
29
|
+
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
|
|
30
|
+
if ($rule.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and
|
|
31
|
+
$rule.IdentityReference.Value -notin @($sid.Value,'S-1-5-18','S-1-5-32-544')) { throw 'ACL' }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function Private-Directory([string]$path) {
|
|
35
|
+
if ([IO.Directory]::Exists($path)) { Check-Private $path; return }
|
|
36
|
+
$acl = New-Object Security.AccessControl.DirectorySecurity
|
|
37
|
+
$acl.SetOwner($sid)
|
|
38
|
+
$acl.SetAccessRuleProtection($true,$false)
|
|
39
|
+
$rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow')
|
|
40
|
+
$acl.AddAccessRule($rule)
|
|
41
|
+
[void][IO.Directory]::CreateDirectory($path,$acl)
|
|
42
|
+
Check-Private $path
|
|
43
|
+
}
|
|
44
|
+
$base = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'NativeStudio-platform'
|
|
45
|
+
Private-Directory $base
|
|
46
|
+
$cache = Join-Path $base $digest
|
|
47
|
+
Private-Directory $cache
|
|
48
|
+
$mutex = New-Object Threading.Mutex($false,('Local\NVS-compile-' + $sid.Value + '-' + $digest))
|
|
49
|
+
$locked = $false
|
|
50
|
+
try {
|
|
51
|
+
try { $locked = $mutex.WaitOne(10000) } catch [Threading.AbandonedMutexException] { $locked = $true }
|
|
52
|
+
if (-not $locked) { throw 'BUSY' }
|
|
53
|
+
$record = Join-Path $cache 'helper.json'
|
|
54
|
+
if ([IO.File]::Exists($record)) {
|
|
55
|
+
Check-Private $record
|
|
56
|
+
$value = [IO.File]::ReadAllText($record) | ConvertFrom-Json
|
|
57
|
+
if ($value.sourceDigest -ne $digest -or $value.file -notmatch '^helper-[0-9a-f-]{36}\.exe$') { throw 'CACHE' }
|
|
58
|
+
$executable = Join-Path $cache $value.file
|
|
59
|
+
Check-Private $executable
|
|
60
|
+
$actual = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
61
|
+
if ($actual -ne $value.sha256) { throw 'CACHE_CHANGED' }
|
|
62
|
+
} else {
|
|
63
|
+
$file = 'helper-' + [Guid]::NewGuid().ToString() + '.exe'
|
|
64
|
+
$executable = Join-Path $cache $file
|
|
65
|
+
$sources = @($names | Where-Object { $_.EndsWith('.cs') } | ForEach-Object { Join-Path $directory $_ })
|
|
66
|
+
$compiler = New-Object CodeDom.Compiler.CompilerParameters
|
|
67
|
+
$compiler.GenerateExecutable = $true
|
|
68
|
+
$compiler.OutputAssembly = $executable
|
|
69
|
+
$compiler.CompilerOptions = '/platform:x64 /optimize+ /langversion:5'
|
|
70
|
+
$compiler.ReferencedAssemblies.AddRange(@('System.dll','System.Core.dll','System.Web.dll','System.Web.Extensions.dll','System.Security.dll'))
|
|
71
|
+
Add-Type -Path $sources -CompilerParameters $compiler
|
|
72
|
+
Check-Private $executable
|
|
73
|
+
$actual = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
74
|
+
$value = @{ sourceDigest=$digest; file=$file; sha256=$actual }
|
|
75
|
+
$temporary = Join-Path $cache ([Guid]::NewGuid().ToString() + '.json')
|
|
76
|
+
$bytes = [Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Compress))
|
|
77
|
+
$stream = New-Object IO.FileStream($temporary,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
|
|
78
|
+
try { $stream.Write($bytes,0,$bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() }
|
|
79
|
+
[IO.File]::Move($temporary,$record)
|
|
80
|
+
Check-Private $record
|
|
81
|
+
}
|
|
82
|
+
@{ path=$executable; sha256=$actual; sourceDigest=$digest } | ConvertTo-Json -Compress
|
|
83
|
+
} finally {
|
|
84
|
+
if ($locked) { $mutex.ReleaseMutex() }
|
|
85
|
+
$mutex.Dispose()
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
[Console]::Error.WriteLine('WINDOWS_HELPER_UNAVAILABLE')
|
|
89
|
+
exit 1
|
|
90
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
using System;
|
|
2
|
+
using System.Runtime.InteropServices;
|
|
3
|
+
using System.Text;
|
|
4
|
+
using Microsoft.Win32.SafeHandles;
|
|
5
|
+
namespace NativeStudio.Platform
|
|
6
|
+
{
|
|
7
|
+
public static class JobNative
|
|
8
|
+
{
|
|
9
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
10
|
+
public struct SecurityAttributes
|
|
11
|
+
{
|
|
12
|
+
public int size; public IntPtr descriptor; public int inherit;
|
|
13
|
+
}
|
|
14
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
15
|
+
public struct StartupInfo
|
|
16
|
+
{
|
|
17
|
+
public int size; public string reserved, desktop, title;
|
|
18
|
+
public uint x, y, xSize, ySize, xChars, yChars, fill, flags; public ushort show, reservedSize;
|
|
19
|
+
public IntPtr reservedBytes, input, output, error;
|
|
20
|
+
}
|
|
21
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
22
|
+
public struct ProcessInfo
|
|
23
|
+
{
|
|
24
|
+
public IntPtr process, thread; public uint processId, threadId;
|
|
25
|
+
}
|
|
26
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
27
|
+
public struct BasicLimits
|
|
28
|
+
{
|
|
29
|
+
public long processTime, jobTime; public uint flags; public UIntPtr minWorking, maxWorking;
|
|
30
|
+
public uint active; public UIntPtr affinity; public uint priority, scheduling;
|
|
31
|
+
}
|
|
32
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
33
|
+
public struct Counters
|
|
34
|
+
{
|
|
35
|
+
public ulong readOps, writeOps, otherOps, readBytes, writeBytes, otherBytes;
|
|
36
|
+
}
|
|
37
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
38
|
+
public struct ExtendedLimits
|
|
39
|
+
{
|
|
40
|
+
public BasicLimits basic; public Counters io; public UIntPtr processMemory, jobMemory, peakProcess, peakJob;
|
|
41
|
+
}
|
|
42
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
43
|
+
public struct CpuLimits
|
|
44
|
+
{
|
|
45
|
+
public uint flags, rate;
|
|
46
|
+
}
|
|
47
|
+
[DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr CreateJobObject(IntPtr sa, string name);
|
|
48
|
+
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr job, int type, IntPtr value, uint size);
|
|
49
|
+
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool QueryInformationJobObject(IntPtr job, int type, IntPtr value, uint size, out uint length);
|
|
50
|
+
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
51
|
+
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateJobObject(IntPtr job, uint code);
|
|
52
|
+
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateProcess(IntPtr process, uint code);
|
|
53
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CreateProcess(string application, StringBuilder command, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr environment, string directory, ref StartupInfo startup, out ProcessInfo info);
|
|
54
|
+
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool CreatePipe(out IntPtr read, out IntPtr write, ref SecurityAttributes sa, uint size);
|
|
55
|
+
[DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetHandleInformation(IntPtr handle, uint mask, uint flags);
|
|
56
|
+
[DllImport("kernel32.dll")] public static extern uint ResumeThread(IntPtr thread);
|
|
57
|
+
[DllImport("kernel32.dll")] public static extern uint WaitForSingleObject(IntPtr handle, uint ms);
|
|
58
|
+
[DllImport("kernel32.dll")] public static extern bool GetExitCodeProcess(IntPtr process, out uint code);
|
|
59
|
+
[DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr handle);
|
|
60
|
+
[DllImport("kernel32.dll", EntryPoint = "TerminateJobObject", SetLastError = true)]
|
|
61
|
+
static extern bool TerminateOwnedJob(SafeFileHandle job, uint code);
|
|
62
|
+
public static void Kill(SafeFileHandle job)
|
|
63
|
+
{
|
|
64
|
+
if (job == null)
|
|
65
|
+
return;
|
|
66
|
+
try
|
|
67
|
+
{
|
|
68
|
+
TerminateOwnedJob(job, 1);
|
|
69
|
+
}
|
|
70
|
+
catch (ObjectDisposedException) { }
|
|
71
|
+
}
|
|
72
|
+
public static void Set<T>(IntPtr job, int kind, T data)
|
|
73
|
+
{
|
|
74
|
+
int size = Marshal.SizeOf(typeof(T));
|
|
75
|
+
IntPtr memory = Marshal.AllocHGlobal(size);
|
|
76
|
+
try
|
|
77
|
+
{
|
|
78
|
+
Marshal.StructureToPtr(data, memory, false);
|
|
79
|
+
if (!SetInformationJobObject(job, kind, memory, (uint)size))
|
|
80
|
+
throw new Exception("JOB_LIMIT");
|
|
81
|
+
}
|
|
82
|
+
finally { Marshal.FreeHGlobal(memory); }
|
|
83
|
+
}
|
|
84
|
+
public static IntPtr Job(bool aggregate)
|
|
85
|
+
{
|
|
86
|
+
var job = CreateJobObject(IntPtr.Zero, null);
|
|
87
|
+
if (job == IntPtr.Zero)
|
|
88
|
+
throw new Exception("JOB_CREATE");
|
|
89
|
+
try
|
|
90
|
+
{
|
|
91
|
+
var limits = new ExtendedLimits();
|
|
92
|
+
limits.basic.flags = 0x2000; // KILL_ON_JOB_CLOSE; no breakaway.
|
|
93
|
+
if (aggregate)
|
|
94
|
+
{
|
|
95
|
+
limits.basic.flags |= 0x200 | 8 | 0x20;
|
|
96
|
+
limits.jobMemory = new UIntPtr(4294967296UL);
|
|
97
|
+
limits.basic.active = 64;
|
|
98
|
+
limits.basic.priority = 0x4000;
|
|
99
|
+
}
|
|
100
|
+
Set(job, 9, limits);
|
|
101
|
+
if (aggregate)
|
|
102
|
+
Set(job, 15, new CpuLimits { flags = 5, rate = (uint)Math.Min(10000, Math.Max(1, 20000 / Environment.ProcessorCount)) });
|
|
103
|
+
return job;
|
|
104
|
+
}
|
|
105
|
+
catch { CloseHandle(job); throw; }
|
|
106
|
+
}
|
|
107
|
+
public static void Budget(IntPtr job, double cores, ulong memory)
|
|
108
|
+
{
|
|
109
|
+
var limits = new ExtendedLimits();
|
|
110
|
+
limits.basic.flags = 0x2000 | 0x200 | 8 | 0x20;
|
|
111
|
+
limits.jobMemory = new UIntPtr(memory);
|
|
112
|
+
limits.basic.active = 64;
|
|
113
|
+
limits.basic.priority = 0x4000;
|
|
114
|
+
Set(job, 9, limits);
|
|
115
|
+
Set(job, 15, new CpuLimits { flags = 5, rate = (uint)Math.Min(10000, Math.Max(1, cores * 10000 / Environment.ProcessorCount)) });
|
|
116
|
+
}
|
|
117
|
+
public static uint[] Processes(IntPtr job)
|
|
118
|
+
{
|
|
119
|
+
int size = 8 + 64 * IntPtr.Size;
|
|
120
|
+
IntPtr memory = Marshal.AllocHGlobal(size);
|
|
121
|
+
try
|
|
122
|
+
{
|
|
123
|
+
uint length;
|
|
124
|
+
if (!QueryInformationJobObject(job, 3, memory, (uint)size, out length))
|
|
125
|
+
throw new Exception("JOB_INSPECT");
|
|
126
|
+
int count = Marshal.ReadInt32(memory, 4);
|
|
127
|
+
if (count < 0 || count > 64)
|
|
128
|
+
throw new Exception("JOB_LIMIT");
|
|
129
|
+
var ids = new uint[count];
|
|
130
|
+
for (int i = 0; i < count; i++)
|
|
131
|
+
ids[i] = unchecked((uint)Marshal.ReadIntPtr(memory, 8 + i * IntPtr.Size).ToInt64());
|
|
132
|
+
return ids;
|
|
133
|
+
}
|
|
134
|
+
finally { Marshal.FreeHGlobal(memory); }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|