@nativestudio/cli 0.3.0-rc.1 → 0.3.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMPATIBILITY.json +7 -7
- package/README.md +19 -2
- package/components/runtime.json +3 -3
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-GIEYSDCG.js → chunk-66CUOZVI.js} +1 -1
- package/dist/_chunks/{chunk-MSOMVWKN.js → chunk-7S3DJ2QE.js} +1 -1
- package/dist/_chunks/{chunk-25EDDZQA.js → chunk-BVSTJQJI.js} +1 -1
- package/dist/_chunks/{chunk-G42IS5JF.js → chunk-C33A2DW4.js} +1 -1
- package/dist/_chunks/{chunk-RUMDDTON.js → chunk-C753RRRA.js} +1 -1
- package/dist/_chunks/chunk-K6LVS2IN.js +1 -0
- package/dist/_chunks/chunk-KHKUJXQX.js +1 -0
- package/dist/_chunks/{chunk-QC7RLTGU.js → chunk-VC3ODN3M.js} +1 -1
- package/dist/_chunks/{files-TBJVDQWU.js → files-FZEK2ZZJ.js} +1 -1
- package/dist/_chunks/local-main-NLFS74Q4.js +1 -0
- package/dist/_chunks/{local-mcp-JLPXXIDW.js → local-mcp-OLHBBVNN.js} +1 -1
- package/dist/_chunks/{main-4SNF5EKE.js → main-VRIQTI6R.js} +2 -2
- package/dist/_chunks/oauth-F7EZGVME.js +1 -0
- package/dist/_chunks/{project-connect-6MH2QG6G.js → project-connect-MXM7IY55.js} +1 -1
- package/dist/_chunks/{stdio-main-JEADWO7U.js → stdio-main-KOGQ5OWF.js} +1 -1
- package/dist/_types/cli/local/desktop-contract.d.ts +73 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +2 -0
- package/dist/_types/cli/local/manager.d.ts +30 -2
- package/dist/_types/cli/local/mcp-tools.d.ts +2 -2
- package/dist/_types/cli/local/releases.d.ts +1 -0
- package/dist/_types/cli/local-management.d.ts +1 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +3 -3
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +28 -0
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +3 -3
- package/dist/_types/sdk/local-runtime-client.d.ts +4 -4
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/package.json +1 -1
- package/dist/_chunks/chunk-EAZKDCLD.js +0 -1
- package/dist/_chunks/chunk-U2UKGYGF.js +0 -1
- package/dist/_chunks/local-main-SOERK22D.js +0 -1
- package/dist/_chunks/oauth-257CEUQH.js +0 -1
package/dist/local-management.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalInstallationManager,socketAbsent}from"./_chunks/chunk-U2UKGYGF.js";import{LocalRuntimeDescriptorSchema,canonicalLocalJson,endpoint}from"./_chunks/chunk-EAZKDCLD.js";import"./_chunks/chunk-HLKERZIE.js";import"./_chunks/chunk-VPYAXWXY.js";import{LocalClientError,directory,fail,read,sha256,write}from"./_chunks/chunk-GIEYSDCG.js";import"./_chunks/chunk-6NVIN2NI.js";import{z}from"zod";var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z.string().url().max(4096),publicKey:z.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z.discriminatedUnion("operation",[z.strictObject({operation:z.enum(["status","start","stop","check","configuration","recovery"])}),z.strictObject({operation:z.enum(["prepare","reject"]),version}),z.strictObject({operation:z.literal("configure"),channelFingerprint:fingerprint}),z.strictObject({operation:z.enum(["apply","recover"]),planId:z.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z.string().regex(/^[A-Z_]{1,64}$/)});var DesktopUpdateCheckSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z.array(z.strictObject({version,rejected:z.boolean()})).max(128),notifications:z.boolean()});var DesktopOwnerPlanSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z.strictObject({kind:z.enum(["APPLY","RECOVER"]),planId:z.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z.iso.datetime(),phase:z.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z.boolean(),source:z.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase})}import{createPublicKey}from"node:crypto";import{join}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED"))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;const stateDirectory=join(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop")await manager.stop();result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"prepare":{const plan=await manager.prepare(request.version);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat,readFile,chmod}from"node:fs/promises";import{join as join2,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join2(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join2(await directory(home),"nodes",expected)),target=join2(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join2(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopOwnerRequestSchema,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,runDesktopOwnerRequest,runLocalManagement};
|
|
1
|
+
import{LocalInstallationManager,captureInstalledTools,socketAbsent,toolPreference}from"./_chunks/chunk-K6LVS2IN.js";import{LocalRuntimeDescriptorSchema,canonicalLocalJson,endpoint}from"./_chunks/chunk-KHKUJXQX.js";import"./_chunks/chunk-HLKERZIE.js";import"./_chunks/chunk-VPYAXWXY.js";import{LocalClientError,directory,fail,read,sha256,write}from"./_chunks/chunk-66CUOZVI.js";import"./_chunks/chunk-6NVIN2NI.js";import{z}from"zod";var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z.string().url().max(4096),publicKey:z.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z.discriminatedUnion("operation",[z.strictObject({operation:z.enum(["status","start","stop","check","configuration","recovery"])}),z.strictObject({operation:z.enum(["prepare","reject"]),version}),z.strictObject({operation:z.literal("tools-prepare"),version,choice:z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("MANAGED")}),z.strictObject({mode:z.literal("INSTALLED"),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096)})])}),z.strictObject({operation:z.literal("configure"),channelFingerprint:fingerprint}),z.strictObject({operation:z.enum(["apply","recover"]),planId:z.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z.string().regex(/^[A-Z_]{1,64}$/),toolMode:z.enum(["MANAGED","INSTALLED"]).nullable().optional()});var DesktopUpdateCheckSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z.array(z.strictObject({version,rejected:z.boolean()})).max(128),notifications:z.boolean()});var DesktopOwnerPlanSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z.strictObject({kind:z.enum(["APPLY","RECOVER"]),toolMode:z.enum(["MANAGED","INSTALLED"]).optional(),planId:z.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z.iso.datetime(),phase:z.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z.boolean(),source:z.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"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}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED"))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;const stateDirectory=join(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop")await manager.stop();result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"prepare":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,readFile,chmod}from"node:fs/promises";import{join as join2,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join2(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join2(await directory(home),"nodes",expected)),target=join2(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join2(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopOwnerRequestSchema,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,runDesktopOwnerRequest,runLocalManagement};
|
package/dist/local-navigation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalMcpTools}from"./_chunks/chunk-
|
|
1
|
+
import{LocalMcpTools}from"./_chunks/chunk-VC3ODN3M.js";import"./_chunks/chunk-KHKUJXQX.js";import"./_chunks/chunk-HLKERZIE.js";import"./_chunks/chunk-VPYAXWXY.js";import"./_chunks/chunk-66CUOZVI.js";import"./_chunks/chunk-6NVIN2NI.js";export{LocalMcpTools};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{KeyframeObservationSchema,NativeRuntimePublicKeySchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RoughCutAdmissionSchema,RoughCutManifestReaderSchema,RoughCutStartSchema,RoughCutTechnicalSchema,ValidateReviewIntelligenceSchema,VisualRequirementSchema}from"./chunk-HLKERZIE.js";import{OperationIdSchema}from"./chunk-VPYAXWXY.js";import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-GIEYSDCG.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z as z2}from"zod";import{z}from"zod";var LocalIdSchema=z.uuid().transform(v=>v.toLowerCase());var LocalDigestSchema=z.string().length(64).regex(/^[0-9a-f]{64}$/);var LocalRevisionSchema=z.int().positive();var LocalTimeSchema=z.iso.datetime({offset:true});var LocalPackageVersionSchema=z.string().max(120).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/).refine(v=>v===v.trim());var LocalProjectScopeSchema=z.strictObject({tenantId:LocalIdSchema,projectId:LocalIdSchema});var LocalWorkScopeSchema=LocalProjectScopeSchema.extend({productionId:LocalIdSchema,runtimeJobId:LocalIdSchema});var LocalPlacementPolicySchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("local-only"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("local-preferred"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("cloud-only")})]);var LocalPlacementAvailabilitySchema=z.discriminatedUnion("status",[z.strictObject({status:z.literal("AVAILABLE"),deviceId:LocalIdSchema}),z.strictObject({status:z.literal("UNAVAILABLE"),deviceId:LocalIdSchema,reason:z.enum(["OFFLINE","UNQUALIFIED","BUSY"])}),z.strictObject({status:z.literal("DENIED"),reason:z.enum(["FORBIDDEN","APPROVAL_REQUIRED","INVALID_INPUT"])})]);var LocalDevicePlatformSchema=z2.strictObject({os:z2.enum(["darwin","linux","win32"]),architecture:z2.enum(["x64","arm64"])});var EnrollLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,requestId:LocalIdSchema,label:z2.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema,publicKey:NativeRuntimePublicKeySchema});var LocalDeviceViewSchema=EnrollLocalDeviceSchema.omit({requestId:true}).extend({deviceId:LocalIdSchema,revision:LocalRevisionSchema,enrolledByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable()}).refine(v=>[v.verifiedAt,v.revokedAt].every(time=>time===null||Date.parse(time)>=Date.parse(v.createdAt)));var LocalDeviceChallengeSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>{const ttl=Date.parse(v.expiresAt)-Date.parse(v.issuedAt);return ttl>0&&ttl<=3e5});var LocalDeviceProofClaimsSchema=z2.strictObject({protocol:z2.literal("NVS_LOCAL_DEVICE_PROOF_V1"),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),jti:LocalIdSchema,iat:z2.int().nonnegative(),exp:z2.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var ProveLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,assertion:z2.string().max(4096).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var GrantLocalDeviceSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,expectedRevision:z2.int().nonnegative(),expiresAt:LocalTimeSchema,capability:z2.literal("ROUGH_CUT_PREVIEW_V1")});var LocalDeviceGrantSchema=GrantLocalDeviceSchema.omit({requestId:true,expectedRevision:true}).extend({grantId:LocalIdSchema,revision:LocalRevisionSchema,approvedByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,revokedAt:LocalTimeSchema.nullable()}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.createdAt));var RevokeLocalDeviceGrantSchema=LocalProjectScopeSchema.extend({grantId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});var RevokeLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});import{z as z4}from"zod";import{z as z3}from"zod";var LocalExecutionProfileSchema=z3.strictObject({kind:z3.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z3.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var LocalToolchainSchema=z3.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z3.strictObject({version:z3.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z3.strictObject({version:z3.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema});var LocalFrozenWorkSchema=LocalWorkScopeSchema.extend({protocol:z3.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z3.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:LocalExecutionProfileSchema,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z3.array(z3.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z3.int().positive(),contentType:z3.string().min(1).max(100)})).min(1).max(512)}).superRefine((v,ctx)=>{const t=v.manifest.timeline;if(t.tenantId!==v.tenantId||t.projectId!==v.projectId||t.productionId!==v.productionId||t.executionClass!==v.executionClass)ctx.addIssue({code:"custom",message:"Frozen manifest scope/class mismatch"});if(new Set(v.sources.map(s=>s.representationId)).size!==v.sources.length)ctx.addIssue({code:"custom",message:"Duplicate source representation"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z3.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=z3.discriminatedUnion("kind",[z3.strictObject({kind:z3.literal("DEVICE"),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,grantId:LocalIdSchema,grantRevision:LocalRevisionSchema}),z3.strictObject({kind:z3.literal("SERVER")})]);var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z3.strictObject({work:LocalFrozenWorkSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema}).superRefine(({work,lease,toolchain},ctx)=>{if(["tenantId","projectId","productionId","runtimeJobId"].some(k=>work[k]!==lease[k]))ctx.addIssue({code:"custom",message:"Assignment work scope mismatch"});const p=work.policy,t=lease.target;if(p.mode==="cloud-only"&&t.kind!=="SERVER"||p.mode==="local-only"&&t.kind!=="DEVICE"||t.kind==="DEVICE"&&(p.mode==="cloud-only"||p.deviceId!==t.deviceId))ctx.addIssue({code:"custom",message:"Assignment contradicts placement policy"});if(work.profile.contractDigest!==toolchain.profile.contractDigest)ctx.addIssue({code:"custom",message:"Unqualified execution profile"})});var StartLocalPreviewSchema=RoughCutStartSchema.extend({placement:LocalPlacementPolicySchema});var LocalDeviceScopeSchema=z4.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z4.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z4.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z4.boolean()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z4.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z4.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z4.strictObject({receiptId:LocalIdSchema,role:z4.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z4.int().positive(),uploaded:z4.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z4.int().positive()});var LocalPreviewPlacementViewSchema=z4.strictObject({target:z4.enum(["DEVICE","SERVER"]),reason:z4.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z4.strictObject({endpoint:z4.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z4.int().positive(),projects:z4.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z4.string().min(1).max(4096),platform:LocalDevicePlatformSchema});var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z4.strictObject({found:z4.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z4.strictObject({binding:LocalLeaseBindingSchema,status:z4.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z8}from"zod";import{z as z5}from"zod";var LocalRuntimeDescriptorSchema=z5.strictObject({protocol:z5.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z5.strictObject({major:z5.literal(24),minMinor:z5.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z5.literal("NVS_LOCAL_IPC_V1"),workProtocol:z5.literal("NVS_LOCAL_WORK_V1"),journalSchema:z5.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema});var LocalSessionConnectorSchema=z5.strictObject({protocol:z5.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z5.string().min(1).max(4096),credential:z5.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z5.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z5.strictObject({runtimeRevision:z5.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z5.int().nonnegative(),pendingExecutions:z5.int().nonnegative(),pendingRequests:z5.int().nonnegative(),pendingRenderers:z5.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z5.strictObject({url:z5.string().url().max(2048),byteSize:z5.int().positive().max(256*1024*1024),sha512:z5.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z5.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z5.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z5.strictObject({protocol:z5.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z5.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z5.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z5.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalUpdatePlanSchema=z5.strictObject({protocol:z5.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z5.int().nonnegative(),runtimeRevision:z5.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,release:LocalReleaseSchema,fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z5.strictObject({surface:z5.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z5.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z5.enum(["AVAILABLE","BLOCKED"]),reason:z5.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z7}from"zod";import{z as z6}from"zod";function canonicalLocalJson(value){if(value===null||typeof value==="string"||typeof value==="boolean")return JSON.stringify(value);if(typeof value==="number"&&Number.isFinite(value))return JSON.stringify(value);if(Array.isArray(value))return"["+value.map(canonicalLocalJson).join(",")+"]";if(typeof value==="object")return"{"+Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>JSON.stringify(k)+":"+canonicalLocalJson(v)).join(",")+"}";throw new Error("Fingerprint input must be finite JSON data")}var sha=z6.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=z6.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z6.strictObject({protocol:z6.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z6.string().min(1).max(4096).startsWith("/"),binaryDigest:sha,version:qualifiedVersion,model:z6.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z6.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z6.string().trim().min(1).max(100),inference:z6.literal("REMOTE_OPENAI"),remoteUseApproved:z6.literal(true),imageDisclosureApproved:z6.literal(true).optional(),projects:z6.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z6.iso.datetime({offset:true})});var LocalAgentSnapshotSchema=z6.strictObject({basis:ReviewIntelligenceBasisSchema.extend({target:z6.strictObject({kind:z6.literal("IMAGE"),generationId:z6.uuid()})}),productionRevision:z6.int().positive(),reviewVersion:z6.int().nonnegative(),executionClass:z6.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z6.array(VisualRequirementSchema).min(1).max(64),image:z6.strictObject({contentType:z6.literal("image/png"),byteSize:z6.int().positive().max(8388608),width:z6.int().positive().max(4096),height:z6.int().positive().max(4096)}).optional()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z6.strictObject({configured:z6.boolean(),available:z6.boolean(),reason:z6.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha.nullable(),inference:z6.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_AGENT_REVIEW_V1"),id:z6.uuid(),grantFingerprint:sha,snapshot:LocalAgentSnapshotSchema,expiresAt:z6.iso.datetime({offset:true}),fingerprint:sha});var LocalAgentMetadataAnswerSchema=z6.strictObject({summary:z6.string().trim().min(1).max(1500),observations:z6.array(z6.strictObject({key:z6.string().min(1).max(200),observed:z6.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z6.strictObject({summary:z6.string().trim().min(1).max(1500),imageReadback:z6.string().trim().min(1).max(800),observations:z6.array(KeyframeObservationSchema.omit({region:true})).min(1).max(64)});var LocalAgentAnswerSchema=z6.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z6.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z6.int().positive().max(8388608),contentType:z6.literal("image/png"),width:z6.int().positive().max(4096),height:z6.int().positive().max(4096)});var LocalAgentReviewViewSchema=z6.strictObject({plan:LocalAgentPlanSchema,revision:z6.int().positive(),phase:z6.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),provenance:z6.strictObject({adapter:z6.literal("CODEX_METADATA_V1"),binaryDigest:sha,version:qualifiedVersion,model:z6.string().max(100),reasoningEffort:z6.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z6.string().max(100),inference:z6.literal("REMOTE_OPENAI"),evidence:z6.enum(["METADATA_ONLY","IMAGE_PIXELS"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;if(v.answer&&!!image!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!image;return v.provenance.evidence===(pixels?"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||!!receipt)});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var projectInput=LocalProjectScopeSchema;var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z7.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z7.int().min(1).max(16).default(8)});var LocalIpcCallSchema=z7.discriminatedUnion("operation",[z7.strictObject({operation:z7.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z7.string().regex(/^[a-f0-9]{64}$/)}),z7.strictObject({operation:z7.literal("agent.probe")}),z7.strictObject({operation:z7.literal("agent.revoke"),approval:z7.string().regex(/^[a-f0-9]{64}$/)}),z7.strictObject({operation:z7.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z7.strictObject({operation:z7.literal("agent.start"),id:z7.uuid(),expectedRevision:LocalRevisionSchema,approval:z7.string().regex(/^[a-f0-9]{64}$/)}),z7.strictObject({operation:z7.literal("agent.inspect"),id:z7.uuid()}),z7.strictObject({operation:z7.literal("runtime.status")}),z7.strictObject({operation:z7.literal("runtime.doctor")}),z7.strictObject({operation:z7.literal("runtime.inventory")}),z7.strictObject({operation:z7.literal("session.issue"),projects:z7.array(projectInput).min(1).max(100),expiresAt:z7.iso.datetime({offset:true})}),z7.strictObject({operation:z7.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z7.strictObject({operation:z7.literal("execution.inspect"),input:LocalWorkScopeSchema}),z7.strictObject({operation:z7.literal("execution.list"),input:LocalExecutionListInputSchema}),z7.strictObject({operation:z7.literal("update.check")}),z7.strictObject({operation:z7.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z7.strictObject({operation:z7.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z7.strictObject({call:LocalIpcCallSchema,availability:z7.enum(["AVAILABLE","BLOCKED"]),reason:z7.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z7.strictObject({component:z7.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z7.string().min(1).max(4096).nullable(),installOwner:z7.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z7.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z7.literal(1),workProtocols:z7.array(z7.literal("NVS_LOCAL_WORK_V1")).min(1).max(1),versions:z7.array(LocalVersionReportSchema).max(8),authorizedProjects:z7.array(projectInput).max(100),nextActions:z7.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z7.strictObject({mode:z7.enum(["MANAGED","INSTALLED"]),availability:z7.enum(["AVAILABLE","UNAVAILABLE"]),reason:z7.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z7.boolean(),tools:z7.array(z7.strictObject({name:z7.enum(["FFMPEG","FFPROBE"]),path:z7.string().min(1).max(4096),version:z7.string().min(1).max(200),digest:z7.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z7.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z7.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z7.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"])});var LocalExecutionPageSchema=z7.strictObject({items:z7.array(LocalExecutionInspectionSchema).max(16),nextCursor:z7.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z7.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED"]);var LocalIpcResponseSchema=z7.discriminatedUnion("semanticStatus",[z7.strictObject({protocol:z7.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z7.literal("SUCCESS"),data:z7.union([LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z7.strictObject({state:z7.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z7.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema])}),z7.strictObject({protocol:z7.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z7.enum(["BLOCKED","INVALID_INPUT"]),error:z7.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z8.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"]);var LocalMcpActionSchema=z8.strictObject({tool:LocalMcpToolNameSchema,arguments:z8.record(z8.string(),z8.unknown()),availability:z8.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z8.string().max(100).optional()});var LocalMcpNavigationSchema=z8.strictObject({location:z8.literal("LOCAL"),state:z8.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),authorizedProjects:z8.array(LocalProjectScopeSchema).max(100).optional(),groups:z8.array(z8.strictObject({id:z8.string().max(40),label:z8.string().max(100),tools:z8.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z8.array(z8.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z8.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z8.strictObject({location:z8.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z8.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z8.strictObject({location:z8.literal("LOCAL"),running:z8.array(LocalVersionReportSchema).max(8),available:z8.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z8.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z8.strictObject({location:z8.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z8.object({name:LocalMcpToolNameSchema,description:z8.string(),inputSchema:z8.record(z8.string(),z8.unknown())}).passthrough()});var LocalMcpFailureSchema=z8.strictObject({semanticStatus:z8.enum(["BLOCKED","INVALID_INPUT"]),error:z8.strictObject({code:z8.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z8.literal("NO_WRITE")}),nextActions:z8.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z8.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z11}from"zod";function localBudget(timeoutMs,parent){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>6e4)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}import{z as z9}from"zod";var output=z9.discriminatedUnion("role",[z9.strictObject({role:z9.literal("VIDEO"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z9.int().positive().max(128*1024*1024),contentType:z9.literal("video/mp4")}),z9.strictObject({role:z9.literal("POSTER"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z9.int().positive().max(2*1024*1024),contentType:z9.literal("image/png")})]);var LocalCompletionSubmissionSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputs:z9.array(output).length(2),technical:RoughCutTechnicalSchema}).superRefine((v,ctx)=>{const video=v.outputs.find(o=>o.role==="VIDEO");if(new Set(v.outputs.map(o=>o.role)).size!==2||new Set(v.outputs.map(o=>o.receiptId)).size!==2||!video||video.checksumSha256!==v.technical.checksumSha256||video.byteSize!==v.technical.byteSize)ctx.addIssue({code:"custom",message:"Exact video/poster receipts required"})});var LocalVerifiedUploadSchema=z9.strictObject({binding:LocalLeaseBindingSchema,output,verifiedAt:LocalTimeSchema});var LocalCompletionReceiptSchema=LocalLeaseBindingSchema.extend({submissionFingerprint:LocalDigestSchema.optional(),semanticStatus:z9.literal("SUCCESS"),requestId:LocalIdSchema,renderId:LocalIdSchema,operationId:OperationIdSchema,artifactId:LocalIdSchema,videoRepresentationId:LocalIdSchema,posterRepresentationId:LocalIdSchema,checksumSha256:LocalDigestSchema,acceptedAt:LocalTimeSchema});var GetLocalCompletionReceiptSchema=LocalLeaseBindingSchema.pick({tenantId:true,projectId:true,productionId:true,runtimeJobId:true}).extend({requestId:LocalIdSchema});import{z as z10}from"zod";var executable=z10.strictObject({path:z10.string().min(1).max(4096),digest:LocalDigestSchema});var LocalToolSelectionSchema=z10.strictObject({mode:z10.enum(["MANAGED","INSTALLED"]),ffmpeg:executable,ffprobe:executable});var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output2,signal){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if(i.tenantId!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json"},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output2.parse(JSON.parse(Buffer.concat(parts).toString()));if(value&&typeof value==="object"){const result=value,request3=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request3&&result[key]!==request3[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal)}grant(input,signal){return this.command("devices/grant",input,GrantLocalDeviceSchema,LocalDeviceGrantSchema,signal)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z11.strictObject({semanticStatus:z11.literal("SUCCESS")}),signal)}revokeGrant(input,signal){return this.command("devices/revoke-grant",input,RevokeLocalDeviceGrantSchema,z11.strictObject({semanticStatus:z11.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z12}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(options.timeoutMs??1e4,signal);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>8388608)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z12.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image||bytes.length!==snapshot.image.byteSize||bytes.length>8388608||createHash("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}import{randomUUID as randomUUID2}from"node:crypto";import{request as request2}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,projects:initial.projects,authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||canonicalLocalJson(current.projects)!==canonicalLocalJson(initial.projects)||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:1e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.inspect"].includes(call.operation);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request2({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status"},signal));if(this.options.projects&&value.authorizedProjects.some(p=>!this.options.projects.some(q=>q.tenantId===p.tenantId&&q.projectId===p.projectId)))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(this.options.timeoutMs??1e4,signal);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===i.tenantId&&p.projectId===i.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalWorkScopeSchema.parse(raw);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===input.tenantId&&p.projectId===input.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");const r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream"}});if(!r.ok||Number(r.headers.get("content-length"))>maximum){await r.body?.cancel();fail("RELEASE_UNAVAILABLE")}const parts=[];let size=0;for await(const part of r.body??[]){size+=part.byteLength;if(size>maximum){await r.body?.cancel().catch(()=>{});fail("RELEASE_LIMIT")}parts.push(part)}return Buffer.concat(parts)}async function catalogue(trust,signal){const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));const signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()));const key=createPublicKey((await read(trust.publicKeyFile,16384)).toString());if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin}}function select(signed,version){const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{LocalWorkScopeSchema,EnrollLocalDeviceSchema,GrantLocalDeviceSchema,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,LocalRuntimeDescriptorSchema,LocalManagementInventorySchema,LocalUpdatePlanSchema,canonicalLocalJson,LocalAgentGrantSchema,localAgentSnapshotFromContext,localAgentNativeProposal,LocalExecutionListInputSchema,LocalDoctorReportSchema,StartLocalPreviewSchema,LocalDeviceTransportConfigurationSchema,LocalToolSelectionSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,endpoint,catalogue,select,asset};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,asset,canonicalLocalJson,catalogue,select}from"./chunk-EAZKDCLD.js";import{directory,entries,fail,localSocketPath,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-GIEYSDCG.js";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",...["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}from"node:fs/promises";import{dirname,join,delimiter}from"node:path";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:dirname(process.execPath)+(process.platform==="win32"?"":delimiter+["/usr/bin","/bin"].join(delimiter)),LANG:"C",LC_ALL:"C",UV_THREADPOOL_SIZE:"2",NVS_INSTALL_OWNER:"MANAGED"});async function verifySlot(root,slot){if(requiredRuntimeFiles.some(name=>!Object.hasOwn(slot.files,name)))fail("SLOT_FILES_MISSING");for(const[name,hash]of Object.entries(slot.files)){if(!allowedRuntimeFiles.has(name))fail("SLOT_PATH_INVALID");if(sha256(await read(join(root,name),64*1024*1024))!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probe(root,expected){const bytes=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(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(join(stateDirectory,"control-token"),128)).toString()})}async function runningInventory(client,root,slot){const inventory=await client.inventory(),status=await client.status();if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(slot.descriptor)||status.versions.find(v=>v.component==="RUNTIME")?.executablePath!==join(root,"dist/entry.js"))fail("RUNTIME_ALREADY_RUNNING");return inventory}async function launch(root,slot,stateDirectory,cloudConfig,toolsConfig){await verifySlot(root,slot);await probe(root,slot.descriptor);await directory(stateDirectory);const existing=await ownerClient(stateDirectory);try{return await runningInventory(existing,root,slot)}catch(e){if(e instanceof Error&&e.message.includes("RUNTIME_ALREADY_RUNNING"))throw e}const log=await open(join(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env: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}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat(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 bytes=await new Promise((resolve,reject)=>execFile(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:environment(),timeout:35e3,maxBuffer:65536},(error,stdout)=>error?reject(Error("Tool probe failed")):resolve(stdout)));const report=LocalDoctorReportSchema.parse(JSON.parse(bytes));if(report.availability!=="AVAILABLE")fail("TOOL_QUALIFICATION_FAILED");return report}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}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){if(cloud){const raw=JSON.parse((await read(cloud,32768)).toString());if(LocalToolSelectionSchema.parse(raw.tools).mode==="INSTALLED")return identity(cloud,true)}return identity(path??cloud,!path)}async function assertPendingCompatible(raw,expected,previous,next,cloud){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingRenderers.some(d=>d!==expected.rendererDigest))fail("NATIVE_RECOVERY_REQUIRED");if(i.pendingExecutions+i.pendingRequests===0)return;if(i.descriptor.profileDigest!==expected.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")}import{randomUUID}from"node:crypto";import{join as join2,dirname as dirname2}from"node:path";import{z}from"zod";async function grant(manager,raw,output){const i=z.strictObject({projects:z.array(z.strictObject({tenantId:z.uuid(),projectId:z.uuid()})).min(1).max(100),expiresAt:z.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname2(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join2(manager.ledger.root,"grants",randomUUID()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,projects:i.projects,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-TBJVDQWU.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join2(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z.strictObject({projects:z.array(z.strictObject({tenantId:z.uuid(),projectId:z.uuid()})).max(100),expiresAt:z.iso.datetime({offset:true}),output:z.string().min(1)}).parse(await optional(join2(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 randomUUID3}from"node:crypto";import{join as join6}from"node:path";import{z as z4}from"zod";import{z as z2}from"zod";import{join as join3}from"node:path";var slotSchema=z2.strictObject({id:z2.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z2.string().nullable().default(null),files:z2.record(z2.string().min(1).max(100),z2.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z2.strictObject({id:z2.uuid(),planId:z2.uuid(),fingerprint:z2.string().regex(/^[0-9a-f]{64}$/),phase:z2.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z2.string().nullable(),failedPhase:z2.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z2.strictObject({revision:z2.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z2.strictObject({previous:z2.string().nullable(),value:installationSchema,digest:z2.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(join3(root,name));return new _InstallationLedger(root)}async current(){const names=(await entries(join3(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(join3(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(join3(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 join3(this.root,"slots",slot.id)}};import{randomUUID as randomUUID2}from"node:crypto";import{chmod as chmod2}from"node:fs/promises";import{join as join5}from"node:path";import{constants}from"node:fs";import{open as open2}from"node:fs/promises";import{z as z3}from"zod";var metadataSchema=z3.strictObject({protocol:z3.literal("NVS_PRODUCT_COMPONENT_V1"),version:z3.string().min(1).max(120),byteSize:z3.int().positive().max(64*1024*1024),sha512:z3.string().regex(/^[a-f0-9]{128}$/)});async function regularBytes(url,maximum){const file=await open2(url,constants.O_RDONLY|constants.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.1")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 join4}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)?)?\/?$/.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(join4(root,"dist"));if([...files.keys()].some(p=>p.startsWith("dist/native/")))await directory(join4(root,"dist/native"));for(const[path,contents]of files){await write(join4(root,path),contents,true);await chmod(join4(root,path),path.endsWith("entry.js")?320:256);hashes[path]=sha256(contents)}return hashes}async function stage(ledger,release,origin){const id=randomUUID2(),root=await directory(join5(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(join5(stateDirectory,"tools",a.sha256)),path2=join5(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=join5(await directory(join5(stateDirectory,"tool-selections")),selectionId+".json");await write(path,JSON.stringify(selection));return path}async function selectedTools(release,origin,state,slotId,cloudConfig,previousSelection){if(cloudConfig){const raw=JSON.parse((await read(cloudConfig,32768)).toString());const selection=LocalToolSelectionSchema.parse(raw.tools);if(selection.mode==="INSTALLED"){const path=join5(await directory(join5(state,"tool-selections")),slotId+".json");await write(path,JSON.stringify(selection),true);return path}}return await managedTools(release,origin,state,slotId)??previousSelection}var configurationSchema=z4.strictObject({stateDirectory:z4.string().min(1).max(4096),catalogueUrl:z4.string().url(),publicKeyFile:z4.string().min(1).max(4096),cloudConfigFile:z4.string().nullable().default(null),notifications:z4.boolean().default(true),rejectedVersions:z4.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(join6(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join6(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?join6(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}}async prepare(version){const c=await this.configuration(),current=(await this.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const trusted=await catalogue(c),release=select(trusted.signed,version);let runtimeRevision=null;try{const inventory=await(await ownerClient(c.stateDirectory)).inventory();runtimeRevision=inventory.runtimeRevision;if(inventory.pendingRenderers.some(d=>d!==release.descriptor.rendererDigest))fail("NATIVE_RECOVERY_REQUIRED");await assertPendingCompatible(inventory,release.descriptor,current.active?.toolsConfigPath??null,current.active?.toolsConfigPath??null,c.cloudConfigFile)}catch(e){if(e instanceof Error&&e.message.includes("NATIVE_RECOVERY_REQUIRED"))throw e;if(!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED")}const body={protocol:"NVS_LOCAL_UPDATE_PLAN_V1",planId:randomUUID3(),installationRevision:current.revision,runtimeRevision,catalogueFingerprint:trusted.fingerprint,release,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(join6(this.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}async plan(id){if(!z4.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join6(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()||trusted.fingerprint!==plan.catalogueFingerprint||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=>d!==plan.release.descriptor.rendererDigest))fail("REVISION_CONFLICT")}if(plan.runtimeRevision===null&&!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");s=await this.ledger.commit(s,{active:s.active,transition:{id:randomUUID3(),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);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=>d!==candidate.descriptor.rendererDigest))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");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){const chosen=c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;return launch(this.ledger.slotPath(slot),slot,c.stateDirectory,c.cloudConfigFile??void 0,chosen?.mode==="INSTALLED"?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{ownerClient,socketAbsent,LocalInstallationManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LocalInstallationManager,ownerClient}from"./chunk-U2UKGYGF.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,GrantLocalDeviceSchema,LocalAgentGrantSchema,LocalDeviceTransportConfigurationSchema,LocalToolSelectionSchema,NativeStudioLocalDeviceClient,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentNativeProposal,localAgentSnapshotFromContext}from"./chunk-EAZKDCLD.js";import{NativeStudioAgentClient}from"./chunk-E57YVMQ4.js";import"./chunk-GJ7BZJLW.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import{readCredential,readInput}from"./chunk-25EDDZQA.js";import{LocalClientError,directory,fail,read,write}from"./chunk-GIEYSDCG.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";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);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"}]}}import{homedir as homedir2}from"node:os";import{join as join3,resolve as resolve2}from"node:path";import{homedir}from"node:os";import{join as join2,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:"Explicitly approves remote OpenAI inference/use for these Projects until expiry. Does not invoke a model."}}}if(flags.has("--evidence")&&!["IMAGE_PIXELS","METADATA_ONLY"].includes(need("--evidence")))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join2(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":output=await client.prepareAgentReview(localAgentSnapshotFromContext(await readInput(need("--input"),stdin),flags.get("--evidence")==="IMAGE_PIXELS"));break;case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image)throw Error();const studio=new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId:snapshot.basis.scope.tenantId,authorization:()=>readCredential(flags,process.env)});const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentNativeProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|grant|revoke-device|revoke-grant|preview --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp --connector <private-file>","agent-grant-plan|agent-probe|agent-grant|agent-revoke|review-prepare|review-image-fetch|review-start|review-inspect|review-proposal \u2014 see --input private JSON and exact --approve"],note:"Check/prepare do not download executables. Apply requires exact approval. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);if(typeof input.tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId:input.tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const action=required("--action");const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="grant"?await client.grant(GrantLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="revoke-grant"?await client.revokeGrant(RevokeLocalDeviceGrantSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const manager=await LocalInstallationManager.open(resolve2(options.get("--home")??join3(homedir2(),".nativestudio","client")));let output;mutation=["configure","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepare(required("--version"));break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{profileAuthorization,runOAuthCommand}from"./chunk-G42IS5JF.js";import"./chunk-MSOMVWKN.js";import"./chunk-PUNG4ND7.js";import"./chunk-25EDDZQA.js";import"./chunk-GIEYSDCG.js";import"./chunk-6NVIN2NI.js";export{profileAuthorization,runOAuthCommand};
|