@nativestudio/cli 0.3.0-rc.17 → 0.3.0-rc.19

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.
Files changed (145) hide show
  1. package/COMPATIBILITY.json +11 -11
  2. package/components/runtime.json +7 -7
  3. package/components/runtime.tgz +0 -0
  4. package/dist/_chunks/chunk-226SBV53.js +1 -0
  5. package/dist/_chunks/{chunk-TWC3NXFA.js → chunk-27KI24GK.js} +1 -1
  6. package/dist/_chunks/chunk-2GV47BUV.js +1 -0
  7. package/dist/_chunks/chunk-2MKMGMA4.js +1 -0
  8. package/dist/_chunks/{chunk-FX5UVDTH.js → chunk-3TOXIJ7K.js} +1 -1
  9. package/dist/_chunks/{chunk-65X56WAQ.js → chunk-4NCE337I.js} +1 -1
  10. package/dist/_chunks/{chunk-BR26X3ZF.js → chunk-5G3AJAKI.js} +1 -1
  11. package/dist/_chunks/chunk-5TKBEFRX.js +1 -0
  12. package/dist/_chunks/chunk-67QDMD7M.js +1 -0
  13. package/dist/_chunks/{chunk-SKAVQ4UW.js → chunk-7I7ARCY7.js} +1 -1
  14. package/dist/_chunks/{chunk-UMCOLDHH.js → chunk-7P2NA6TH.js} +1 -1
  15. package/dist/_chunks/{chunk-K25YVVTT.js → chunk-AIR7YOFU.js} +1 -1
  16. package/dist/_chunks/chunk-BZPQB66Z.js +1 -0
  17. package/dist/_chunks/chunk-CTCEGOC7.js +1 -0
  18. package/dist/_chunks/chunk-DLW42PJ6.js +1 -0
  19. package/dist/_chunks/{chunk-SDTAJ7FI.js → chunk-GQ32ZQTM.js} +1 -1
  20. package/dist/_chunks/{chunk-HI5SIUX7.js → chunk-H46NB5FL.js} +1 -1
  21. package/dist/_chunks/{chunk-ORFGJBJA.js → chunk-HIBT6NXN.js} +1 -1
  22. package/dist/_chunks/chunk-IF6AUKH3.js +1 -0
  23. package/dist/_chunks/{chunk-IHTF6VEC.js → chunk-J2IYRUVM.js} +1 -1
  24. package/dist/_chunks/{chunk-UGOXJEDU.js → chunk-JL4MUI7K.js} +1 -1
  25. package/dist/_chunks/chunk-LZPPTW2K.js +1 -0
  26. package/dist/_chunks/{chunk-53EULX5D.js → chunk-PAIJRAJB.js} +1 -1
  27. package/dist/_chunks/chunk-QGK6G6YS.js +1 -0
  28. package/dist/_chunks/{chunk-KYNC2BSW.js → chunk-TIHGZGU3.js} +1 -1
  29. package/dist/_chunks/chunk-TT7IA5HB.js +1 -0
  30. package/dist/_chunks/chunk-UITIQHVU.js +45 -0
  31. package/dist/_chunks/chunk-WTJVS2VS.js +1 -0
  32. package/dist/_chunks/chunk-WXEERCXN.js +1 -0
  33. package/dist/_chunks/component-contract-HETXQ2J4.js +1 -0
  34. package/dist/_chunks/connect-7TJDWXV4.js +1 -0
  35. package/dist/_chunks/device-management-NP7HAXRU.js +1 -0
  36. package/dist/_chunks/device-preflight-QAPMMHWK.js +1 -0
  37. package/dist/_chunks/devices-inventory-WZ3QAPTS.js +1 -0
  38. package/dist/_chunks/devices-main-XKRRLX5B.js +1 -0
  39. package/dist/_chunks/files-JJ6YOULB.js +1 -0
  40. package/dist/_chunks/host-component-H3Q7TU5Y.js +1 -0
  41. package/dist/_chunks/host-help-SBXGX457.js +1 -0
  42. package/dist/_chunks/host-main-VUEGUFTU.js +1 -0
  43. package/dist/_chunks/http-profile-3VVSWYA5.js +1 -0
  44. package/dist/_chunks/library-main-4BQ2J73H.js +1 -0
  45. package/dist/_chunks/local-main-GBC2HPD4.js +1 -0
  46. package/dist/_chunks/local-mcp-FXHB3CKF.js +1 -0
  47. package/dist/_chunks/main-R7DV24KT.js +2 -0
  48. package/dist/_chunks/mcp-6D4KHCCL.js +1 -0
  49. package/dist/_chunks/oauth-RPME2XYB.js +1 -0
  50. package/dist/_chunks/observe-entry-NKXTUZYF.js +1 -0
  51. package/dist/_chunks/remote-client-TIFVZEGG.js +1 -0
  52. package/dist/_chunks/render-main-KMP4SMK7.js +1 -0
  53. package/dist/_chunks/source-import-YYRII5FQ.js +1 -0
  54. package/dist/_chunks/src-IX5ZVGZS.js +1 -0
  55. package/dist/_chunks/stdio-main-HNLJCG45.js +1 -0
  56. package/dist/_chunks/workspace-main-LD56MMI6.js +1 -0
  57. package/dist/_types/cli/local/desktop-contract.d.ts +9 -3
  58. package/dist/_types/cli/local/desktop-device-contract.d.ts +18 -3
  59. package/dist/_types/cli/local/desktop-device-owner.d.ts +4 -1
  60. package/dist/_types/cli/local/desktop-device-state.d.ts +10 -4
  61. package/dist/_types/cli/local/desktop-owner.d.ts +13 -11
  62. package/dist/_types/cli/local/ledger.d.ts +2 -0
  63. package/dist/_types/cli/local/manager.d.ts +12 -6
  64. package/dist/_types/cli/local/mcp-tools.d.ts +21 -4
  65. package/dist/_types/contracts/component-status.d.ts +241 -0
  66. package/dist/_types/contracts/composition-source-review.d.ts +1 -1
  67. package/dist/_types/contracts/delivery-completion.d.ts +1 -1
  68. package/dist/_types/contracts/delivery-operations.d.ts +5 -5
  69. package/dist/_types/contracts/delivery-summary.d.ts +1 -1
  70. package/dist/_types/contracts/delivery-validation.d.ts +3 -3
  71. package/dist/_types/contracts/device-render.d.ts +2 -0
  72. package/dist/_types/contracts/final-render.d.ts +1 -1
  73. package/dist/_types/contracts/index.d.ts +1 -0
  74. package/dist/_types/contracts/interface/common.d.ts +18 -0
  75. package/dist/_types/contracts/interface/production-snapshot.d.ts +1 -1
  76. package/dist/_types/contracts/keyframe-review.d.ts +6 -6
  77. package/dist/_types/contracts/local-execution/agent-component-status.d.ts +109 -0
  78. package/dist/_types/contracts/local-execution/agent-context.d.ts +4 -4
  79. package/dist/_types/contracts/local-execution/agent-review.d.ts +7 -7
  80. package/dist/_types/contracts/local-execution/device.d.ts +2 -1
  81. package/dist/_types/contracts/local-execution/enrollment-credential.d.ts +141 -0
  82. package/dist/_types/contracts/local-execution/enrollment-handoff.d.ts +44 -0
  83. package/dist/_types/contracts/local-execution/index.d.ts +3 -0
  84. package/dist/_types/contracts/local-execution/ipc.d.ts +43 -9
  85. package/dist/_types/contracts/local-execution/library-result.d.ts +4 -0
  86. package/dist/_types/contracts/local-execution/local-navigation.d.ts +25 -8
  87. package/dist/_types/contracts/local-execution/management.d.ts +5 -2
  88. package/dist/_types/contracts/local-execution/media-validation.d.ts +2 -2
  89. package/dist/_types/contracts/local-execution/preview.d.ts +1 -0
  90. package/dist/_types/contracts/local-execution/processor-capability.d.ts +8 -0
  91. package/dist/_types/contracts/local-execution/processor-recipes.d.ts +29 -0
  92. package/dist/_types/contracts/local-execution/processor.d.ts +73 -3
  93. package/dist/_types/contracts/local-execution/workspace.d.ts +1 -1
  94. package/dist/_types/contracts/mcp-capabilities.d.ts +1 -0
  95. package/dist/_types/contracts/navigation-context.d.ts +1 -0
  96. package/dist/_types/contracts/navigation.d.ts +1 -0
  97. package/dist/_types/contracts/programmatic-exploration.d.ts +8 -8
  98. package/dist/_types/contracts/programmatic-video-review.d.ts +5 -5
  99. package/dist/_types/contracts/reference-preview.d.ts +1 -0
  100. package/dist/_types/contracts/repair-lifecycle.d.ts +12 -12
  101. package/dist/_types/contracts/repair-plan.d.ts +2 -2
  102. package/dist/_types/contracts/review-intelligence-final-output.d.ts +3 -3
  103. package/dist/_types/contracts/review-intelligence.d.ts +5 -5
  104. package/dist/_types/contracts/review1-repair-source.d.ts +6 -6
  105. package/dist/_types/contracts/review1-repair-strategy.d.ts +4 -4
  106. package/dist/_types/contracts/video-review.d.ts +6 -6
  107. package/dist/_types/sdk/errors.d.ts +3 -2
  108. package/dist/_types/sdk/local-runtime/device-client.d.ts +2 -2
  109. package/dist/_types/sdk/local-runtime-client.d.ts +29 -16
  110. package/dist/entry.js +1 -1
  111. package/dist/local-management.js +1 -1
  112. package/dist/local-navigation.js +1 -1
  113. package/package.json +1 -1
  114. package/dist/_chunks/chunk-3KBIDTXT.js +0 -1
  115. package/dist/_chunks/chunk-4IFMG2ZS.js +0 -1
  116. package/dist/_chunks/chunk-4NJIT52T.js +0 -1
  117. package/dist/_chunks/chunk-744IEPTK.js +0 -1
  118. package/dist/_chunks/chunk-C7CSZFV6.js +0 -1
  119. package/dist/_chunks/chunk-CW67UB2I.js +0 -1
  120. package/dist/_chunks/chunk-GKDGSAI5.js +0 -1
  121. package/dist/_chunks/chunk-HAOCQVMU.js +0 -1
  122. package/dist/_chunks/chunk-HTUTYIRU.js +0 -1
  123. package/dist/_chunks/chunk-RUPH3HZ2.js +0 -1
  124. package/dist/_chunks/chunk-U5FT4VBR.js +0 -1
  125. package/dist/_chunks/connect-OY623MMA.js +0 -1
  126. package/dist/_chunks/device-management-CXSZFF53.js +0 -1
  127. package/dist/_chunks/device-preflight-6HKPPZ5L.js +0 -1
  128. package/dist/_chunks/devices-inventory-K553HAF3.js +0 -1
  129. package/dist/_chunks/devices-main-LBDRDV2M.js +0 -1
  130. package/dist/_chunks/files-72BEXD7E.js +0 -1
  131. package/dist/_chunks/host-main-ZMBFHY55.js +0 -1
  132. package/dist/_chunks/http-profile-D65WSTZU.js +0 -1
  133. package/dist/_chunks/library-main-RNDPNKYK.js +0 -1
  134. package/dist/_chunks/local-main-RC4RM3OB.js +0 -1
  135. package/dist/_chunks/local-mcp-LQCQ3WLF.js +0 -1
  136. package/dist/_chunks/main-CPIMF4PS.js +0 -2
  137. package/dist/_chunks/mcp-HQQJCKHS.js +0 -1
  138. package/dist/_chunks/oauth-QBJ62PIA.js +0 -1
  139. package/dist/_chunks/observe-entry-4GPGZ3NJ.js +0 -1
  140. package/dist/_chunks/remote-client-6XHMNMXK.js +0 -1
  141. package/dist/_chunks/render-main-ATCEBECW.js +0 -1
  142. package/dist/_chunks/source-import-HIL7NW3L.js +0 -1
  143. package/dist/_chunks/src-MRFJOTKK.js +0 -1
  144. package/dist/_chunks/stdio-main-T4ORVLSX.js +0 -1
  145. package/dist/_chunks/workspace-main-44ECTGHC.js +0 -1
