@nativestudio/cli 0.3.0-rc.6 → 0.3.0-rc.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMPATIBILITY.json +7 -7
- package/LICENSE +201 -21
- package/components/runtime.json +3 -3
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-CA54SKBO.js → chunk-6SYHA2B4.js} +1 -1
- package/dist/_chunks/{chunk-GJ7BZJLW.js → chunk-A7EUJNCL.js} +1 -1
- package/dist/_chunks/chunk-AJ7S73M4.js +1 -0
- package/dist/_chunks/chunk-DRHPICBU.js +1 -0
- package/dist/_chunks/chunk-FCHO4AVP.js +1 -0
- package/dist/_chunks/chunk-JH5QP6PC.js +1 -0
- package/dist/_chunks/chunk-LF442QV6.js +1 -0
- package/dist/_chunks/chunk-LUBHPAPW.js +1 -0
- package/dist/_chunks/chunk-OZ5KZSTM.js +1 -0
- package/dist/_chunks/chunk-RJ4QQF7E.js +1 -0
- package/dist/_chunks/chunk-RT5PFKYS.js +1 -0
- package/dist/_chunks/chunk-SIJPJIBO.js +1 -0
- package/dist/_chunks/{chunk-KNFUMWDY.js → chunk-TCZJLYSR.js} +1 -1
- package/dist/_chunks/chunk-TTFDNLQE.js +1 -0
- package/dist/_chunks/chunk-URKX77KR.js +1 -0
- package/dist/_chunks/chunk-XRYARPEL.js +1 -0
- package/dist/_chunks/device-management-4XIITODX.js +1 -0
- package/dist/_chunks/device-preflight-SDA7Q3LH.js +1 -0
- package/dist/_chunks/devices-inventory-RVHGI2YW.js +1 -0
- package/dist/_chunks/devices-main-WOILNAGY.js +1 -0
- package/dist/_chunks/http-profile-XCHTSJV4.js +1 -0
- package/dist/_chunks/library-main-ZQKJQNHE.js +1 -0
- package/dist/_chunks/local-main-DX47PKHX.js +1 -0
- package/dist/_chunks/local-mcp-HMS5ODZN.js +1 -0
- package/dist/_chunks/main-HQGVZ2O2.js +2 -0
- package/dist/_chunks/mcp-6Q4ALHN6.js +1 -0
- package/dist/_chunks/project-connect-U2IHGC5W.js +1 -0
- package/dist/_chunks/render-main-A2AABFAG.js +1 -0
- package/dist/_chunks/source-import-5N4KZMTC.js +1 -0
- package/dist/_chunks/src-NIMTPR5W.js +1 -0
- package/dist/_chunks/{stdio-main-4Z2JVCMO.js → stdio-main-JJCNIY4H.js} +1 -1
- package/dist/_chunks/workspace-main-ZIZO4WRI.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +1077 -564
- package/dist/_types/cli/local/desktop-device-contract.d.ts +170 -556
- package/dist/_types/cli/local/desktop-device-owner.d.ts +16 -50
- package/dist/_types/cli/local/desktop-device-state.d.ts +198 -31
- package/dist/_types/cli/local/desktop-library.d.ts +853 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +220 -39
- package/dist/_types/cli/local/ledger.d.ts +2 -0
- package/dist/_types/cli/local/manager.d.ts +352 -22
- package/dist/_types/cli/local/mcp-tools.d.ts +218 -39
- package/dist/_types/cli/local/project-render-tools.d.ts +8742 -77
- package/dist/_types/cli/local-management.d.ts +2 -1
- 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 -11765
- package/dist/_types/contracts/delivery-operations.d.ts +51 -3921
- 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 +67 -0
- package/dist/_types/contracts/editor-intelligence.d.ts +114 -2491
- package/dist/_types/contracts/exploration-recommendation.d.ts +263 -11655
- package/dist/_types/contracts/external-agent-access.d.ts +9 -3
- package/dist/_types/contracts/final-ready.d.ts +22 -22
- package/dist/_types/contracts/final-render.d.ts +1569 -6949
- package/dist/_types/contracts/human-identity.d.ts +13 -0
- package/dist/_types/contracts/index.d.ts +3 -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-evidence.d.ts +2 -2
- package/dist/_types/contracts/local-execution/agent-grant.d.ts +2 -2
- package/dist/_types/contracts/local-execution/agent-review.d.ts +30 -285
- 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/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 -59
- package/dist/_types/contracts/local-execution/external-generation.d.ts +199 -0
- package/dist/_types/contracts/local-execution/index.d.ts +19 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +1517 -711
- 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 +21 -5
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +161 -44
- package/dist/_types/contracts/local-execution/management.d.ts +214 -208
- package/dist/_types/contracts/local-execution/media-recipe.d.ts +5 -1
- 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/preview.d.ts +120 -10988
- 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 +69 -10741
- package/dist/_types/contracts/local-execution/workspace.d.ts +5 -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/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 -6009
- 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 -4505
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +317 -8163
- package/dist/_types/contracts/review-intelligence.d.ts +450 -11468
- package/dist/_types/contracts/rough-cut-manifest.d.ts +1 -0
- package/dist/_types/contracts/rough-cut-review.d.ts +134 -12566
- package/dist/_types/contracts/rough-cut.d.ts +1076 -5731
- 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 +37 -6
- package/dist/_types/contracts/visual-sequence.d.ts +22 -0
- package/dist/_types/contracts/workspace.d.ts +22 -0
- package/dist/_types/sdk/errors.d.ts +1 -1
- package/dist/_types/sdk/local-runtime/device-client.d.ts +7 -33
- package/dist/_types/sdk/local-runtime/library.d.ts +268 -0
- package/dist/_types/sdk/local-runtime/workspace.d.ts +9 -4
- package/dist/_types/sdk/local-runtime-client.d.ts +477 -32
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/package.json +2 -8
- package/README.md +0 -119
- package/dist/_chunks/chunk-D533YC7J.js +0 -1
- package/dist/_chunks/chunk-HKD6F6M6.js +0 -1
- package/dist/_chunks/chunk-INLSOHAK.js +0 -1
- package/dist/_chunks/chunk-N6S6HCWE.js +0 -1
- package/dist/_chunks/chunk-PBEHCYR7.js +0 -1
- package/dist/_chunks/chunk-RVGDXRPK.js +0 -1
- package/dist/_chunks/chunk-YKOJPJZR.js +0 -1
- package/dist/_chunks/local-main-J2G7OU5E.js +0 -1
- package/dist/_chunks/local-mcp-LCHXL2IE.js +0 -1
- package/dist/_chunks/main-PPA76ARV.js +0 -2
- package/dist/_chunks/mcp-P7W623FE.js +0 -1
- package/dist/_chunks/project-connect-7L2HRJUN.js +0 -1
- package/dist/_chunks/render-main-ZW6UJHGN.js +0 -1
- package/dist/_chunks/src-BXLFLNRG.js +0 -1
package/dist/local-management.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalInstallationManager,captureInstalledTools,connectDevice,generateDeviceKey,newerVersion,ownerClient,socketAbsent,toolPreference,waitStopped}from"./_chunks/chunk-HKD6F6M6.js";import{DesktopDeviceRecords,DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-N6S6HCWE.js";import{LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDeviceChallengeSchema,LocalDeviceGrantSchema,LocalDeviceSessionSchema,LocalDeviceViewSchema,LocalDiagnosticsSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalPreviewAdmissionSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema,canonicalLocalJson,catalogue,endpoint}from"./_chunks/chunk-RVGDXRPK.js";import{LocalClientError,atomicMove,directory,entries,fail,optional,read,sha256,write}from"./_chunks/chunk-KB2GVAN7.js";import"./_chunks/chunk-PBEHCYR7.js";import"./_chunks/chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./_chunks/chunk-6NVIN2NI.js";import{z as z8}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest5=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest5||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest5}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest5=record.digest}return{plan,digest:digest5}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z3}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join4,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}import{join as join3}from"node:path";import{z as z2}from"zod";var digest=z2.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z2.strictObject({enabled:z2.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z2.uuid(),deviceRevision:z2.int().positive(),installationFingerprint:digest,projects:z2.array(z2.strictObject({projectId:z2.uuid(),grantId:z2.uuid(),revision:z2.int().positive(),expiresAt:z2.iso.datetime()})).min(1).max(20)});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join3(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;const grants=state.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());return grants.length>0&&grants.every(g=>policy.projects.some(p=>p.projectId===g.projectId&&p.grantId===g.grantId&&p.revision===g.revision&&p.expiresAt===g.expiresAt))}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint,projectIds){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const grants=state.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());if(!grants.length||grants.some(g=>!projectIds.includes(g.projectId)))fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint,projects:grants.map(g=>({projectId:g.projectId,grantId:g.grantId,revision:g.revision,expiresAt:g.expiresAt}))});await write(join3(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join3(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}var id=z3.uuid();var digest2=z3.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z3.strictObject({operation:z3.literal("storage"),call:z3.discriminatedUnion("action",[z3.strictObject({action:z3.literal("status")}),z3.strictObject({action:z3.literal("prepare"),mode:z3.enum(["BACKUP","MIGRATE"]),destination:z3.string().min(1).max(4096)}),z3.strictObject({action:z3.enum(["execute","recover","abandon"]),id,fingerprint:digest2})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view2}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view2)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join4(home,"storage-plans"));const pointer=await optional(join4(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join4(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join4(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join4(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join4(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join4(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join4(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z4}from"zod";var DesktopOfflineRequestSchema=z4.strictObject({operation:z4.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!policy.projects.some(p=>Date.parse(p.expiresAt)>Date.now())||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z5}from"zod";import{join as join5}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z5.string().regex(/^[a-f0-9]{64}$/);var historyItem=z5.strictObject({id:z5.uuid(),projectId:z5.uuid(),productionId:z5.uuid(),kind:z5.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z5.uuid().optional()});var stateSchema=z5.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z5.array(historyItem).max(200)});var DesktopAgentRequestSchema=z5.strictObject({operation:z5.literal("agent"),scope:DesktopDeviceScopeSchema,call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("discover"),binary:z5.string().min(1).max(4096).optional()}),z5.strictObject({action:z5.literal("probe")}),z5.strictObject({action:z5.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z5.strictObject({action:z5.literal("revoke")}),z5.strictObject({action:z5.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z5.strictObject({action:z5.literal("stage"),id:z5.uuid(),mediaFileId:z5.uuid().optional()}),z5.strictObject({action:z5.literal("start"),id:z5.uuid(),expectedRevision:z5.int().positive(),approval:sha}),z5.strictObject({action:z5.literal("inspect"),id:z5.uuid()})])});var DesktopAgentReplySchema=z5.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z5.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z5.boolean()})).max(200),pendingGrant:z5.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join5(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join5(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join5(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join5(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z6}from"zod";var digest3=z6.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z6.strictObject({operation:z6.literal("bootstrap"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.literal("prepare")}),z6.strictObject({action:z6.literal("apply"),id:z6.uuid(),fingerprint:digest3})])});var DesktopBootstrapReplySchema=z6.strictObject({id:z6.uuid(),fingerprint:digest3,version:z6.string().min(1).max(80),host:z6.string().min(1).max(512),bytes:z6.int().positive(),expiresAt:z6.iso.datetime(),installed:z6.boolean()});import{z as z7}from"zod";var DesktopWorkspaceRequestSchema=z7.strictObject({operation:z7.literal("workspace"),call:z7.discriminatedUnion("action",[z7.strictObject({action:z7.enum(["inspect","clean","diagnostics"])}),z7.strictObject({action:z7.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z7.int().nonnegative()}),z7.strictObject({action:z7.literal("activity"),idleSeconds:z7.int().min(0).max(86400),observedAt:z7.iso.datetime()})])});var DesktopWorkspaceReplySchema=z7.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z8.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z8.string().url().max(4096),publicKey:z8.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z8.discriminatedUnion("operation",[DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z8.strictObject({operation:z8.enum(["status","start","stop","check","configuration","recovery"])}),z8.strictObject({operation:z8.enum(["prepare","reject"]),version}),z8.strictObject({operation:z8.literal("tools-prepare"),version,choice:z8.discriminatedUnion("mode",[z8.strictObject({mode:z8.literal("MANAGED")}),z8.strictObject({mode:z8.literal("INSTALLED"),ffmpeg:z8.string().min(1).max(4096),ffprobe:z8.string().min(1).max(4096)})])}),z8.strictObject({operation:z8.literal("configure"),channelFingerprint:fingerprint}),z8.strictObject({operation:z8.enum(["apply","recover"]),planId:z8.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z8.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z8.string().regex(/^[A-Z_]{1,64}$/),toolMode:z8.enum(["MANAGED","INSTALLED"]).nullable().optional()});var DesktopUpdateCheckSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z8.array(z8.strictObject({version,rejected:z8.boolean()})).max(128),notifications:z8.boolean()});var DesktopOwnerPlanSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z8.strictObject({kind:z8.enum(["APPLY","RECOVER"]),toolMode:z8.enum(["MANAGED","INSTALLED"]).optional(),planId:z8.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z8.iso.datetime(),phase:z8.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z8.boolean(),source:z8.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z8.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;const active=(await manager.ledger.current()).value.active;const toolMode=active?.toolsConfigPath?(await toolPreference(active.toolsConfigPath,null)).mode:null;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase,toolMode})}import{createPublicKey}from"node:crypto";import{join as join6}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED"))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;const stateDirectory=join6(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join6(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join6(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}import{createPrivateKey as createPrivateKey2,createPublicKey as createPublicKey2,randomUUID as randomUUID4}from"node:crypto";import{randomUUID as randomUUID2}from"node:crypto";async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device)fail("DEVICE_ENROLLMENT_REQUIRED");const valid=s.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());if(!valid.length)fail("LOCAL_AUTHORIZATION_REQUIRED");const projects=valid.map(g=>({tenantId:g.tenantId,projectId:g.projectId}));const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const reuse=running&&previous&&canonicalLocalJson(previous.projects)===canonicalLocalJson(projects);const expiresAt=new Date(Math.min(Date.now()+24*36e5,...valid.map(g=>Date.parse(g.expiresAt)))).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",projects,expiresAt}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,projects});await manager.start()}const id2=randomUUID2();await manager.grant({projects,expiresAt},records.connectorPath(id2));return records.save(s,{connectorId:id2,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const actual=JSON.parse((await read(c.cloudConfigFile,32768)).toString());if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||canonicalLocalJson(actual.projects)!==canonicalLocalJson(s.connection.projects))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID3}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const started=performance.now();const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)-Date.parse(challenge.issuedAt)<=performance.now()-started)fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.parse(challenge.issuedAt)/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID3(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint2=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label}:null,grants:s.grants,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="GRANT"){const g=LocalDeviceGrantSchema.parse(result),input2=command.input;if(g.tenantId!==input2.tenantId||g.projectId!==input2.projectId||g.deviceId!==input2.deviceId||g.deviceRevision!==input2.deviceRevision||g.revision!==input2.expectedRevision+1||g.expiresAt!==input2.expiresAt||g.capability!==input2.capability||g.executionPolicy!==input2.executionPolicy||g.approvedByPrincipalId!==s.scope.principalId||g.revokedAt)fail("DEVICE_RESULT_INVALID");return{grants:[...s.grants.filter(v=>v.projectId!==g.projectId),g]}}if(command.kind==="REVOKE_GRANT"){if(result?.semanticStatus!=="SUCCESS")fail("DEVICE_RESULT_INVALID");return{grants:s.grants.map(g=>g.projectId===command.input.projectId?{...g,revision:g.revision+1,revokedAt:new Date().toISOString()}:g),connectorId:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint,call.projectIds);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey2(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID4(),label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(!s.grants.some(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now()))fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID4()}}}else{const grant=s.grants.find(g=>g.projectId===call.projectId);if(call.action==="grant"){const ttl=Date.parse(call.expiresAt)-Date.now();if(ttl<=0||ttl>24*36e5||s.grants.length>=20&&!grant)fail("INVALID_INPUT");command={kind:"GRANT",input:{tenantId:s.scope.tenantId,projectId:call.projectId,requestId:randomUUID4(),deviceId:d.deviceId,deviceRevision:d.revision,expectedRevision:grant?.revision??0,expiresAt:call.expiresAt,...call.executionPolicy?{executionPolicy:call.executionPolicy}:{},capability:call.capability??"ROUGH_CUT_PREVIEW_V1"}}}else{if(!grant||grant.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_GRANT",input:{tenantId:s.scope.tenantId,projectId:call.projectId,requestId:randomUUID4(),grantId:grant.grantId,expectedRevision:grant.revision}}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint2(parsed),phase:"PREPARED"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}import{z as z9}from"zod";import{join as join7}from"node:path";import{randomUUID as randomUUID5}from"node:crypto";var digest4=z9.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z9.strictObject({id:z9.uuid(),channel:z9.strictObject({protocol:z9.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z9.string().url(),publicKey:z9.string()}),release:LocalReleaseSchema,installationRevision:z9.int().nonnegative(),expiresAt:z9.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join7(home,"bootstrap-plans"));let intent2,fingerprint3;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join7(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent2=intentSchema.parse({id:randomUUID5(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint3=sha256(canonicalLocalJson(intent2));await write(join7(root,intent2.id+".json"),canonicalLocalJson({intent:intent2,fingerprint:fingerprint3}),true)}else{const saved=z9.strictObject({intent:intentSchema,fingerprint:digest4}).parse(JSON.parse((await read(join7(root,call.id+".json"),131072)).toString()));intent2=saved.intent;fingerprint3=saved.fingerprint;if(fingerprint3!==call.fingerprint||fingerprint3!==sha256(canonicalLocalJson(intent2))||intent2.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join7(root,intent2.id+".installation.json");const receipt=z9.strictObject({id:z9.uuid(),fingerprint:digest4}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent2.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent2.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent2.channel);await configureDesktopChannel(manager,trust.fingerprint,intent2.channel);const plan=await manager.prepare(intent2.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent2.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent2.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent2.id,fingerprint:fingerprint3,version:intent2.release.descriptor.version,host:new URL(intent2.channel.catalogueUrl).host,bytes:intent2.release.package.byteSize+Object.values(intent2.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent2.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat as lstat3,readFile,chmod as chmod2}from"node:fs/promises";import{join as join8,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat3(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod2(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join8(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join8(await directory(home),"nodes",expected)),target=join8(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join8(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,runDesktopOwnerRequest,runLocalManagement};
|
|
1
|
+
import{DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,canResumeDesktop,desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation,prepareDesktopLibraryImport,rememberDesktopAutomation,runDesktopLibraryImport,runDesktopLibraryMedia,runDesktopLibraryRequest}from"./_chunks/chunk-LF442QV6.js";import{connectDevice,generateDeviceKey}from"./_chunks/chunk-OZ5KZSTM.js";import{LocalInstallationManager,captureInstalledTools,newerVersion,ownerClient,probeLocalLibrary,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantSpeech,probeTenantTranscription,socketAbsent,toolPreference,waitStopped}from"./_chunks/chunk-LUBHPAPW.js";import{DesktopDeviceRecords,DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-SIJPJIBO.js";import{catalogue,endpoint}from"./_chunks/chunk-JH5QP6PC.js";import{LocalClientError,atomicMove,directory,entries,fail,optional,read,sha256,write}from"./_chunks/chunk-KB2GVAN7.js";import{LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDeviceChallengeSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalDiagnosticsSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalPreviewAdmissionSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema,canonicalLocalJson,processorFamilies}from"./_chunks/chunk-FCHO4AVP.js";import"./_chunks/chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./_chunks/chunk-6NVIN2NI.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,...view2}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view2)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(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();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=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({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}import{createPrivateKey as createPrivateKey2,createPublicKey as createPublicKey2,randomUUID as randomUUID4}from"node:crypto";import{randomUUID as randomUUID2}from"node:crypto";async function desktopDeviceCapabilities(manager){const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");const root=manager.ledger.slotPath(active);const validation=await probeTenantMediaValidation(root,active);const processing=await probeTenantMediaProcessing(root,active);const processors=processing?Object.keys(processorFamilies).filter(kind=>!["COMPOSITION_RENDER","LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH","SPEECH_SYNTHESIZE","TRANSCRIBE_AUDIO","KEYFRAME_GENERATE","VIDEO_GENERATE","SPEECH_EXTERNAL_QWEN","TRANSCRIBE_EXTERNAL_QWEN"].includes(kind)):[];if(processing){if(await probeLocalLibrary(root,active))processors.push("LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH");if(await probeTenantComposition(root,active))processors.push("COMPOSITION_RENDER");if(await probeTenantSpeech(root,active))processors.push("SPEECH_SYNTHESIZE");if(await probeTenantTranscription(root,active))processors.push("TRANSCRIBE_AUDIO")}return{...validation?{tenantMediaValidation:true}:{},...processors.length?{tenantMediaProcessing:true,processorCapabilities:processors.sort()}:{}}}async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device||s.device.revokedAt)fail("DEVICE_ENROLLMENT_REQUIRED");const capabilities=await desktopDeviceCapabilities(manager);const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const matches=value=>{const saved=value;return saved?.deviceRevision===s.device.revision&&saved.tenantMediaValidation===capabilities.tenantMediaValidation&&saved.tenantMediaProcessing===capabilities.tenantMediaProcessing&&canonicalLocalJson(saved.processorCapabilities??null)===canonicalLocalJson(capabilities.processorCapabilities??null)};const reuse=running&&matches(previous)&&matches(s.connection);const expiresAt=new Date(Date.now()+24*36e5).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",expiresAt,deviceRevision:s.device.revision,...capabilities}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,...capabilities});await manager.start()}const id2=randomUUID2();await manager.grant({tenantId:s.scope.tenantId,deviceId:s.device.deviceId,expiresAt},records.connectorPath(id2));return records.save(s,{connectorId:id2,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device||s.device.revokedAt)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const raw=JSON.parse((await read(c.cloudConfigFile,32768)).toString());const{tools:_tools,...transport}=raw;void _tools;const actual=LocalDeviceTransportConfigurationSchema.parse(transport);if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||actual.deviceRevision!==s.connection.deviceRevision||actual.deviceRevision!==s.device.revision||actual.tenantMediaValidation!==s.connection.tenantMediaValidation||actual.tenantMediaProcessing!==s.connection.tenantMediaProcessing||canonicalLocalJson(actual.processorCapabilities??null)!==canonicalLocalJson(s.connection.processorCapabilities??null))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID3}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const started=performance.now();const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)-Date.parse(challenge.issuedAt)<=performance.now()-started)fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.parse(challenge.issuedAt)/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID3(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint2=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label,revision:s.device.revision,revokedAt:s.device.revokedAt}:null,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="REVOKE_DEVICE"){if(result?.semanticStatus!=="SUCCESS"||!s.device)fail("DEVICE_RESULT_INVALID");return{device:{...s.device,revision:s.device.revision+1,revokedAt:new Date().toISOString()},connectorId:null,connection:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});const processingSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantMediaProcessing(manager.ledger.slotPath(active),active)};const librarySupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeLocalLibrary(manager.ledger.slotPath(active),active)};const compositionSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantComposition(manager.ledger.slotPath(active),active)};if(call.action==="media-processing-capability")return DesktopDeviceReplySchema.parse({view:publicView(),mediaProcessingSupported:await processingSupported(),localLibrarySupported:await librarySupported(),compositionProcessingSupported:await compositionSupported()});if(call.action==="media-validation-capability"){const active=(await manager.ledger.current()).value.active;const supported=!!active&&await probeTenantMediaValidation(manager.ledger.slotPath(active),active);return DesktopDeviceReplySchema.parse({view:publicView(),mediaValidationSupported:supported})}if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey2(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID4(),label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID4()}}}else{if(call.action!=="revoke"||d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_DEVICE",input:{tenantId:s.scope.tenantId,deviceId:d.deviceId,requestId:randomUUID4(),expectedRevision:d.revision}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint2(parsed),phase:"PREPARED"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}import{z as z8}from"zod";import{join as join6}from"node:path";import{randomUUID as randomUUID5}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,fingerprint3;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=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:randomUUID5(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint3=sha256(canonicalLocalJson(intent2));await write(join6(root,intent2.id+".json"),canonicalLocalJson({intent:intent2,fingerprint:fingerprint3}),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;fingerprint3=saved.fingerprint;if(fingerprint3!==call.fingerprint||fingerprint3!==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:fingerprint3,version:intent2.release.descriptor.version,host:new URL(intent2.channel.catalogueUrl).host,bytes:intent2.release.package.byteSize+Object.values(intent2.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent2.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"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-AJ7S73M4.js";import{DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-SIJPJIBO.js";import"./_chunks/chunk-JH5QP6PC.js";import"./_chunks/chunk-KB2GVAN7.js";import"./_chunks/chunk-FCHO4AVP.js";import"./_chunks/chunk-VPYAXWXY.js";import"./_chunks/chunk-6NVIN2NI.js";async function openDesktopDeviceTools(raw,home){const scope=DesktopDeviceScopeSchema.parse(raw);return LocalMcpTools.open(await desktopDeviceConnector(home,scope),home)}export{LocalMcpTools,openDesktopDeviceTools};
|
package/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.7",
|
|
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,119 +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
|
-
Connect to the selected Project; its verified MCP URL is resolved automatically:
|
|
30
|
-
|
|
31
|
-
```sh
|
|
32
|
-
nvs connect
|
|
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
|
-
Managed FFmpeg/ffprobe are selected from the signed catalogue when a qualified
|
|
61
|
-
distribution exists for the requested media profile. The older silent-preview
|
|
62
|
-
tools do not qualify for `STUDIO_MEDIA_V2` device preview/final rendering. That
|
|
63
|
-
profile currently requires an explicitly selected, qualified installed tool pair;
|
|
64
|
-
the Runtime checks the actual encoders, decoders, filters and hashes before use.
|
|
65
|
-
To switch deliberately, prepare a tools plan for the exact installed Runtime version:
|
|
66
|
-
|
|
67
|
-
```sh
|
|
68
|
-
nvs local tools-prepare --version VERSION_FROM_CHECK --input /absolute/private/tools.json
|
|
69
|
-
nvs local update-apply --plan PLAN_UUID --approve PLAN_FINGERPRINT
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
The private JSON is `{ "mode": "MANAGED" }` or
|
|
73
|
-
`{ "mode": "INSTALLED", "ffmpeg": "/absolute/ffmpeg", "ffprobe": "/absolute/ffprobe" }`.
|
|
74
|
-
The CLI captures exact hashes and qualifies the programs before activation; it does not
|
|
75
|
-
search PATH. Installed choices survive later updates. In Desktop, use Local Runtime's
|
|
76
|
-
tool choices and the native file pickers. Existing stopped journals need an explicitly
|
|
77
|
-
started Runtime for pending-work inspection before a switch; incompatible pending work
|
|
78
|
-
blocks it. Timestamp renewal preserves a fresh trust-bound approval, while a changed
|
|
79
|
-
key/source/release or expired plan requires a new selection.
|
|
80
|
-
|
|
81
|
-
Media executables have their own GPL notices and corresponding source archive; see the
|
|
82
|
-
Runtime notices and the download site's media inventory. Platform support depends on the signed catalogue and
|
|
83
|
-
qualification evidence; packaging alone does not certify Windows/Apple Silicon QA.
|
|
84
|
-
|
|
85
|
-
## Recovery and private state
|
|
86
|
-
|
|
87
|
-
Private credentials, connection epochs and receipts live outside the package under
|
|
88
|
-
`~/.nativestudio/client` (or an explicit private `NATIVESTUDIO_CLIENT_HOME`). Failed
|
|
89
|
-
login preserves the prior account/connection. An unresolved token exchange is fenced;
|
|
90
|
-
start a fresh login/connection rather than replay the exchange. UNKNOWN business writes
|
|
91
|
-
must be reconciled through their native Operation or supported explicit idempotency.
|
|
92
|
-
Neither a process timeout nor MCP cancellation cancels an admitted Job automatically.
|
|
93
|
-
|
|
94
|
-
The implementation remains readable under MIT. Packages exclude source maps,
|
|
95
|
-
build-machine paths, raw TypeScript, private credentials and local state. Fixed
|
|
96
|
-
Windows C#/PowerShell helper resources are intentional scoped execution assets.
|
|
97
|
-
`COMPATIBILITY.json` records protocol and component identities. The local navigation
|
|
98
|
-
and management export subpaths are experimental host integrations, not general Agent
|
|
99
|
-
permission to control installation or execute shell commands.
|
|
100
|
-
|
|
101
|
-
With a workspace and Project selected, `nvs connect` resolves the first-party
|
|
102
|
-
Project endpoint. To render, request `nvs connect --scope 'nvs:read nvs:write'`.
|
|
103
|
-
A matching current consent is reused. Device enrollment and Project consent
|
|
104
|
-
remain separate; the Agent does not receive the device key or account password.
|
|
105
|
-
|
|
106
|
-
nvs render preview --production PRODUCTION_UUID --request STABLE_REQUEST_UUID
|
|
107
|
-
nvs render final --production PRODUCTION_UUID --request ANOTHER_REQUEST_UUID
|
|
108
|
-
|
|
109
|
-
The CLI reads the native basis and stores the exact command before sending it.
|
|
110
|
-
Keep the request UUID. A repeat reads the original local receipt or reports an
|
|
111
|
-
unknown outcome without submitting a second render. You can specify `--device
|
|
112
|
-
DEVICE_UUID` where several devices are authorized. Offline or missing capacity
|
|
113
|
-
does not start a server render. The receipt identifies the device, Runtime Job,
|
|
114
|
-
Operation and render; use `nvs resume` for subsequent native status.
|
|
115
|
-
|
|
116
|
-
For an Agent running on the tenant computer, `nvs local mcp` discovers an
|
|
117
|
-
already-approved connector for the selected account when available. Its default
|
|
118
|
-
tools are read-only. Add `--with-project-renders` to expose `local_render_prepare`
|
|
119
|
-
and `local_render_start` after the separate write grant has been obtained.
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{loadConnection,projectConnection}from"./chunk-KNFUMWDY.js";import{profileAuthorization}from"./chunk-DXJQWTLG.js";import{readCredential}from"./chunk-6LU6GJKW.js";import{sha256}from"./chunk-KB2GVAN7.js";import{connectRemoteMcp}from"./chunk-CA54SKBO.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";async function renderConnection(env,signal){const scope=await loadConnection(env,true);if(!scope?.scope.split(/\s+/).includes("nvs:write"))throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const auth=await profileAuthorization(scope.profile,signal);if(auth.resource!==scope.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return{scope,...await connectRemoteMcp(scope.resource,auth.authorization,scope.tenantId)}}async function callerRenderConnection(env,flags){const url=flags.get("--mcp-url");if(!url&&!flags.has("--token-file"))return renderConnection(env);if(!url||!flags.has("--token-file"))throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const scope=projectConnection(url),auth=await readCredential(flags,env);return{scope:{...scope,profile:"grant:"+sha256(auth)},...await connectRemoteMcp(scope.resource,auth,scope.tenantId)}}export{renderConnection,callerRenderConnection};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LocalDeviceTransportConfigurationSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,asset,canonicalLocalJson,catalogue,select}from"./chunk-RVGDXRPK.js";import{assertExecutable,directory,entries,fail,localSocketPath,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-KB2GVAN7.js";import{z}from"zod";import{constants,createReadStream}from"node:fs";import{open,realpath}from"node:fs/promises";import{isAbsolute}from"node:path";import{createHash}from"node:crypto";async function toolPreference(previous,cloud,explicit){if(explicit)return LocalToolChoiceSchema.parse(explicit);const raw=previous?JSON.parse((await read(previous,32768)).toString()):cloud?JSON.parse((await read(cloud,32768)).toString()).tools:null;const selected=raw?LocalToolSelectionSchema.parse(raw):null;return selected?.mode==="INSTALLED"?{...selected,mode:"INSTALLED"}:{mode:"MANAGED"}}async function captureInstalledTools(paths){paths=z.strictObject({mode:z.literal("INSTALLED").optional(),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096)}).parse(paths);const selected={};for(const name of["ffmpeg","ffprobe"]){if(!isAbsolute(paths[name]))fail("TOOL_PATH_INVALID");const path=await realpath(paths[name]);await assertExecutable(path);const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await file.stat();if(!before.isFile()||before.size<1||before.size>256*1024*1024)fail("TOOL_PATH_INVALID");const h=createHash("sha256");let count=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){count+=chunk.length;if(count>before.size)fail("TOOL_CHANGED");h.update(chunk)}const after=await file.stat();if(count!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs)fail("TOOL_CHANGED");selected[name]={path,digest:h.digest("hex")}}finally{await file.close()}}return LocalToolChoiceSchema.parse({mode:"INSTALLED",...selected})}import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.extend({tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);const active=(await manager.ledger.current()).value.active;const actual=active?.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;if(input.tools&&active&&(!actual||canonicalLocalJson(input.tools)!==canonicalLocalJson(actual)))fail("TOOL_SELECTION_PLAN_REQUIRED");let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");await write(file,canonicalLocalJson({...input,tools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,projects:input.projects,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}var requiredRuntimeFiles=["package.json","dist/entry.js","dist/supervisor.mjs","dist/parent-lifetime.mjs","dist/execution-identity.json"];var allowedRuntimeFiles=new Set([...requiredRuntimeFiles,"README.md","LICENSE","dist/THIRD_PARTY_NOTICES.md","dist/BUNDLED_DEPENDENCIES.json","dist/agent-supervisor.mjs","dist/captions/NotoSansSC.ttf","dist/captions/NativeStudioSC-Regular.ttf","dist/captions/OFL.txt",...["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open as open2}from"node:fs/promises";import{dirname as dirname2,join as join2,delimiter}from"node:path";import{z as z2}from"zod";var environment=()=>({...Object.fromEntries(["HOME","USER","LOGNAME","TMPDIR","CODEX_HOME","SystemRoot","SYSTEMROOT","USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP"].flatMap(k=>process.env[k]?[[k,process.env[k]]]:[])),PATH:dirname2(process.execPath)+(process.platform==="win32"?"":delimiter+["/usr/bin","/bin"].join(delimiter)),LANG:"C",LC_ALL:"C",UV_THREADPOOL_SIZE:"2",NVS_INSTALL_OWNER:"MANAGED"});async function verifySlot(root,slot){if(requiredRuntimeFiles.some(name=>!Object.hasOwn(slot.files,name)))fail("SLOT_FILES_MISSING");for(const[name,hash]of Object.entries(slot.files)){if(!allowedRuntimeFiles.has(name))fail("SLOT_PATH_INVALID");if(sha256(await read(join2(root,name),64*1024*1024))!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probe(root,expected){const bytes=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join2(root,"dist/entry.js"),"--describe"],{env:environment(),stdio:["ignore","pipe","ignore"],shell:false});const parts=[];let size=0;const timer=setTimeout(()=>child.kill("SIGKILL"),1e4);child.stdout.on("data",b=>{size+=b.length;if(size>65536)child.kill("SIGKILL");else parts.push(b)});child.on("error",reject);child.on("close",code=>{clearTimeout(timer);if(code!==0||size>65536)reject(Error("Runtime descriptor unavailable"));else resolve(Buffer.concat(parts))})});const descriptor=LocalRuntimeDescriptorSchema.parse(JSON.parse(bytes.toString()));if(canonicalLocalJson(descriptor)!==canonicalLocalJson(expected))fail("RUNTIME_DESCRIPTOR_MISMATCH");return descriptor}async function ownerClient(stateDirectory){await directory(stateDirectory);return new NativeStudioLocalRuntimeClient({stateDirectory,authorization:async()=>"Bearer "+(await read(join2(stateDirectory,"control-token"),128)).toString()})}async function runningInventory(client,root,slot){const inventory=await client.inventory(),status=await client.status();if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(slot.descriptor)||status.versions.find(v=>v.component==="RUNTIME")?.executablePath!==join2(root,"dist/entry.js"))fail("RUNTIME_ALREADY_RUNNING");return inventory}async function launch(root,slot,stateDirectory,cloudConfig,toolsConfig){await verifySlot(root,slot);await probe(root,slot.descriptor);await directory(stateDirectory);const existing=await ownerClient(stateDirectory);try{return await runningInventory(existing,root,slot)}catch(e){if(e instanceof Error&&e.message.includes("RUNTIME_ALREADY_RUNNING"))throw e}const log=await open2(join2(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join2(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:environment(),detached:true,windowsHide:true,stdio:["ignore",log.fd,log.fd],shell:false});let spawnError=false;child.once("error",()=>{spawnError=true});child.unref();await log.close();const deadline=Date.now()+15e3;while(Date.now()<deadline){if(spawnError||child.exitCode!==null)fail("RUNTIME_START_FAILED");try{return await runningInventory(existing,root,slot)}catch{}await new Promise(r=>setTimeout(r,100))}child.kill("SIGTERM");fail("RUNTIME_START_UNCONFIRMED")}async function waitStopped(stateDirectory){const client=await ownerClient(stateDirectory),deadline=Date.now()+1e4;while(Date.now()<deadline){try{await client.inventory()}catch{const{lstat:lstat2}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat2(localSocketPath(stateDirectory))}catch(e){if(e.code==="ENOENT")return}const{createConnection}=await import("node:net");const closed=await new Promise(resolve=>{const s=createConnection(localSocketPath(stateDirectory));s.once("connect",()=>{s.destroy();resolve(false)});s.once("error",e=>resolve(["ECONNREFUSED","ENOENT"].includes(e.code??"")));s.setTimeout(300,()=>{s.destroy();resolve(false)})});if(closed)return}await new Promise(r=>setTimeout(r,100))}fail("RUNTIME_STOP_UNCONFIRMED")}async function socketAbsent(stateDirectory){const{createConnection}=await import("node:net");return new Promise(resolve=>{const socket=createConnection(localSocketPath(stateDirectory));socket.once("connect",()=>{socket.destroy();resolve(false)});socket.once("error",error=>resolve(["ECONNREFUSED","ENOENT"].includes(error.code??"")));socket.setTimeout(500,()=>{socket.destroy();resolve(false)})})}async function probeTools(root,stateDirectory,selection){const{execFile}=await import("node:child_process");const diagnostic=z2.strictObject({tool:z2.enum(["FFMPEG","FFPROBE"]),stage:z2.enum(["IDENTITY","VERSION","ENCODERS","DECODERS","FILTERS","DEMUXERS","MUXERS","FINAL_IDENTITY"]),cause:z2.enum(["IDENTITY_INVALID","VERSION_INVALID","CAPABILITY_MISSING","PROCESS_FAILED","TIMEOUT","CANCELLED"])});const failures=[];for(let attempt=0;attempt<2;attempt++){const result=await new Promise((resolve,reject)=>execFile(process.execPath,["--max-old-space-size=256",join2(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:environment(),timeout:5e4,maxBuffer:65536},(error,stdout,stderr)=>error?reject(Error("Tool probe failed")):resolve({stdout,stderr})));const report=LocalDoctorReportSchema.parse(JSON.parse(result.stdout));let failure;for(const line of result.stderr.split("\n")){try{const parsed=diagnostic.safeParse(JSON.parse(line).toolProbe);if(parsed.success)failure=parsed.data}catch{}}if(failure)failures.push(failure);if(failures.length)await write(join2(stateDirectory,"tool-qualification.json"),JSON.stringify({checkedAt:new Date().toISOString(),availability:report.availability,failures}));if(report.availability==="AVAILABLE")return report;if(!failure||!["TIMEOUT","PROCESS_FAILED"].includes(failure.cause))break}fail("TOOL_QUALIFICATION_FAILED")}import{randomUUID}from"node:crypto";import{lstat}from"node:fs/promises";import{join as join3}from"node:path";async function identity(path,cloud){if(!path)return null;const raw=JSON.parse((await read(path,32768)).toString());const tools=LocalToolSelectionSchema.parse(cloud?raw.tools:raw);return tools.ffmpeg.digest+":"+tools.ffprobe.digest}async function effective(path,cloud){return path?identity(path,false):identity(cloud,true)}function supportedRenderer(expected,digest){return expected.rendererDigest===digest||!!expected.compatibleRenderers?.some(r=>r.rendererDigest===digest)}async function assertPendingCompatible(raw,expected,previous,next,cloud){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingRenderers.some(d=>!supportedRenderer(expected,d)))fail("NATIVE_RECOVERY_REQUIRED");if(i.pendingExecutions+i.pendingRequests===0)return;if(i.descriptor.profileDigest!==expected.profileDigest&&!expected.compatibleRenderers?.some(r=>r.profileDigest===i.descriptor.profileDigest))fail("NATIVE_RECOVERY_REQUIRED");const before=await effective(previous,cloud);const after=await effective(next,cloud);if(!before||before!==after)fail("NATIVE_RECOVERY_REQUIRED")}async function assertPendingToolIdentity(raw,previous,cloud,next){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingExecutions+i.pendingRequests>0&&await effective(previous,cloud)!==next)fail("NATIVE_RECOVERY_REQUIRED")}async function assertNoStoppedJournal(state){for(const suffix of["","-wal","-shm","-journal"]){try{await lstat(join3(state,"journal.sqlite"+suffix))}catch(e){if(e.code==="ENOENT")continue;throw e}fail("RUNTIME_STATUS_REQUIRED")}}async function prepareInstallation(manager,version,raw){const c=await manager.configuration(),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const trusted=await catalogue(c),release=select(trusted.signed,version),explicit=raw===void 0?void 0:LocalToolChoiceSchema.parse(raw),preference=await toolPreference(current.active?.toolsConfigPath??null,c.cloudConfigFile,explicit),toolSelection=explicit||preference.mode==="INSTALLED"||release.tools?preference:void 0;if(toolSelection?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");let runtimeRevision=null;try{const inventory=await(await ownerClient(c.stateDirectory)).inventory();runtimeRevision=inventory.runtimeRevision;const previous=current.active?.toolsConfigPath??null;await assertPendingCompatible(inventory,release.descriptor,previous,previous,c.cloudConfigFile);const desired=preference.mode==="INSTALLED"?preference:release.tools;if(desired)await assertPendingToolIdentity(inventory,previous,c.cloudConfigFile,preference.mode==="INSTALLED"?preference.ffmpeg.digest+":"+preference.ffprobe.digest:release.tools.ffmpeg.sha256+":"+release.tools.ffprobe.sha256)}catch(e){if(e instanceof Error&&e.message.includes("NATIVE_RECOVERY_REQUIRED"))throw e;if(!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await assertNoStoppedJournal(c.stateDirectory)}const body={protocol:"NVS_LOCAL_UPDATE_PLAN_V1",planId:randomUUID(),installationRevision:current.revision,runtimeRevision,catalogueFingerprint:trusted.fingerprint,trustFingerprint:trusted.trustFingerprint,release,...toolSelection?{toolSelection}:{},createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join3(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{randomUUID as randomUUID2}from"node:crypto";import{join as join4,dirname as dirname3}from"node:path";import{z as z3}from"zod";async function grant(manager,raw,output){const i=z3.strictObject({projects:z3.array(z3.strictObject({tenantId:z3.uuid(),projectId:z3.uuid()})).min(1).max(100),expiresAt:z3.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname3(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join4(manager.ledger.root,"grants",randomUUID2()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,projects:i.projects,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-TTIQ7LYJ.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join4(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z3.strictObject({projects:z3.array(z3.strictObject({tenantId:z3.uuid(),projectId:z3.uuid()})).max(100),expiresAt:z3.iso.datetime({offset:true}),output:z3.string().min(1)}).parse(await optional(join4(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",projects:g.projects,expiresAt:g.expiresAt});await write(g.output,canonicalLocalJson(connector));renewed++}catch{blocked++}}return{renewed,blocked}}import{randomUUID as randomUUID4}from"node:crypto";import{join as join8}from"node:path";import{z as z6}from"zod";import{z as z4}from"zod";import{join as join5}from"node:path";var slotSchema=z4.strictObject({id:z4.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z4.string().nullable().default(null),files:z4.record(z4.string().min(1).max(100),z4.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z4.strictObject({id:z4.uuid(),planId:z4.uuid(),fingerprint:z4.string().regex(/^[0-9a-f]{64}$/),phase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z4.string().nullable(),failedPhase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z4.strictObject({revision:z4.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z4.strictObject({previous:z4.string().nullable(),value:installationSchema,digest:z4.string().regex(/^[0-9a-f]{64}$/)});var InstallationLedger=class _InstallationLedger{constructor(root){this.root=root}root;static async open(path){const root=await directory(path);for(const name of["revisions","plans","slots","grants"])await directory(join5(root,name));return new _InstallationLedger(root)}async current(){const names=(await entries(join5(this.root,"revisions"))).filter(n=>/^\d{12}\.json$/.test(n)).sort();let previous=null,value={revision:0,active:null,transition:null};for(const[i,name]of names.entries()){const raw=JSON.parse((await read(join5(this.root,"revisions",name),262144,true)).toString());const r=recordSchema.parse(raw);const expected=sha256(canonicalLocalJson({previous:raw.previous,value:raw.value}));if(r.value.revision!==i+1||r.previous!==previous||r.digest!==expected)fail("INSTALLATION_HISTORY_INVALID");previous=r.digest;value=r.value}return{value,digest:previous}}async commit(expected,next){const current=await this.current();if(current.value.revision!==expected.revision)fail("REVISION_CONFLICT");const value=installationSchema.parse({...next,revision:expected.revision+1});const record={previous:current.digest,value,digest:sha256(canonicalLocalJson({previous:current.digest,value}))};try{await write(join5(this.root,"revisions",String(value.revision).padStart(12,"0")+".json"),canonicalLocalJson(record),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return value}slotPath(slot){return join5(this.root,"slots",slot.id)}};import{randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod2}from"node:fs/promises";import{join as join7}from"node:path";import{constants as constants2}from"node:fs";import{open as open3}from"node:fs/promises";import{z as z5}from"zod";var metadataSchema=z5.strictObject({protocol:z5.literal("NVS_PRODUCT_COMPONENT_V1"),version:z5.string().min(1).max(120),byteSize:z5.int().positive().max(64*1024*1024),sha512:z5.string().regex(/^[a-f0-9]{128}$/)});async function regularBytes(url,maximum){const file=await open3(url,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size>maximum)fail("EMBEDDED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let size=0;while(size<bytes.length){const result=await file.read(bytes,size,bytes.length-size,null);if(!result.bytesRead)break;size+=result.bytesRead}if(size!==stat.size)fail("EMBEDDED_COMPONENT_INVALID");return bytes.subarray(0,size)}finally{await file.close()}}async function verifiedEmbeddedAsset(base,release){try{const info=metadataSchema.parse(JSON.parse((await regularBytes(new URL("runtime.json",base),4096)).toString()));if(info.version!==release.descriptor.version)fail("EMBEDDED_RELEASE_MISMATCH");if(info.byteSize!==release.package.byteSize||info.sha512!==release.package.sha512)fail("EMBEDDED_RELEASE_MISMATCH");const bytes=await regularBytes(new URL("runtime.tgz",base),info.byteSize);if(bytes.length!==release.package.byteSize||sha512(bytes)!==release.package.sha512)fail("EMBEDDED_COMPONENT_INVALID");return bytes}catch(error){if(error instanceof Error&&error.message.includes("EMBEDDED_RELEASE_MISMATCH"))throw error;fail("EMBEDDED_COMPONENT_INVALID")}}async function embeddedAsset(release){if(false)return null;if(release.descriptor.version!=="0.3.0-rc.6")return null;if(false)fail("EMBEDDED_COMPONENT_INVALID");const base=new URL("./components/",import.meta.resolve("@nativestudio/cli/package.json"));return verifiedEmbeddedAsset(base,release)}import{gunzipSync}from"node:zlib";import{chmod}from"node:fs/promises";import{join as join6}from"node:path";async function unpack(bytes,root,expectedVersion){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024}),files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0))break;const text=(a,b)=>header.subarray(a,b).toString().replace(/\0.*$/s,"");const number=(a,b)=>{const v=text(a,b).trim();if(!/^[0-7]+$/.test(v))fail("PACKAGE_FORMAT_INVALID");return parseInt(v,8)};const sum=number(148,156);let actual=0;for(let i=0;i<512;i++)actual+=i>=148&&i<156?32:header[i];if(actual!==sum||!text(257,263).startsWith("ustar"))fail("PACKAGE_FORMAT_INVALID");const name=text(0,100),prefix=text(345,500),path=(prefix?prefix+"/":"")+name,size=number(124,136),kind=text(156,157);if(!Number.isSafeInteger(size)||size<0||offset+512+size>data.length)fail("PACKAGE_FORMAT_INVALID");if(kind==="5"){if(!/^package(?:\/dist(?:\/(?:native|captions))?)?\/?$/.test(path))fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowedRuntimeFiles.has(path.slice(8))||files.has(path.slice(8)))fail("PACKAGE_PATH_INVALID");files.set(path.slice(8),data.subarray(offset+512,offset+512+size))}offset+=512+Math.ceil(size/512)*512}if(!requiredRuntimeFiles.every(p=>files.has(p)))fail("PACKAGE_FILES_MISSING");const manifest=JSON.parse(files.get("package.json").toString());const deps=manifest.dependencies;if(manifest.name!=="@nativestudio/local-runtime"||manifest.version!==expectedVersion||manifest.type!=="module"||Object.keys(deps??{}).length||Object.keys(manifest.optionalDependencies??{}).length||["preinstall","install","postinstall","prepare"].some(name=>Object.hasOwn(manifest.scripts??{},name))||!["dist/entry.js","./dist/entry.js"].includes(manifest.bin?.["nvs-runtime"]??"")||Object.keys(manifest.bin??{}).length!==1)fail("PACKAGE_IDENTITY_INVALID");const hashes={};await directory(join6(root,"dist"));if([...files.keys()].some(p=>p.startsWith("dist/native/")))await directory(join6(root,"dist/native"));if([...files.keys()].some(p=>p.startsWith("dist/captions/")))await directory(join6(root,"dist/captions"));for(const[path,contents]of files){await write(join6(root,path),contents,true);await chmod(join6(root,path),path.endsWith("entry.js")?320:256);hashes[path]=sha256(contents)}return hashes}async function stage(ledger,release,origin){const id=randomUUID3(),root=await directory(join7(ledger.root,"slots",id));const bytes=await embeddedAsset(release)??await asset(release.package,origin),files=await unpack(bytes,root,release.descriptor.version);const slot={id,files,descriptor:release.descriptor,toolsConfigPath:null};await probe(root,slot.descriptor);return slot}async function managedTools(release,origin,stateDirectory,selectionId){if(!release.tools)return null;const result={};for(const name of["ffmpeg","ffprobe"]){const a=release.tools[name],dir=await directory(join7(stateDirectory,"tools",a.sha256)),path2=join7(dir,name+(process.platform==="win32"?".exe":""));try{if(sha256(await read(path2,256*1024*1024))!==a.sha256)fail("TOOL_INTEGRITY_INVALID")}catch(e){if(e.code!=="ENOENT")throw e;const bytes=await asset(a,origin);if(sha256(bytes)!==a.sha256)fail("TOOL_INTEGRITY_INVALID");await write(path2,bytes,true);await chmod2(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe};const path=join7(await directory(join7(stateDirectory,"tool-selections")),selectionId+".json");await write(path,JSON.stringify(selection));return path}async function selectedTools(release,origin,state,slotId,cloudConfig,previousSelection,explicit){const preference=await toolPreference(previousSelection,cloudConfig,explicit);if(preference.mode==="INSTALLED"){const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");await write(path,JSON.stringify(preference),true);return path}if(explicit?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");return await managedTools(release,origin,state,slotId)??previousSelection}var configurationSchema=z6.strictObject({stateDirectory:z6.string().min(1).max(4096),catalogueUrl:z6.string().url(),publicKeyFile:z6.string().min(1).max(4096),cloudConfigFile:z6.string().nullable().default(null),notifications:z6.boolean().default(true),rejectedVersions:z6.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])});var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join8(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join8(this.ledger.root,"configuration.json"));if(!value)fail("CONFIGURATION_REQUIRED");return configurationSchema.parse(value)}async status(){const s=(await this.ledger.current()).value;let c;try{c=await this.configuration()}catch(error){if(error instanceof Error&&error.message.includes("CONFIGURATION_REQUIRED"))return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,running:null,phase:s.transition?.phase??"IDLE",nextActions:[{surface:"CLI",operation:"local.configure",availability:"AVAILABLE",reason:"INSTALL_REQUIRED"}]};throw error}let running=null;try{running=await(await ownerClient(c.stateDirectory)).status()}catch{}return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,entryPath:s.active?join8(this.ledger.slotPath(s.active),"dist/entry.js"):null,installOwner:"MANAGED",phase:s.transition?.phase??"IDLE",running,nextActions:[{surface:"CLI",operation:s.transition?"local.update.reconcile":s.active?"local.start":"local.install",availability:"AVAILABLE",reason:s.transition?"RECOVERY_REQUIRED":s.active?"READY":"INSTALL_REQUIRED"}]}}async reject(version){LocalRuntimeDescriptorSchema.shape.version.parse(version);const c=await this.configuration();await this.configure({...c,rejectedVersions:[...new Set([...c.rejectedVersions,version])]});return{rejected:true,version,selectedVersion:(await this.ledger.current()).value.active?.descriptor.version??null}}async check(){const c=await this.configuration(),v=await catalogue(c);return{installation:await this.status(),catalogueFingerprint:v.fingerprint,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),notifications:c.notifications,rejectedVersions:c.rejectedVersions}}prepare(version,choice){return prepareInstallation(this,version,choice)}async plan(id){if(!z6.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join8(this.ledger.root,"plans",id+".json"))).toString()));const{fingerprint,...body}=p;if(sha256(canonicalLocalJson(body))!==fingerprint)fail("PLAN_CHANGED");return p}async transition(s,phase,patch={}){if(!s.transition)fail("TRANSITION_REQUIRED");return this.ledger.commit(s,{active:s.active,transition:{...s.transition,...patch,phase}})}async apply(id,approval){const plan=await this.plan(id),c=await this.configuration();if(approval!==plan.fingerprint)fail("USER_APPROVAL_REQUIRED");const trusted=await catalogue(c);if(Date.parse(plan.expiresAt)<=Date.now()||plan.trustFingerprint!==trusted.trustFingerprint||canonicalLocalJson(select(trusted.signed,plan.release.descriptor.version))!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");let s=(await this.ledger.current()).value;if(s.revision!==plan.installationRevision||s.transition)fail("REVISION_CONFLICT");if(plan.runtimeRevision!==null){const i=await(await ownerClient(c.stateDirectory)).inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(plan.release.descriptor,d)))fail("REVISION_CONFLICT")}if(plan.runtimeRevision===null){if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory)}s=await this.ledger.commit(s,{active:s.active,transition:{id:randomUUID4(),planId:id,fingerprint:approval,phase:"STAGING",previous:s.active,candidate:null,backupPath:null,failedPhase:null}});try{let candidate=await stage(this.ledger,plan.release,trusted.origin);const tools=await selectedTools(plan.release,trusted.origin,c.stateDirectory,candidate.id,c.cloudConfigFile,s.active?.toolsConfigPath??null,plan.toolSelection);candidate={...candidate,toolsConfigPath:tools};if(tools)await probeTools(this.ledger.slotPath(candidate),c.stateDirectory,tools);s=await this.transition(s,"STAGED",{candidate});if(plan.runtimeRevision!==null){const client=await ownerClient(c.stateDirectory),i=await client.inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(candidate.descriptor,d)))fail("REVISION_CONFLICT");await assertPendingCompatible(i,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile);s=await this.transition(s,"DRAINING");const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:plan.runtimeRevision});if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,c.stateDirectory);s=await this.transition(s,"ACTIVATING",{backupPath:result.backupPath});await waitStopped(c.stateDirectory);await assertPendingCompatible("inventory"in result?result.inventory:null,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile)}else{if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory);s=await this.transition(s,"ACTIVATING")}s=await this.ledger.commit(s,{active:candidate,transition:{...s.transition,phase:"VERIFYING"}});await this.startSlot(candidate,c);s=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{activated:true,revision:s.revision,version:candidate.descriptor.version}}catch(error){const actual=(await this.ledger.current()).value;if(actual.transition?.planId===id)await this.transition(actual,"ROLLBACK_REQUIRED",{failedPhase:actual.transition.phase});throw error}}async startSlot(slot,c){return launch(this.ledger.slotPath(slot),slot,c.stateDirectory,c.cloudConfigFile??void 0,slot.toolsConfigPath??void 0)}async start(){const s=(await this.ledger.current()).value;if(s.transition)fail("ACTIVATION_IN_PROGRESS");if(!s.active)fail("INSTALL_REQUIRED");const c=await this.configuration(),inventory=await this.startSlot(s.active,c);const clients=await this.reconnect();let updateNotice={status:"DISABLED"};if(c.notifications){try{const v=await catalogue(c,AbortSignal.timeout(1500));updateNotice={status:"CHECKED",versions:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&newerVersion(r.descriptor.version,s.active.descriptor.version)&&!c.rejectedVersions.includes(r.descriptor.version)).map(r=>r.descriptor.version)}}catch{updateNotice={status:"UNAVAILABLE"}}}return{...inventory,clients,updateNotice}}async stop(){const c=await this.configuration(),client=await ownerClient(c.stateDirectory),i=await client.inventory();const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:i.runtimeRevision});await waitStopped(c.stateDirectory);return result}async reconcile(id,approval){const s=(await this.ledger.current()).value,c=await this.configuration();if(!s.transition||s.transition.planId!==id||s.transition.fingerprint!==approval)fail("USER_APPROVAL_REQUIRED");if(s.active?.id===s.transition.previous?.id&&["STAGING","STAGED"].includes(s.transition.failedPhase??s.transition.phase)){const next2=await this.ledger.commit(s,{active:s.transition.previous,transition:null});return{rolledBack:true,revision:next2.revision,version:next2.active?.descriptor.version??null}}const candidate=s.transition.candidate;if(candidate){try{const i=await runningInventory(await ownerClient(c.stateDirectory),this.ledger.slotPath(candidate),candidate);if(canonicalLocalJson(i.descriptor)===canonicalLocalJson(candidate.descriptor)){await verifySlot(this.ledger.slotPath(candidate),candidate);const next2=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{recovered:true,revision:next2.revision,version:candidate.descriptor.version}}}catch{}}await waitStopped(c.stateDirectory);const previous=s.transition.previous;const next=await this.ledger.commit(s,{active:previous,transition:null});if(previous)await this.startSlot(previous,c);await this.reconnect();return{rolledBack:true,revision:next.revision,version:previous?.descriptor.version??null}}grant(raw,output){return grant(this,raw,output)}reconnect(){return reconnect(this)}};export{toolPreference,captureInstalledTools,generateDeviceKey,connectDevice,ownerClient,waitStopped,socketAbsent,newerVersion,LocalInstallationManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalMcpOutputSchemas,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-RVGDXRPK.js";import{fail,optional}from"./chunk-KB2GVAN7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";import{join}from"node:path";var localTools={local_navigate:{description:"Local execution entry. Discover Project-scoped Runtime progress, recovery and updates. Native writes remain with the cloud owner.",input:z.strictObject({intent:z.string().max(500).optional()})},local_capability_describe:{description:"Inspect the exact public schema for a local capability. Standard discovery stays stable; each call validates current Runtime authority.",input:z.strictObject({tool:z.enum(["local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"])})},local_runtime_status:{description:"Read current authorized local Runtime status. Does not start, stop or mutate native work.",input:z.strictObject({})},local_execution_list:{description:"List a bounded page of pending local execution identities in one authorized Project, then inspect an exact native Job.",input:LocalExecutionListInputSchema},local_execution_inspect:{description:"Inspect one exact native Job in the authorized Project. Native Job/Attempt identity remains authoritative.",input:LocalExecutionInspectInputSchema},local_update_check:{description:"Read signed compatible release metadata only. No executable download, approval, installation or restart.",input:z.strictObject({})}};var LocalMcpTools=class _LocalMcpTools{constructor(client,home,renders){this.client=client;this.home=home;this.renders=renders}client;home;renders;static async open(connector,home,renderTools){const client=await NativeStudioLocalRuntimeClient.fromConnector(connector);return new _LocalMcpTools(client,home,renderTools?await renderTools(client):void 0)}schema(name){return{name,description:localTools[name].description,inputSchema:z.toJSONSchema(localTools[name].input,{io:"input"}),outputSchema:z.toJSONSchema(LocalMcpOutputSchemas[name],{io:"input"}),annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:name==="local_update_check"}}}async call(name,raw,signal){return LocalMcpOutputSchemas[name].parse(await this.invoke(name,raw,signal))}async invoke(name,raw,signal){const input=localTools[name].input.parse(raw);if(name==="local_capability_describe")return{location:"LOCAL",tool:input.tool,schema:this.schema(input.tool)};if(name==="local_navigate"){let status;try{status=await this.client.status(signal)}catch{return{location:"LOCAL",state:"UNAVAILABLE",groups:[],nextActions:[{surface:"CLI",operation:"local.grant",availability:"BLOCKED",reason:"AUTHORIZATION_REQUIRED"}]}}return{location:"LOCAL",state:status.state,authorizedProjects:status.authorizedProjects,groups:[{id:"execution",label:"Local execution and recovery",tools:["local_runtime_status","local_execution_list","local_execution_inspect"]},{id:"versions",label:"Versions and updates",tools:["local_update_check"]}],nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"},availability:"AVAILABLE",reason:"READY"},...status.state==="RECOVERY_REQUIRED"?[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:"RECOVERY_REQUIRED"}]:[]]}}if(name==="local_runtime_status")return{...await this.client.status(signal),nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"}}]};if(name==="local_execution_list"){const page=await this.client.executions(LocalExecutionListInputSchema.parse(input),signal);return{...page,nextActions:page.items.map(item=>({tool:"local_execution_inspect",arguments:{tenantId:item.binding.tenantId,projectId:item.binding.projectId,productionId:item.binding.productionId,runtimeJobId:item.binding.runtimeJobId}}))}}if(name==="local_execution_inspect")return{location:"LOCAL",execution:await this.client.inspect(LocalExecutionInspectInputSchema.parse(input),signal),nextActions:[]};if(name==="local_update_check"){const current=await this.client.status(signal);if(!current.authorizedProjects.length)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const raw2=await optional(join(this.home,"configuration.json"));const config=z.object({catalogueUrl:z.string().url(),publicKeyFile:z.string()}).parse(raw2);const v=await catalogue(config,signal);return{location:"LOCAL",running:current.versions,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),nextActions:[{surface:"CLI",operation:"local.update.prepare",availability:"BLOCKED",reason:"USER_APPROVAL_REQUIRED"}]}}fail("CAPABILITY_UNAVAILABLE")}};export{localTools,LocalMcpTools};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LocalDeviceGrantSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-RVGDXRPK.js";import{directory,entries,fail,read,sha256,write}from"./chunk-KB2GVAN7.js";import{z}from"zod";var DesktopDeviceScopeSchema=z.strictObject({origin:z.url().refine(value=>{const u=new URL(value);return u.origin===value&&(u.protocol==="https:"||u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname))}),tenantId:z.uuid(),principalId:z.uuid()});var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest,projectIds:z.array(z.uuid()).min(1).max(20)}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120)}),z.strictObject({action:z.literal("grant"),projectId:z.uuid(),expiresAt:z.iso.datetime(),executionPolicy:z.literal("DEVICE_ONLY").optional(),capability:z.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2"]).optional()}),z.strictObject({action:z.literal("revoke"),projectId:z.uuid()}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),grants:z.array(LocalDeviceGrantSchema).max(20),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),projects:z.array(z.strictObject({tenantId:z.uuid(),projectId:z.uuid()})).min(1).max(20)}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"])}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120)}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","GRANT","REVOKE_GRANT","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional()});import{join}from"node:path";var DesktopDeviceRecords=class _DesktopDeviceRecords{constructor(root,scope){this.root=root;this.scope=scope}root;scope;static async open(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);return new _DesktopDeviceRecords(await directory(join(home,"devices",sha256(canonicalLocalJson(scope)))),scope)}async current(){const names=(await entries(this.root)).filter(n=>/^\d{12}\.json$/.test(n)).sort();let state={revision:0,scope:this.scope,enrollment:null,device:null,grants:[],previews:[],connectorId:null,connection:null,pending:null};for(const[index,name]of names.entries()){const next=DesktopDeviceStateSchema.parse(JSON.parse((await read(join(this.root,name),262144,true)).toString()));if(next.revision!==index+1||canonicalLocalJson(next.scope)!==canonicalLocalJson(this.scope))fail("DEVICE_HISTORY_INVALID");state=next}return state}async save(before,fields){if((await this.current()).revision!==before.revision)fail("REVISION_CONFLICT");const next=DesktopDeviceStateSchema.parse({...before,...fields,revision:before.revision+1});try{await write(join(this.root,String(next.revision).padStart(12,"0")+".json"),canonicalLocalJson(next),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}keyPath(){return join(this.root,"device-key.json")}connectorPath(id){return join(this.root,id+".connector.json")}};async function desktopDeviceConnector(home,scope){const records=await DesktopDeviceRecords.open(home,scope),state=await records.current();if(!state.connectorId)fail("LOCAL_AUTHORIZATION_REQUIRED");return records.connectorPath(state.connectorId)}export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceReplySchema,DesktopDeviceRecords,desktopDeviceConnector};
|