@@ -1 +1 @@
1
- import{desktopDevicePending,runDesktopDeviceRequest}from"./_chunks/chunk-4IFMG2ZS.js";import{DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia,runDesktopLibraryRequest}from"./_chunks/chunk-ORFGJBJA.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./_chunks/chunk-IHTF6VEC.js";import{prepareInstalledCpuSpeech}from"./_chunks/chunk-K25YVVTT.js";import"./_chunks/chunk-SDTAJ7FI.js";import{LocalInstallationManager,captureInstalledTools,ownerClient,socketAbsent,toolPreference,waitStopped}from"./_chunks/chunk-744IEPTK.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-GKDGSAI5.js";import{CpuSpeechPrepareInputSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema,catalogue,endpoint,newerVersion}from"./_chunks/chunk-3KBIDTXT.js";import{canonicalLocalJson}from"./_chunks/chunk-C7CSZFV6.js";import{LocalClientError,atomicMove,directory,entries,fail,optional,read,sha256,write}from"./_chunks/chunk-RUPH3HZ2.js";import"./_chunks/chunk-HAOCQVMU.js";import{NativeStudioSdkError}from"./_chunks/chunk-HTUTYIRU.js";import{z as z7}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest4=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest4||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest4}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest4=record.digest}return{plan,digest:digest4}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews","library"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join3(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join3(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join3(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join3(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join4(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join4(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.literal("speech-prepare"),input:CpuSpeechPrepareInputSchema}),z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional(),speech:z7.strictObject({voiceIds:CpuSpeechPrepareInputSchema.shape.voiceIds}).optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,"speech-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 tools=active?.toolsConfigPath?await toolPreference(active.toolsConfigPath,null):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:tools?.mode??null,...tools?.cpuSpeech?{speech:{voiceIds:tools.cpuSpeech.voiceIds}}:{}})}import{createPublicKey}from"node:crypto";import{join as join5}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();if(!config.catalogueUrl||!config.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&["CONFIGURATION_REQUIRED","DEPENDENCY_CHANNEL_REQUIRED"].includes(error.code)))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;let existing;try{existing=await manager.configuration()}catch(e){if(!(e instanceof LocalClientError&&e.code==="CONFIGURATION_REQUIRED"))throw e}const stateDirectory=existing?.stateDirectory??join5(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join5(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join5(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({...existing,stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:!existing})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}import{z as z8}from"zod";import{join as join6}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";var digest3=z8.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z8.strictObject({id:z8.uuid(),channel:z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z8.string().url(),publicKey:z8.string()}),release:LocalReleaseSchema,installationRevision:z8.int().nonnegative(),expiresAt:z8.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join6(home,"bootstrap-plans"));let intent2,fingerprint2;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;if(configuration&&!configuration.publicKeyFile)fail("DESKTOP_CHANNEL_CHANGED");const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join6(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent2=intentSchema.parse({id:randomUUID2(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint2=sha256(canonicalLocalJson(intent2));await write(join6(root,intent2.id+".json"),canonicalLocalJson({intent:intent2,fingerprint:fingerprint2}),true)}else{const saved=z8.strictObject({intent:intentSchema,fingerprint:digest3}).parse(JSON.parse((await read(join6(root,call.id+".json"),131072)).toString()));intent2=saved.intent;fingerprint2=saved.fingerprint;if(fingerprint2!==call.fingerprint||fingerprint2!==sha256(canonicalLocalJson(intent2))||intent2.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join6(root,intent2.id+".installation.json");const receipt=z8.strictObject({id:z8.uuid(),fingerprint:digest3}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent2.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent2.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent2.channel);await configureDesktopChannel(manager,trust.fingerprint,intent2.channel);const plan=await manager.prepare(intent2.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent2.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent2.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent2.id,fingerprint:fingerprint2,version:intent2.release.descriptor.version,host:new URL(intent2.channel.catalogueUrl).host,bytes:intent2.release.package.byteSize+Object.values(intent2.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent2.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"library":result=await runDesktopLibraryRequest(home,request);break;case"library-import":result=await runDesktopLibraryImport(home,request);break;case"library-import-prepare":result=await prepareDesktopLibraryImport(request);break;case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"speech-prepare":{const prepared=await prepareInstalledCpuSpeech(manager,request.input),plan=prepared.plan;result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",toolMode:plan.toolSelection?.mode,planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat as lstat3,readFile,chmod as chmod2}from"node:fs/promises";import{join as join7,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat3(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod2(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join7(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join7(await directory(home),"nodes",expected)),target=join7(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join7(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,prepareDesktopLibraryImport,runDesktopLibraryMedia,runDesktopOwnerRequest,runLocalManagement};
1
+ import{prepareInstalledCpuSpeech}from"./_chunks/chunk-AIR7YOFU.js";import{configureDesktopChannel,desktopChannelInfo,desktopRuntimeChannel}from"./_chunks/chunk-2GV47BUV.js";import{DesktopBootstrapReplySchema,DesktopBootstrapRequestSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,desktopOwnerResponses,runDesktopAgentRequest,runDesktopOfflineRequest,runDesktopStorageRequest,runDesktopWorkspaceRequest}from"./_chunks/chunk-WXEERCXN.js";import{DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia,runDesktopLibraryRequest}from"./_chunks/chunk-HIBT6NXN.js";import{desktopDevicePending,runDesktopDeviceRequest}from"./_chunks/chunk-67QDMD7M.js";import"./_chunks/chunk-GQ32ZQTM.js";import{disableDesktopAutomation}from"./_chunks/chunk-J2IYRUVM.js";import{LocalInstallationManager,captureInstalledTools,ownerClient,socketAbsent,toolPreference}from"./_chunks/chunk-IF6AUKH3.js";import{desktopDeviceConnector}from"./_chunks/chunk-BZPQB66Z.js";import{DesktopDeviceReplySchema,DesktopDeviceScopeSchema}from"./_chunks/chunk-5TKBEFRX.js";import{LocalReleaseSchema,catalogue,newerVersion}from"./_chunks/chunk-CTCEGOC7.js";import{canonicalLocalJson}from"./_chunks/chunk-LZPPTW2K.js";import{directory,fail,optional,read,sha256,write}from"./_chunks/chunk-DLW42PJ6.js";import"./_chunks/chunk-WTJVS2VS.js";import"./_chunks/chunk-TT7IA5HB.js";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 tools=active?.toolsConfigPath?await toolPreference(active.toolsConfigPath,null):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:tools?.mode??null,...tools?.cpuSpeech?{speech:{voiceIds:tools.cpuSpeech.voiceIds}}:{}})}import{z}from"zod";import{join}from"node:path";import{randomUUID}from"node:crypto";var digest=z.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z.strictObject({id:z.uuid(),channel:z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z.string().url(),publicKey:z.string()}),release:LocalReleaseSchema,installationRevision:z.int().nonnegative(),expiresAt:z.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join(home,"bootstrap-plans"));let intent,fingerprint;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;if(configuration&&!configuration.publicKeyFile)fail("DESKTOP_CHANNEL_CHANGED");const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent=intentSchema.parse({id:randomUUID(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint=sha256(canonicalLocalJson(intent));await write(join(root,intent.id+".json"),canonicalLocalJson({intent,fingerprint}),true)}else{const saved=z.strictObject({intent:intentSchema,fingerprint:digest}).parse(JSON.parse((await read(join(root,call.id+".json"),131072)).toString()));intent=saved.intent;fingerprint=saved.fingerprint;if(fingerprint!==call.fingerprint||fingerprint!==sha256(canonicalLocalJson(intent))||intent.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join(root,intent.id+".installation.json");const receipt=z.strictObject({id:z.uuid(),fingerprint:digest}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent.channel);await configureDesktopChannel(manager,trust.fingerprint,intent.channel);const plan=await manager.prepare(intent.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent.id,fingerprint,version:intent.release.descriptor.version,host:new URL(intent.channel.catalogueUrl).host,bytes:intent.release.package.byteSize+Object.values(intent.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"library":result=await runDesktopLibraryRequest(home,request);break;case"library-import":result=await runDesktopLibraryImport(home,request);break;case"library-import-prepare":result=await prepareDesktopLibraryImport(request);break;case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"speech-prepare":{const prepared=await prepareInstalledCpuSpeech(manager,request.input),plan=prepared.plan;result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",toolMode:plan.toolSelection?.mode,planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};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{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,prepareDesktopLibraryImport,runDesktopLibraryMedia,runDesktopOwnerRequest,runLocalManagement};
@@ -1 +1 @@
1
- import{LocalMcpTools}from"./_chunks/chunk-UGOXJEDU.js";import{DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-GKDGSAI5.js";import"./_chunks/chunk-3KBIDTXT.js";import"./_chunks/chunk-C7CSZFV6.js";import"./_chunks/chunk-RUPH3HZ2.js";import"./_chunks/chunk-HAOCQVMU.js";import"./_chunks/chunk-HTUTYIRU.js";async function openDesktopDeviceTools(raw,home){const scope=DesktopDeviceScopeSchema.parse(raw);return LocalMcpTools.open(await desktopDeviceConnector(home,scope),home)}export{LocalMcpTools,openDesktopDeviceTools};
1
+ import{LocalMcpTools}from"./_chunks/chunk-JL4MUI7K.js";import{desktopDeviceConnector}from"./_chunks/chunk-BZPQB66Z.js";import{DesktopDeviceScopeSchema}from"./_chunks/chunk-5TKBEFRX.js";import"./_chunks/chunk-CTCEGOC7.js";import"./_chunks/chunk-LZPPTW2K.js";import"./_chunks/chunk-DLW42PJ6.js";import"./_chunks/chunk-WTJVS2VS.js";import"./_chunks/chunk-TT7IA5HB.js";async function openDesktopDeviceTools(raw,home){const scope=DesktopDeviceScopeSchema.parse(raw);return LocalMcpTools.open(await desktopDeviceConnector(home,scope),home)}export{LocalMcpTools,openDesktopDeviceTools};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativestudio/cli",
3
- "version": "0.3.0-rc.17",
3
+ "version": "0.3.0-rc.19",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "engines": {
@@ -1 +0,0 @@
1
- import{CpuSpeechCapabilitySchema,CpuSpeechInputSchema,CpuSpeechInstallationSchema,EnrollLocalDeviceSchema,KeyframeObservationSchema,LegacyCaptionRenderStyleSchema,LocalDeviceManagementCommandSchema,LocalDevicePlatformSchema,LocalDeviceViewSchema,LocalDigestSchema,LocalFinalRenderAdmissionSchema,LocalIdSchema,LocalLeaseBindingSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryUsageSchema,LocalManagementReceiptSchema,LocalPackageVersionSchema,LocalPreviewAdmissionSchema,LocalProjectScopeSchema,LocalRevisionSchema,LocalTimeSchema,LocalWhisperToolSelectionSchema,LocalWorkScopeSchema,RegularCaptionRenderStyleSchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RevokeLocalDeviceSchema,RoughCutRequirementSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,TenantProcessorKindSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VisualRequirementSchema,assertManagementReceipt,canonicalLocalJson,checkedManagementReceipt,kokoroCpuProfile,mediaCategoryOf}from"./chunk-C7CSZFV6.js";import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-RUPH3HZ2.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{z}from"zod";var HYPERFRAME_RENDER_PROFILE={id:"HYPERFRAME_1080P30_FULL_PAINT_V1",adapter:"native-hyperframe-v1",engine:"0.8.134",producer:"0.8.134",gsap:"3.15.0",node:"v24.21.0",browser:"Google Chrome for Testing 154.0.8037.57",browserSha256:"60c03e8882f4bb47459a905ede1074e1e746c5b765e437c288e460320540a8a3",ffmpeg:"ffmpeg version 8.0.1-3ubuntu2 Copyright (c) 2000-2025 the FFmpeg developers",maxFrames:360,timeoutMs:6e5,maxRssBytes:3221225472,maxScratchBytes:3221225472,maxOutputBytes:134217728,maxCpuMs:6e5,capture:"PNG_SOFTWARE_SCREENSHOT_FULL_PAINT",encode:"H264_YUV420P_CRF18_THREADS2_NO_AUDIO"};var HYPERFRAME_ALPHA_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1",adapter:"native-hyperframe-alpha-v1",encode:"RGBA_PNG_SEQUENCE_30_V1",maxOutputBytes:67108864,maxDecodedBytes:536870912};var HYPERFRAME_CACHED_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_1080P30_FRAME_CACHE_V2",adapter:"native-hyperframe-cache-v2",encode:"H264_YUV420P_CRF18_VERYFAST_THREADS2_NO_AUDIO"};var executable=z.strictObject({path:z.string().min(1).max(4096),digest:LocalDigestSchema});var LocalManagedMediaReuseSchema=z.strictObject({schemaVersion:z.literal(1),ffmpeg:executable,ffprobe:executable});var mediaTools={ffmpeg:executable,ffprobe:executable};var LocalCompositionBrowserSelectionSchema=executable.extend({digest:z.literal(HYPERFRAME_CACHED_RENDER_PROFILE.browserSha256)});var LocalInstalledToolSelectionSchema=z.strictObject({mode:z.literal("INSTALLED"),...mediaTools,compositionBrowser:LocalCompositionBrowserSelectionSchema.optional(),whisper:LocalWhisperToolSelectionSchema.optional(),cpuSpeech:CpuSpeechInstallationSchema.optional()});var LocalToolSelectionSchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("MANAGED"),...mediaTools,cpuSpeech:CpuSpeechInstallationSchema.optional()}),LocalInstalledToolSelectionSchema]);import{z as z11}from"zod";import{z as z4}from"zod";import{z as z2}from"zod";var LocalRuntimeDescriptorSchema=z2.strictObject({protocol:z2.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z2.strictObject({major:z2.literal(24),minMinor:z2.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z2.literal("NVS_LOCAL_IPC_V1"),workProtocol:z2.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z2.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z2.array(z2.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalReleaseAssetSchema=z2.strictObject({url:z2.string().url().max(2048),byteSize:z2.int().positive().max(256*1024*1024),sha512:z2.string().length(128).regex(/^[0-9a-f]{128}$/)});import{z as z3}from"zod";var RuntimeCaptionAssets={"NotoSansSC.ttf":LegacyCaptionRenderStyleSchema.shape.fontSha256.value,"NativeStudioSC-Regular.ttf":RegularCaptionRenderStyleSchema.shape.fontSha256.value,"OFL.txt":"092c580f54ee69841e94731e91f63f5d2d2a793550f4827cec485656e462f1bd"};var LocalComponentBytesSchema=z3.strictObject({byteSize:z3.int().positive().max(64*1024*1024),sha512:z3.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalRuntimeComponentSchema=LocalComponentBytesSchema.extend({protocol:z3.literal("NVS_PRODUCT_COMPONENT_V2"),version:LocalPackageVersionSchema,descriptor:LocalRuntimeDescriptorSchema.omit({platform:true}),resources:z3.strictObject({captions:LocalComponentBytesSchema})}).refine(v=>v.version===v.descriptor.version);var LocalSessionConnectorSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z4.string().min(1).max(4096),credential:z4.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,tenantId:z4.uuid(),deviceId:z4.uuid()});var LocalManagementInventorySchema=z4.strictObject({runtimeRevision:z4.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z4.int().nonnegative(),pendingExecutions:z4.int().nonnegative(),pendingRequests:z4.int().nonnegative(),pendingRenderers:z4.array(LocalDigestSchema).max(64)});var LocalReleaseSchema=z4.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z4.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable(),resources:z4.strictObject({captions:LocalReleaseAssetSchema.extend({byteSize:LocalComponentBytesSchema.shape.byteSize})}).optional()});var LocalBundledReleaseSchema=LocalReleaseSchema.extend({package:LocalComponentBytesSchema.extend({source:z4.literal("CLI")})});var LocalReleaseCatalogueSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z4.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=z4.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z4.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z4.discriminatedUnion("mode",[z4.strictObject({mode:z4.literal("MANAGED"),cpuSpeech:CpuSpeechInstallationSchema.optional(),reuseMedia:LocalManagedMediaReuseSchema.optional()}),LocalInstalledToolSelectionSchema.extend({captionAssetsDirectory:z4.string().min(1).max(4096).optional()})]);var LocalUpdatePlanSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z4.int().nonnegative(),runtimeRevision:z4.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema.nullable(),trustFingerprint:LocalDigestSchema.optional(),release:z4.union([LocalReleaseSchema,LocalBundledReleaseSchema]),toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z4.strictObject({surface:z4.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z4.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:z4.enum(["AVAILABLE","BLOCKED"]),reason:z4.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z10}from"zod";import{z as z5}from"zod";var LocalOfflineSnapshotSchema=z5.strictObject({projectId:z5.uuid(),title:z5.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z5.array(z5.strictObject({id:z5.uuid(),title:z5.string().max(200)})).max(40),possiblyTruncated:z5.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z5.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z5.discriminatedUnion("action",[z5.strictObject({action:z5.enum(["list","forget"]),key:LocalDigestSchema}),z5.strictObject({action:z5.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z5.strictObject({action:z5.literal("draft"),key:LocalDigestSchema,projectId:z5.uuid(),text,expectedRevision:z5.int().nonnegative()})]);var LocalOfflinePageSchema=z5.strictObject({historical:z5.literal(true),items:z5.array(z5.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z5.strictObject({text,revision:z5.int().nonnegative()})})).max(3)});import{z as z7}from"zod";import{z as z6}from"zod";var QualifiedLocalAgentVersionSchema=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).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z6.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,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(),mediaDisclosureApproved:z6.literal(true).optional(),projects:z6.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z6.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z7.strictObject({profile:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z7.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z7.int().positive().max(134217728),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096),durationMs:z7.int().positive().max(6e4).optional(),frameRate:z7.union([z7.literal(24),z7.literal(30)]).optional(),hasAudio:z7.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z7.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z7.strictObject({protocol:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z7.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z7.strictObject({checksumSha256:sha,byteSize:z7.int().positive().max(8388608),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)}),timestampsMs:z7.array(z7.number().nonnegative().max(6e4)).max(6),audio:z7.strictObject({sampleRateHz:z7.literal(48e3),channels:z7.literal(1),samples:z7.int().positive().max(2881024),peak:z7.number().min(0).max(1),rms:z7.number().min(0).max(1),clippedSamples:z7.int().nonnegative().max(2881024)}).nullable(),limitations:z7.tuple([z7.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z7.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z7.strictObject({candidate:z7.strictObject({binary:z7.string().min(1).max(4096),binaryDigest:sha,version:z7.string().regex(/^\d+\.\d+\.\d+$/),qualified:z7.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z8}from"zod";var LocalResourcePolicySchema=z8.strictObject({acceptNewWork:z8.boolean().default(true),mode:z8.enum(["CONTINUOUS","IDLE_ONLY"]).default("CONTINUOUS"),idleAfterSeconds:z8.int().min(30).max(3600).default(300),maxConcurrentJobs:z8.int().min(1).max(2).default(1),cpuCores:z8.union([z8.literal(1),z8.literal(2)]).default(2),memoryMiB:z8.int().min(512).max(4096).default(4096),cacheQuotaBytes:z8.int().min(512*1024*1024).max(32*1024*1024*1024).default(1024*1024*1024)});var LocalResourceSettingsSchema=z8.strictObject({revision:z8.int().nonnegative(),policy:LocalResourcePolicySchema});var LocalExecutionProgressSchema=z8.strictObject({stage:z8.enum(["WAITING","DOWNLOADING","EXECUTING","UPLOADING","AWAITING_ACCEPTANCE","COMPLETE","RECOVERY_REQUIRED","FENCED"]),downloadedBytes:z8.int().nonnegative(),sourceBytes:z8.int().nonnegative(),uploadedBytes:z8.int().nonnegative(),outputBytes:z8.int().nonnegative(),lastError:z8.strictObject({code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema}).nullable()});var LocalStorageInspectionSchema=z8.strictObject({cacheBytes:z8.int().nonnegative(),protectedBytes:z8.int().nonnegative(),reclaimableBytes:z8.int().nonnegative(),transferBytes:z8.int().nonnegative(),journalBytes:z8.int().nonnegative(),reviewBytes:z8.int().nonnegative().optional(),ownerStagingBytes:z8.int().nonnegative().optional(),availableDiskBytes:z8.int().nonnegative(),quotaBytes:z8.int().positive(),overQuota:z8.boolean()});var LocalWorkspaceInspectionSchema=z8.strictObject({settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,scheduling:z8.strictObject({state:z8.enum(["READY","PAUSED","WAITING_FOR_IDLE","AT_CAPACITY","DRAINING"]),activeJobs:z8.int().nonnegative(),idleObservationCurrent:z8.boolean()})});var LocalDiagnosticsSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_DIAGNOSTICS_V1"),createdAt:LocalTimeSchema,runtimeVersion:z8.string().min(1).max(80),runtimeRevision:LocalRevisionSchema,settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,recordCounts:z8.record(z8.string().regex(/^[A-Z_]{1,40}$/),z8.int().nonnegative()),failures:z8.array(z8.strictObject({taskFingerprint:z8.string().regex(/^[a-f0-9]{64}$/),code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema})).max(32)});import{z as z9}from"zod";var sha2=z9.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=QualifiedLocalAgentVersionSchema;var LocalAgentSnapshotSchema=z9.strictObject({basis:ReviewIntelligenceBasisSchema,productionRevision:z9.int().positive(),reviewVersion:z9.int().nonnegative(),executionClass:z9.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z9.array(z9.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema])).min(1).max(64),evidence:LocalAgentMediaInputSchema.optional(),image:z9.strictObject({contentType:z9.literal("image/png"),byteSize:z9.int().positive().max(8388608),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)}).optional()}).refine(v=>!v.image||!v.evidence&&v.basis.target.kind==="IMAGE").refine(v=>v.basis.target.kind==="IMAGE"||!v.evidence||v.evidence.contentType==="video/mp4").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=z9.strictObject({configured:z9.boolean(),available:z9.boolean(),reason:z9.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha2.nullable(),inference:z9.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z9.strictObject({protocol:z9.enum(["NVS_LOCAL_AGENT_REVIEW_V1","NVS_LOCAL_AGENT_REVIEW_V2"]),id:z9.uuid(),grantFingerprint:sha2,snapshot:LocalAgentSnapshotSchema,expiresAt:z9.iso.datetime({offset:true}),fingerprint:sha2});var LocalAgentMetadataAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),observations:z9.array(z9.strictObject({key:z9.string().min(1).max(220),observed:z9.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),imageReadback:z9.string().trim().min(1).max(800),observations:z9.array(KeyframeObservationSchema.omit({region:true}).extend({key:z9.string().min(1).max(220)})).min(1).max(64)});var LocalAgentAnswerSchema=z9.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z9.strictObject({protocol:z9.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z9.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z9.int().positive().max(8388608),contentType:z9.literal("image/png"),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)});var LocalAgentReviewViewSchema=z9.strictObject({plan:LocalAgentPlanSchema,revision:z9.int().positive(),phase:z9.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),evidenceReceipt:LocalAgentEvidenceReceiptSchema.optional(),provenance:z9.strictObject({adapter:z9.enum(["CODEX_METADATA_V1","CODEX_MEDIA_V2"]),binaryDigest:sha2,version:qualifiedVersion,model:z9.string().max(100),reasoningEffort:z9.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z9.string().max(100),inference:z9.literal("REMOTE_OPENAI"),evidence:z9.enum(["METADATA_ONLY","IMAGE_PIXELS","VIDEO_FRAMES"])})}).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;const derived=v.plan.snapshot.evidence,receipt2=v.evidenceReceipt;if(v.provenance.adapter!==(derived?"CODEX_MEDIA_V2":"CODEX_METADATA_V1"))return false;if(receipt2&&(!derived||receipt2.draftId!==v.plan.id||canonicalLocalJson(receipt2.media)!==canonicalLocalJson(v.plan.snapshot.media)))return false;if(v.answer&&!!(image||derived)!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!(image||derived);return v.provenance.evidence===(pixels?derived?.contentType==="video/mp4"?"VIDEO_FRAMES":"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||(derived?!!receipt2:!!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.plan.snapshot.basis.target.kind!=="IMAGE"||v.plan.snapshot.evidence)throw Error("LOCAL_AGENT_MEDIA_PROPOSAL_REQUIRED");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 LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z10.int().min(1).max(16).default(8),includeCompleted:z10.boolean().optional(),includeProgress:z10.boolean().optional()});var LocalExecutionInspectInputSchema=LocalWorkScopeSchema.extend({includeProgress:z10.boolean().optional()});var LocalIpcCallSchema=z10.discriminatedUnion("operation",[z10.strictObject({operation:z10.literal("library.capability")}),z10.strictObject({operation:z10.literal("library.call"),input:LocalLibraryCallSchema}),z10.strictObject({operation:z10.literal("agent.discover"),binary:z10.string().min(1).max(4096).optional()}),z10.strictObject({operation:z10.literal("offline.workspace"),input:LocalOfflineCallSchema}),z10.strictObject({operation:z10.literal("workspace.inspect")}),z10.strictObject({operation:z10.literal("workspace.configure"),policy:LocalResourcePolicySchema,expectedRevision:z10.int().nonnegative()}),z10.strictObject({operation:z10.literal("workspace.activity"),idleSeconds:z10.int().min(0).max(86400),observedAt:z10.iso.datetime()}),z10.strictObject({operation:z10.literal("storage.clean")}),z10.strictObject({operation:z10.literal("diagnostics.read")}),z10.strictObject({operation:z10.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.probe")}),z10.strictObject({operation:z10.literal("agent.revoke"),approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z10.strictObject({operation:z10.literal("agent.start"),id:z10.uuid(),expectedRevision:LocalRevisionSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.inspect"),id:z10.uuid()}),z10.strictObject({operation:z10.literal("runtime.status"),includeDevice:z10.literal(true).optional()}),z10.strictObject({operation:z10.literal("runtime.doctor")}),z10.strictObject({operation:z10.literal("runtime.inventory")}),z10.strictObject({operation:z10.literal("session.issue"),tenantId:z10.uuid(),deviceId:z10.uuid(),expiresAt:z10.iso.datetime({offset:true})}),z10.strictObject({operation:z10.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("execution.inspect"),input:LocalExecutionInspectInputSchema}),z10.strictObject({operation:z10.literal("execution.list"),input:LocalExecutionListInputSchema}),z10.strictObject({operation:z10.literal("update.check")}),z10.strictObject({operation:z10.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z10.strictObject({call:LocalIpcCallSchema,availability:z10.enum(["AVAILABLE","BLOCKED"]),reason:z10.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z10.strictObject({component:z10.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z10.string().min(1).max(4096).nullable(),installOwner:z10.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z10.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z10.literal(1),workProtocols:z10.array(z10.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"])).min(1).max(2),versions:z10.array(LocalVersionReportSchema).max(8),deviceAuthority:z10.strictObject({tenantId:z10.uuid(),deviceId:z10.uuid(),origin:z10.url()}).optional(),deviceCapabilities:z10.strictObject({deviceRevision:LocalRevisionSchema,tenantMediaValidation:z10.boolean(),tenantMediaProcessing:z10.boolean(),processorCapabilities:z10.array(TenantProcessorKindSchema).max(TenantProcessorKindSchema.options.length)}).optional(),nextActions:z10.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z10.strictObject({mode:z10.enum(["MANAGED","INSTALLED"]),availability:z10.enum(["AVAILABLE","UNAVAILABLE"]),reason:z10.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z10.boolean(),executionProfiles:z10.array(z10.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2","AUDIO_MEDIA_V1"])).max(3).optional(),tools:z10.array(z10.strictObject({name:z10.enum(["FFMPEG","FFPROBE"]),path:z10.string().min(1).max(4096),version:z10.string().min(1).max(200),digest:z10.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z10.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z10.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z10.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"]),progress:LocalExecutionProgressSchema.optional()});var LocalExecutionPageSchema=z10.strictObject({items:z10.array(LocalExecutionInspectionSchema).max(16),nextCursor:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z10.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_RUNTIME_UNAVAILABLE","AGENT_LOGIN_REQUIRED","AGENT_VERSION_UNQUALIFIED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED","CACHE_QUOTA_EXCEEDED","LIBRARY_NOT_FOUND","LIBRARY_CONFLICT","LIBRARY_BYTES_INVALID","LIBRARY_ACCESS_DENIED","LIBRARY_SYNC_REQUIRED","LIBRARY_SYNC_UNAVAILABLE","LIBRARY_QUOTA_EXCEEDED"]);var LocalIpcResponseSchema=z10.discriminatedUnion("semanticStatus",[z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z10.literal("SUCCESS"),data:z10.union([LocalLibraryCapabilitySchema,LocalLibraryUsageSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionSchema,LocalLibraryProjectionPageSchema,LocalLibraryReadReplySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalOfflinePageSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z10.strictObject({state:z10.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z10.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentDiscoverySchema,LocalAgentReviewViewSchema])}),z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z10.enum(["BLOCKED","INVALID_INPUT"]),error:z10.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z11.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"]);var LocalMcpActionSchema=z11.strictObject({tool:LocalMcpToolNameSchema,arguments:z11.record(z11.string(),z11.unknown()),availability:z11.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z11.string().max(100).optional()});var LocalMcpNavigationSchema=z11.strictObject({location:z11.literal("LOCAL"),state:z11.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),deviceAuthority:LocalRuntimeStatusSchema.shape.deviceAuthority,groups:z11.array(z11.strictObject({id:z11.string().max(40),label:z11.string().max(100),tools:z11.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z11.array(z11.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z11.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z11.strictObject({location:z11.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z11.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z11.strictObject({location:z11.literal("LOCAL"),running:z11.array(LocalVersionReportSchema).max(8),available:z11.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z11.strictObject({location:z11.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z11.object({name:LocalMcpToolNameSchema,description:z11.string(),inputSchema:z11.record(z11.string(),z11.unknown())}).passthrough()});var LocalMcpFailureSchema=z11.strictObject({semanticStatus:z11.enum(["BLOCKED","INVALID_INPUT"]),error:z11.strictObject({code:z11.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z11.literal("NO_WRITE")}),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_library_list:LocalLibraryProjectionPageSchema.extend({location:z11.literal("LOCAL")}),local_library_get:z11.strictObject({location:z11.literal("LOCAL"),item:LocalLibraryProjectionSchema.nullable()}),local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z11.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z13}from"zod";function localAgentMediaSnapshot(raw){const c=ReviewIntelligenceContextResultSchema.parse(raw),r=c.reviewTarget,t=r.target,scope=c.basis.scope;if(c.ownerContext.semanticStatus!=="SUCCESS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||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||r.kind!==c.basis.target.kind)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");let media,descriptor;if(r.kind==="ROUGH_CUT"){if(!r.target.inspectable||c.basis.target.kind!=="ROUGH_CUT"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.basis;descriptor={...r.target.technical,contentType:"video/mp4"}}else if(r.kind==="PROGRAMMATIC"){if(!r.target.runtimeSucceeded||r.target.media.availability!=="AVAILABLE"||c.basis.target.kind!=="PROGRAMMATIC"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.media;descriptor=r.target.media}else{if(!r.target.runtimeSucceeded||r.target.candidate.availability!=="AVAILABLE"||r.target.candidate.freshness!=="CURRENT_BASIS"||!("generationId"in c.basis.target)||r.target.generationId!==c.basis.target.generationId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.candidate;descriptor=r.target.candidate}const video=descriptor.contentType==="video/mp4";return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:media.artifactId,representationId:media.representationId,checksumSha256:media.checksumSha256},requirements:t.requirements,evidence:{profile:"NVS_AGENT_DERIVED_EVIDENCE_V1",contentType:descriptor.contentType,byteSize:descriptor.byteSize,width:descriptor.width,height:descriptor.height,...video&&"durationMs"in descriptor?{durationMs:descriptor.durationMs,frameRate:descriptor.frameRate,hasAudio:descriptor.hasAudio}:{}}})}function localAgentMediaProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw),s=v.plan.snapshot;if(!s.evidence)return localAgentNativeProposal(v);if(v.phase!=="RESULT_PENDING"||!v.answer||!v.evidenceReceipt||s.basis.target.kind==="ROUGH_CUT")throw Error("LOCAL_AGENT_FULL_TEMPORAL_INSPECTION_REQUIRED");const video=s.evidence.contentType==="video/mp4",p=v.provenance,id=video?"sampled_frames":"normalized_image";const observations=v.answer.observations.map(o=>{const requirement=s.requirements.find(r=>r.key===o.key);if(!requirement)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const sound="family"in requirement&&requirement.family==="SOUND"||/^(audio|sound):/.test(requirement.key);return{...o,status:video||!("status"in o)?"NOT_OBSERVABLE":o.status,confidence:video||!("confidence"in o)?"UNCERTAIN":o.confidence,observed:video?sound?"This draft has no listening evidence.":"Sampled frames are advisory. This draft has no playback coverage.":o.observed,evidenceIds:video&&sound?[]:[id],..."interval"in requirement&&requirement.interval?{interval:requirement.interval}:{}}});return ValidateReviewIntelligenceSchema.parse({basis:s.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`Advisory ${video?"sampled frame observations. Full playback, listening and transcription are unavailable":"normalized original image"}. ${p.inference} via ${p.adapter} using Codex ${p.version}, model ${p.model}, effort ${p.reasoningEffort??"DEFAULT"}, binary ${p.binaryDigest}. Source ${s.media.checksumSha256}, attachment ${v.evidenceReceipt.attachment.checksumSha256}, draft ${v.plan.id}, plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:observations.some(o=>o.evidenceIds.length)?[{id,label:video?"Ordered verified source frame samples":"Verified normalized source image",producer:"EXTERNAL_AGENT_HOST",media:s.media,...video?{kind:"VIDEO_FRAMES",timestampsMs:v.evidenceReceipt.timestampsMs}:{kind:"IMAGE_PIXELS"}}]:[],review:{kind:s.basis.target.kind,observations}}})}import{z as z12}from"zod";var CpuSpeechPrepareInputSchema=z12.strictObject({profileId:z12.literal(kokoroCpuProfile.id).default(kokoroCpuProfile.id),voiceIds:z12.array(CpuSpeechInputSchema.shape.voiceId).min(1).max(8).refine(v=>new Set(v).size===v.length).default([0,45])});var CpuSpeechPreparedSchema=z12.strictObject({semanticStatus:z12.literal("PREPARED"),selection:CpuSpeechInstallationSchema,capability:CpuSpeechCapabilitySchema,reused:z12.strictObject({engine:z12.boolean(),model:z12.boolean()})});function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)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()})}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,output,signal,readOnly=false,validate){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.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","x-native-tenant-id":this.options.tenantId},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",readOnly?"NO_WRITE":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=output.parse(JSON.parse(Buffer.concat(parts).toString()));validate?.(i,value);if(value&&typeof value==="object"){const result=value,request4=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request4&&result[key]!==request4[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal,false,(original,result)=>assertManagementReceipt("device.enroll",original,result))}async managementReceipt(input,signal){const parsedInput=LocalDeviceManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalDeviceManagementCommandSchema,LocalManagementReceiptSchema,signal,true);return checkedManagementReceipt(parsed,value)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z13.strictObject({semanticStatus:z13.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z14}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(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z14.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728: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":snapshot.evidence?"application/octet-stream":"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.evidenceReceipt??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)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.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()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{Readable as Readable2}from"node:stream";import{createHash as createHash2}from"node:crypto";import{request as request2}from"node:http";async function libraryTransport(options,input,signal){const budget=localBudget(18e4,signal,18e4);let started=false;try{const root=await checkedLocalDirectory(options.stateDirectory),socketPath=localSocketPath(root);await privateAccess(socketPath,"pipe");const authorization=await localAbortable(Promise.resolve().then(()=>options.authorization()),budget.signal);if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(authorization))throw Error();budget.signal.throwIfAborted();const response=await new Promise((resolve,reject)=>{const req=request2({socketPath,method:input.method,path:input.path,signal:budget.signal,headers:{authorization,...input.headers}},resolve);req.on("error",reject);started=true;if(input.body){input.body.once("error",error=>req.destroy(error));input.body.pipe(req)}else req.end()});return{response,close:()=>{budget.close();response.destroy();input.body?.destroy()}}}catch(error){budget.close();input.body?.destroy();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&input.method==="PUT"?"UNKNOWN":"NO_WRITE")}}import{Readable}from"node:stream";var libraryRange=/^bytes=(?:[0-9]+-[0-9]*|-[0-9]+)$/;function expectedRange(range,total){if(!range)return{length:total,header:void 0};const match=/^bytes=(\d*)-(\d*)$/.exec(range);if(!match||!total)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const start=match[1]?Number(match[1]):Math.max(0,total-Number(match[2]));const end=match[1]&&match[2]?Math.min(total-1,Number(match[2])):total-1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start<0||start>=total||end<start)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);return{length:end-start+1,header:`bytes ${start}-${end}/${total}`}}async function readLibraryMedia(options,raw,input={},signal){const value=LocalLibraryGetSchema.parse(raw),method=input.method??"GET";if(method!=="GET"&&method!=="HEAD")throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");if(input.range!==void 0&&(input.range.length>100||!libraryRange.test(input.range)))throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const expected=expectedRange(input.range,value.reference.byteSize);const header=Buffer.from(JSON.stringify(value)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const transfer=await libraryTransport(options,{method,path:"/ipc/v1/library/read",headers:{"x-nvs-library-read":header,...input.range?{range:input.range}:{}}},signal);const{response}=transfer;try{if(response.statusCode===416)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const status=response.statusCode,contentLength=Number(response.headers["content-length"]);if(![200,206].includes(status??0)||!Number.isSafeInteger(contentLength)||contentLength<0||contentLength>value.reference.byteSize||response.headers["content-type"]!==value.reference.contentType)throw Error();const contentRange=response.headers["content-range"];if(status===206){if(!input.range||contentRange!==expected.header||contentLength!==expected.length)throw Error()}else if(input.range||contentRange||contentLength!==value.reference.byteSize)throw Error();const stream=Readable.from((async function*(){let size=0;try{for await(const bytes of response){size+=bytes.length;if(size>contentLength||method==="HEAD")throw Error();yield bytes}if(method!=="HEAD"&&size!==contentLength)throw Error()}finally{transfer.close()}})());stream.once("close",transfer.close);return{stream,contentType:value.reference.contentType,byteSize:value.reference.byteSize,contentLength,httpStatus:status,...contentRange?{contentRange:String(contentRange)}:{}}}catch(error){transfer.close();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}}var NativeStudioLocalLibraryClient=class{constructor(client){this.client=client}client;async capability(signal){return LocalLibraryCapabilitySchema.parse(await this.client.call({operation:"library.capability"},signal))}async call(raw,signal){const input=LocalLibraryCallSchema.parse(raw),data=await this.client.call({operation:"library.call",input},signal);const schema=input.action==="list"?LocalLibraryPageSchema:input.action==="scoped-list"?LocalLibraryProjectionPageSchema:input.action==="scoped-get"?LocalLibraryProjectionSchema.nullable():input.action==="usage"?LocalLibraryUsageSchema:input.action==="read"?LocalLibraryReadReplySchema:["get","import-receipt"].includes(input.action)?LocalLibraryItemSchema.nullable():LocalLibraryItemSchema;const result=schema.parse(data);if(result&&"items"in result&&"limit"in input&&result.items.length>input.limit)throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");if((input.action==="list"||input.action==="scoped-list")&&result&&"items"in result){for(const item of result.items){const label=input.action==="list"&&"title"in item?item.title:"metadata"in item?item.metadata?.label:void 0;if(input.mediaCategory&&mediaCategoryOf(item.reference.contentType)!==input.mediaCategory||input.search&&!label?.toLowerCase().includes(input.search.toLowerCase()))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}}if(input.action==="read"){const value=LocalLibraryReadReplySchema.parse(result),bytes=Buffer.from(value.contentBase64,"base64");const length=Math.min(input.length,Math.max(0,input.reference.byteSize-input.offset));if(value.offset!==input.offset||bytes.toString("base64")!==value.contentBase64||bytes.length!==length||value.complete!==input.offset+length>=input.reference.byteSize)throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}const refs=result&&typeof result==="object"&&"items"in result?result.items.map(item=>item.reference):result&&typeof result==="object"&&"reference"in result?[result.reference]:[];for(const ref of refs){if("reference"in input&&canonicalLocalJson(ref)!==canonicalLocalJson(input.reference)||"tenantId"in input&&(ref.tenantId!==input.tenantId||input.projectId!==void 0&&ref.projectId!==input.projectId||ref.deviceId!==input.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}if("ownerKey"in input&&input.ownerKey&&result&&typeof result==="object"){const owned="items"in result?result.items:"ownerKey"in result?[result]:[];if(owned.some(item=>"ownerKey"in item&&item.ownerKey!==input.ownerKey))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}return result}async import(raw,bytes,signal){const input=LocalLibraryImportSchema.parse(raw),header=Buffer.from(JSON.stringify(input)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const body=Readable2.from((async function*(){let count=0;const hash=createHash2("sha256");for await(const chunk of bytes){const part=Buffer.from(chunk);count+=part.length;if(count>input.reference.byteSize)throw Error("LOCAL_FILE_CHANGED");hash.update(part);yield part}if(count!==input.reference.byteSize||hash.digest("hex")!==input.reference.checksumSha256)throw Error("LOCAL_FILE_CHANGED")})());const transfer=await libraryTransport(this.client.options,{method:"PUT",path:"/ipc/v1/library/import",body,headers:{"x-nvs-request-id":input.requestId,"x-nvs-library-import":header,"content-type":"application/octet-stream","content-length":input.reference.byteSize}},signal);try{let size=0;const parts=[];for await(const part of transfer.response){size+=part.length;if(size>262144)throw Error();parts.push(part)}const reply=LocalIpcResponseSchema.parse(JSON.parse(Buffer.concat(parts).toString()));if(reply.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(reply.error.code,reply.semanticStatus,reply.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const item=LocalLibraryItemSchema.parse(reply.data);if(reply.requestId!==input.requestId||canonicalLocalJson(item.reference)!==canonicalLocalJson(input.reference)||item.ownerKey!==input.ownerKey||item.title!==input.title)throw Error();return item}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_IMPORT_UNKNOWN","BLOCKED","UNKNOWN")}finally{transfer.close()}}media(raw,input={},signal){return readLibraryMedia(this.client.options,raw,input,signal)}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request3}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);library=new NativeStudioLocalLibraryClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,device:{tenantId:initial.tenantId,deviceId:initial.deviceId},authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||current.tenantId!==initial.tenantId||current.deviceId!==initial.deviceId||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:3e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read","library.capability"].includes(call.operation)||call.operation==="library.call"&&["list","get","usage","read","import-receipt","scoped-list","scoped-get","sync"].includes(call.input.action);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=request3({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,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice||this.options.device?{includeDevice:true}:{}},signal));if(this.options.device&&(value.deviceAuthority?.tenantId!==this.options.device.tenantId||value.deviceAuthority.deviceId!==this.options.device.deviceId))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 discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}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(18e4,signal,18e4);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.device&&this.options.device.tenantId!==i.tenantId)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=LocalExecutionInspectInputSchema.parse(raw);if(this.options.device&&this.options.device.tenantId!==input.tenantId)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}};function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{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");let r;try{r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream","user-agent":"NativeStudioDependencyClient"}})}catch{fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}const length=r.headers.get("content-length");if(!r.ok||length!==null&&(!/^[0-9]+$/.test(length)||Number(length)>maximum)){void r.body?.cancel().catch(()=>{});fail(r.status===403?"RELEASE_ACCESS_DENIED":r.status===404?"RELEASE_NOT_PUBLISHED":r.ok?"RELEASE_LIMIT":"RELEASE_UNAVAILABLE")}const reader=r.body?.getReader(),parts=[];let size=0;try{if(reader)while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>maximum)fail("RELEASE_LIMIT");parts.push(part.value)}return Buffer.concat(parts)}catch(error){if(error instanceof Error&&"code"in error&&error.code==="RELEASE_LIMIT")throw error;fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}finally{void reader?.cancel().catch(()=>{});reader?.releaseLock()}}async function catalogue(trust,signal){if(!trust.catalogueUrl||!trust.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));let signed;try{signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()))}catch{fail("RELEASE_METADATA_INVALID")}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):[],...release.resources?Object.values(release.resources):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version,rejected=[]){if(version==="latest"){const candidates=signed.catalogue.releases.filter(r2=>!rejected.includes(r2.descriptor.version)&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch&&Number(process.versions.node.split(".")[0])===r2.descriptor.node.major&&Number(process.versions.node.split(".")[1])>=r2.descriptor.node.minMinor);const latest=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,void 0);if(!latest)fail("VERSION_INCOMPATIBLE");version=latest.descriptor.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{LocalOfflineCallSchema,LocalOfflinePageSchema,LocalAgentGrantSchema,LocalAgentDiscoverySchema,LocalCompositionBrowserSelectionSchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,RuntimeCaptionAssets,LocalRuntimeComponentSchema,LocalManagementInventorySchema,LocalReleaseSchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,LocalResourcePolicySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalAgentSnapshotSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,localAgentSnapshotFromContext,LocalExecutionListInputSchema,LocalExecutionInspectInputSchema,LocalDoctorReportSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,localAgentMediaSnapshot,localAgentMediaProposal,CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,newerVersion,endpoint,catalogue,select,asset};
@@ -1 +0,0 @@
1
- import{canResumeDesktop,desktopAutomation,desktopInstallationIdentity,rememberDesktopAutomation}from"./chunk-IHTF6VEC.js";import{connectDevice,generateDeviceKey}from"./chunk-SDTAJ7FI.js";import{LocalInstallationManager,probeLocalLibrary,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantSpeech,probeTenantTranscription,socketAbsent}from"./chunk-744IEPTK.js";import{DesktopDeviceRecords,DesktopDeviceReplySchema,DesktopDeviceRequestSchema}from"./chunk-GKDGSAI5.js";import{LocalDeviceChallengeSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalPreviewAdmissionSchema,canonicalLocalJson,processorFamilies}from"./chunk-C7CSZFV6.js";import{fail,read,sha256}from"./chunk-RUPH3HZ2.js";import{createPrivateKey as createPrivateKey2,createPublicKey,randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";async function desktopDeviceCapabilities(manager){const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");const root=manager.ledger.slotPath(active);const validation=await probeTenantMediaValidation(root,active);const processing=await probeTenantMediaProcessing(root,active);const processors=processing?Object.keys(processorFamilies).filter(kind=>!["COMPOSITION_RENDER","LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH","SPEECH_SYNTHESIZE","TRANSCRIBE_AUDIO","KEYFRAME_GENERATE","VIDEO_GENERATE","SPEECH_EXTERNAL_QWEN","TRANSCRIBE_EXTERNAL_QWEN"].includes(kind)):[];if(processing){if(await probeLocalLibrary(root,active))processors.push("LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH");if(await probeTenantComposition(root,active))processors.push("COMPOSITION_RENDER");if(await probeTenantSpeech(root,active))processors.push("SPEECH_SYNTHESIZE");if(await probeTenantTranscription(root,active))processors.push("TRANSCRIBE_AUDIO")}return{...validation?{tenantMediaValidation:true}:{},...processors.length?{tenantMediaProcessing:true,processorCapabilities:processors.sort()}:{}}}async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device||s.device.revokedAt)fail("DEVICE_ENROLLMENT_REQUIRED");const capabilities=await desktopDeviceCapabilities(manager);const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const matches=value=>{const saved=value;return saved?.deviceRevision===s.device.revision&&saved.tenantMediaValidation===capabilities.tenantMediaValidation&&saved.tenantMediaProcessing===capabilities.tenantMediaProcessing&&canonicalLocalJson(saved.processorCapabilities??null)===canonicalLocalJson(capabilities.processorCapabilities??null)};const reuse=running&&matches(previous)&&matches(s.connection);const expiresAt=new Date(Date.now()+24*36e5).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",expiresAt,deviceRevision:s.device.revision,...capabilities}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,...capabilities});await manager.start()}const id=randomUUID();await manager.grant({tenantId:s.scope.tenantId,deviceId:s.device.deviceId,expiresAt},records.connectorPath(id));return records.save(s,{connectorId:id,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device||s.device.revokedAt)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const raw=JSON.parse((await read(c.cloudConfigFile,32768)).toString());const{tools:_tools,...transport}=raw;void _tools;const actual=LocalDeviceTransportConfigurationSchema.parse(transport);if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||actual.deviceRevision!==s.connection.deviceRevision||actual.deviceRevision!==s.device.revision||actual.tenantMediaValidation!==s.connection.tenantMediaValidation||actual.tenantMediaProcessing!==s.connection.tenantMediaProcessing||canonicalLocalJson(actual.processorCapabilities??null)!==canonicalLocalJson(s.connection.processorCapabilities??null))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID2}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const started=performance.now();const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)-Date.parse(challenge.issuedAt)<=performance.now()-started)fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.parse(challenge.issuedAt)/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID2(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label,revision:s.device.revision,revokedAt:s.device.revokedAt}:null,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="REVOKE_DEVICE"){if(result?.semanticStatus!=="SUCCESS"||!s.device)fail("DEVICE_RESULT_INVALID");return{device:{...s.device,revision:s.device.revision+1,revokedAt:new Date().toISOString()},connectorId:null,connection:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw,policy){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();if(s.pending&&policy&&!policy.allowedPendingKinds.includes(s.pending.command.kind))fail("DEVICE_COMMAND_UNSUPPORTED");const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});const processingSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantMediaProcessing(manager.ledger.slotPath(active),active)};const librarySupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeLocalLibrary(manager.ledger.slotPath(active),active)};const compositionSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantComposition(manager.ledger.slotPath(active),active)};if(call.action==="media-processing-capability")return DesktopDeviceReplySchema.parse({view:publicView(),mediaProcessingSupported:await processingSupported(),localLibrarySupported:await librarySupported(),compositionProcessingSupported:await compositionSupported()});if(call.action==="media-validation-capability"){const active=(await manager.ledger.current()).value.active;const supported=!!active&&await probeTenantMediaValidation(manager.ledger.slotPath(active),active);return DesktopDeviceReplySchema.parse({view:publicView(),mediaValidationSupported:supported})}if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID3(),label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID3()}}}else{if(call.action!=="revoke"||d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_DEVICE",input:{tenantId:s.scope.tenantId,deviceId:d.deviceId,requestId:randomUUID3(),expectedRevision:d.revision}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint(parsed),phase:"PREPARED"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}export{runDesktopDeviceRequest,desktopDevicePending};