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

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 (77) hide show
  1. package/COMPATIBILITY.json +8 -8
  2. package/components/runtime.json +4 -4
  3. package/components/runtime.tgz +0 -0
  4. package/dist/_chunks/{chunk-WXEERCXN.js → chunk-4M2SOMSN.js} +1 -1
  5. package/dist/_chunks/{chunk-2GV47BUV.js → chunk-4PAVWOPA.js} +1 -1
  6. package/dist/_chunks/{chunk-CTCEGOC7.js → chunk-6EZX2TRX.js} +1 -1
  7. package/dist/_chunks/{chunk-BZPQB66Z.js → chunk-AFNJRZLJ.js} +1 -1
  8. package/dist/_chunks/chunk-APNZQZFB.js +1 -0
  9. package/dist/_chunks/chunk-D74NHT4I.js +45 -0
  10. package/dist/_chunks/chunk-ELUJ44BO.js +1 -0
  11. package/dist/_chunks/{chunk-AIR7YOFU.js → chunk-FVY3PLG7.js} +1 -1
  12. package/dist/_chunks/{chunk-4NCE337I.js → chunk-GLAF74UU.js} +1 -1
  13. package/dist/_chunks/{chunk-GQ32ZQTM.js → chunk-HBDPYWMI.js} +1 -1
  14. package/dist/_chunks/{chunk-5TKBEFRX.js → chunk-IYDHDLTR.js} +1 -1
  15. package/dist/_chunks/{chunk-2MKMGMA4.js → chunk-K35CWLDH.js} +1 -1
  16. package/dist/_chunks/{chunk-HIBT6NXN.js → chunk-L3QA7FLZ.js} +1 -1
  17. package/dist/_chunks/chunk-LBK42NHW.js +1 -0
  18. package/dist/_chunks/{chunk-J2IYRUVM.js → chunk-MLZ3ZPGU.js} +1 -1
  19. package/dist/_chunks/{chunk-PAIJRAJB.js → chunk-NG4BDFEY.js} +1 -1
  20. package/dist/_chunks/chunk-OSO6KRE2.js +1 -0
  21. package/dist/_chunks/chunk-QE7O57PQ.js +1 -0
  22. package/dist/_chunks/{chunk-JL4MUI7K.js → chunk-QK4XPVKT.js} +1 -1
  23. package/dist/_chunks/{chunk-67QDMD7M.js → chunk-ROGOASYF.js} +1 -1
  24. package/dist/_chunks/{chunk-TIHGZGU3.js → chunk-UYKCN5DU.js} +1 -1
  25. package/dist/_chunks/{chunk-5G3AJAKI.js → chunk-XUSVNPR5.js} +1 -1
  26. package/dist/_chunks/component-contract-KXK7WIUI.js +1 -0
  27. package/dist/_chunks/component-preflight-WECLCZLF.js +1 -0
  28. package/dist/_chunks/device-management-TLRUMZL5.js +1 -0
  29. package/dist/_chunks/{device-preflight-QAPMMHWK.js → device-preflight-C7FFUXI2.js} +1 -1
  30. package/dist/_chunks/{devices-inventory-WZ3QAPTS.js → devices-inventory-BZF53UAU.js} +1 -1
  31. package/dist/_chunks/{devices-main-XKRRLX5B.js → devices-main-V3YHCB2C.js} +1 -1
  32. package/dist/_chunks/host-component-Q5IHRHRI.js +1 -0
  33. package/dist/_chunks/host-help-7BGYR4ET.js +1 -0
  34. package/dist/_chunks/host-main-JLIBRHC2.js +1 -0
  35. package/dist/_chunks/{library-main-4BQ2J73H.js → library-main-ATRFEAVN.js} +1 -1
  36. package/dist/_chunks/{local-main-GBC2HPD4.js → local-main-KTYCLHDA.js} +1 -1
  37. package/dist/_chunks/{local-mcp-FXHB3CKF.js → local-mcp-ISMU6ADI.js} +1 -1
  38. package/dist/_chunks/{main-R7DV24KT.js → main-MOZS2EK3.js} +1 -1
  39. package/dist/_chunks/mcp-M2SO3J2H.js +1 -0
  40. package/dist/_chunks/{observe-entry-NKXTUZYF.js → observe-entry-E6DFHIMW.js} +1 -1
  41. package/dist/_chunks/{remote-client-TIFVZEGG.js → remote-client-T75C45JO.js} +1 -1
  42. package/dist/_chunks/render-main-OGCO2LX4.js +1 -0
  43. package/dist/_chunks/series-main-FBERVYWG.js +1 -0
  44. package/dist/_chunks/{source-import-YYRII5FQ.js → source-import-55JJ26AA.js} +1 -1
  45. package/dist/_chunks/src-V2K52JDH.js +1 -0
  46. package/dist/_chunks/{workspace-main-LD56MMI6.js → workspace-main-3P56DSEQ.js} +1 -1
  47. package/dist/_types/cli/local/manager.d.ts +1 -1
  48. package/dist/_types/cli/local/mcp-tools.d.ts +2 -2
  49. package/dist/_types/cli/local/releases.d.ts +1 -0
  50. package/dist/_types/contracts/enterprise-brand.d.ts +302 -0
  51. package/dist/_types/contracts/index.d.ts +6 -0
  52. package/dist/_types/contracts/local-execution/ipc.d.ts +3 -3
  53. package/dist/_types/contracts/local-execution/lifecycle.d.ts +1 -1
  54. package/dist/_types/contracts/local-execution/local-navigation.d.ts +5 -5
  55. package/dist/_types/contracts/render-readiness.d.ts +175 -0
  56. package/dist/_types/contracts/series-canon.d.ts +97 -0
  57. package/dist/_types/contracts/series-character.d.ts +23 -0
  58. package/dist/_types/contracts/series-improvement.d.ts +1639 -0
  59. package/dist/_types/contracts/series-standard.d.ts +1641 -0
  60. package/dist/_types/sdk/local-runtime-client.d.ts +2 -2
  61. package/dist/entry.js +1 -1
  62. package/dist/local-management.js +1 -1
  63. package/dist/local-navigation.js +1 -1
  64. package/package.json +1 -1
  65. package/dist/_chunks/chunk-226SBV53.js +0 -1
  66. package/dist/_chunks/chunk-H46NB5FL.js +0 -1
  67. package/dist/_chunks/chunk-IF6AUKH3.js +0 -1
  68. package/dist/_chunks/chunk-LZPPTW2K.js +0 -1
  69. package/dist/_chunks/chunk-UITIQHVU.js +0 -45
  70. package/dist/_chunks/component-contract-HETXQ2J4.js +0 -1
  71. package/dist/_chunks/device-management-NP7HAXRU.js +0 -1
  72. package/dist/_chunks/host-component-H3Q7TU5Y.js +0 -1
  73. package/dist/_chunks/host-help-SBXGX457.js +0 -1
  74. package/dist/_chunks/host-main-VUEGUFTU.js +0 -1
  75. package/dist/_chunks/mcp-6D4KHCCL.js +0 -1
  76. package/dist/_chunks/render-main-KMP4SMK7.js +0 -1
  77. package/dist/_chunks/src-IX5ZVGZS.js +0 -1
@@ -0,0 +1,45 @@
1
+ import{LocalInstallationManager,ownerClient,runtimeEnvironment,socketAbsent,supportsLoginService,verifySlot,waitStopped}from"./chunk-ELUJ44BO.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-APNZQZFB.js";import{withProfileLock}from"./chunk-7I7ARCY7.js";import{assertExecutable,assertWindowsSystemTool,atomicMove,digestPrivateFile,fail,loginExecutableDigest,loginInputsCurrent,loginPath,loginRevisionName,parseRuntimeLoginApproval,privateAccess,read,runtimeLoginApprovalFile,runtimeLoginProtocol,sha256,syncDirectory,verifyBackup,write}from"./chunk-DLW42PJ6.js";import{execFile}from"node:child_process";import{lstat,mkdir,realpath,unlink}from"node:fs/promises";import{userInfo}from"node:os";import{join,win32}from"node:path";import{setTimeout as wait}from"node:timers/promises";function loginLabel(home){return"com.nativestudio.runtime."+sha256(process.platform==="win32"?home.toLowerCase():home).slice(0,32)}function loginDefinition(home,approval,fingerprint){if(![home,approval.entry.path,approval.node.path].every(loginPath)||!/^[a-f0-9]{64}$/.test(fingerprint))fail("LOGIN_SERVICE_PLAN_INVALID");return{label:loginLabel(home),fingerprint,...approval.supervision&&{supervision:approval.supervision},command:[approval.node.path,"--max-old-space-size=256",approval.entry.path,"serve-login",home,fingerprint]}}var xml=value=>value.replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"})[c]);function launchAgent(definition){return`<?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0"><dict>
4
+ <key>Label</key><string>${definition.label}</string>
5
+ <key>ProgramArguments</key><array>${definition.command.map(v=>`<string>${xml(v)}</string>`).join("")}</array>
6
+ <key>RunAtLoad</key><true/>${definition.supervision?"":"\n <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>"}
7
+ <key>ThrottleInterval</key><integer>20</integer>
8
+ <key>EnvironmentVariables</key><dict>
9
+ <key>NODE_OPTIONS</key><string></string>
10
+ <key>NODE_PATH</key><string></string>
11
+ <key>UV_THREADPOOL_SIZE</key><string>2</string>
12
+ <key>PATH</key><string>/usr/bin:/bin</string>
13
+ </dict>
14
+ </dict></plist>
15
+ `}function systemdUserUnit(definition){const quote=value=>'"'+value.replace(/[\\"]/g,"\\$&").replaceAll("%","%%")+'"';return`[Unit]
16
+ Description=NativeStudio local Runtime
17
+ StartLimitIntervalSec=120
18
+ StartLimitBurst=3
19
+
20
+ [Service]
21
+ Type=simple
22
+ ExecStart=:${definition.command.map(quote).join(" ")}
23
+ Restart=${definition.supervision?"no":"on-failure"}
24
+ RestartSec=20s
25
+ TimeoutStopSec=60s
26
+ UMask=0077
27
+ UnsetEnvironment=NODE_OPTIONS NODE_PATH
28
+ Environment=UV_THREADPOOL_SIZE=2 PATH=/usr/bin:/bin
29
+
30
+ [Install]
31
+ WantedBy=default.target
32
+ `}function windowsLoginTask(definition,sid){if(!/^S-1-(?:\d+-){1,16}\d+$/.test(sid))fail("LOGIN_SERVICE_USER_UNAVAILABLE");if(definition.command.some(value=>/[%"]/.test(value)||value.endsWith("\\")))fail("LOGIN_SERVICE_PATH_UNSUPPORTED");const[node,...args]=definition.command;const action={node,arguments:args.map(arg=>`"${arg}"`).join(" ")};const description="NativeStudio Runtime "+definition.fingerprint;return{action,description,xml:`<?xml version="1.0" encoding="UTF-16"?>
33
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
34
+ <RegistrationInfo><Description>${description}</Description></RegistrationInfo>
35
+ <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${sid}</UserId></LogonTrigger></Triggers>
36
+ <Principals><Principal id="Owner"><UserId>${sid}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
37
+ <Settings>
38
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
39
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
40
+ <Enabled>true</Enabled><ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
41
+ ${definition.supervision?"":"<RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure>"}
42
+ </Settings>
43
+ <Actions Context="Owner"><Exec><Command>${xml(action.node)}</Command><Arguments>${xml(action.arguments)}</Arguments></Exec></Actions>
44
+ </Task>
45
+ `}}function loginPlatform(){const os=process.platform,arch=process.arch;if(!(os==="darwin"&&(arch==="x64"||arch==="arm64")||(os==="linux"||os==="win32")&&arch==="x64"))fail("LOGIN_SERVICE_PLATFORM_UNSUPPORTED");if(process.getuid?.()===0)fail("LOGIN_SERVICE_USER_REQUIRED");return os}async function observeLoginHost(){const platform=loginPlatform();if(platform==="win32")return"CHECK_AT_SERVICE_PLAN";const result=platform==="darwin"?await run("/bin/launchctl",["print",`gui/${process.getuid?.()}`]):await run("/usr/bin/systemctl",["--user","show","--property=Version","--value"]);return result.code===0?"AVAILABLE":"UNAVAILABLE"}function run(executable,args){const env={...runtimeEnvironment(),...process.platform==="linux"&&{DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS,XDG_RUNTIME_DIR:process.env.XDG_RUNTIME_DIR??"/run/user/"+process.getuid?.()}};return new Promise(resolve=>{const child=execFile(executable,args,{shell:false,env,timeout:8e3,maxBuffer:128*1024,windowsHide:true,encoding:"buffer"},(error,stdout,stderr)=>{const decode=b=>b[0]===255&&b[1]===254?b.subarray(2).toString("utf16le"):b[1]===0?b.toString("utf16le"):b.toString();resolve({code:error?typeof error.code==="number"?error.code:null:0,stdout:decode(stdout),stderr:decode(stderr)})});child.stdin?.on("error",()=>{});child.stdin?.end()})}async function requireSuccess(executable,args){if((await run(executable,args)).code!==0)fail("LOGIN_SERVICE_OS_UNCONFIRMED")}async function userDirectory(segments,create=false){const info=userInfo();let root=await realpath(info.homedir);for(const segment of["",...segments]){root=join(root,segment);if(create&&segment)await mkdir(root,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await lstat(root);if(!stat.isDirectory()||stat.isSymbolicLink()||stat.uid!==info.uid||stat.mode&18)fail("LOGIN_SERVICE_LOCATION_UNSAFE")}return root}async function fileState(file,content){try{return(await read(file,65536)).equals(Buffer.from(content))?"OWNED":"FOREIGN"}catch(error){return error.code==="ENOENT"?"ABSENT":"FOREIGN"}}async function removeFile(file,content){const state=await fileState(file,content);if(state==="FOREIGN")fail("LOGIN_SERVICE_CONFLICT");if(state==="OWNED"){await unlink(file);await syncDirectory(join(file,".."))}}async function installFile(file,content){const state=await fileState(file,content);if(state==="FOREIGN")fail("LOGIN_SERVICE_CONFLICT");if(state==="ABSENT")await write(file,content,true)}async function unixScheduler(definition,os){const mac=os==="darwin",uid=process.getuid?.(),domain=`gui/${uid}`,target=`${domain}/${definition.label}`,dirs=mac?["Library","LaunchAgents"]:[".config","systemd","user"],command=mac?"/bin/launchctl":"/usr/bin/systemctl",name=definition.label+(mac?".plist":".service"),content=mac?launchAgent(definition):systemdUserUnit(definition);const accountHome=await realpath(userInfo().homedir);const file=join(accountHome,...dirs,name);const fileStatus=async()=>{try{await userDirectory(dirs)}catch(error){if(error.code==="ENOENT")return"ABSENT";return"FOREIGN"}return fileState(file,content)};const inspect=async()=>{const saved2=await fileStatus();if(saved2==="FOREIGN")return"CONFLICT";if(mac){const result2=await run(command,["print",target]);if(result2.code===0){const loadedFrom=/^\s*path = (.*)$/m.exec(result2.stdout)?.[1];const loadedProgram=/^\s*program = (.*)$/m.exec(result2.stdout)?.[1];return saved2==="OWNED"&&loadedFrom===file&&loadedProgram===definition.command[0]?"REGISTERED":"CONFLICT"}if(result2.code===113&&/Could not find service/i.test(result2.stderr))return saved2==="ABSENT"?"ABSENT":"INCOMPLETE";return"UNAVAILABLE"}const result=await run(command,["--user","show",name,"--property=LoadState,FragmentPath,UnitFileState,DropInPaths"]);const fields=Object.fromEntries(result.stdout.trim().split("\n").filter(line=>line.includes("=")).map(line=>{const delimiter=line.indexOf("=");return[line.slice(0,delimiter),line.slice(delimiter+1)]}));if(fields.LoadState==="not-found"&&result.code!==null)return saved2==="ABSENT"?"ABSENT":"INCOMPLETE";if(result.code!==0)return"UNAVAILABLE";if(saved2!=="OWNED"||fields.FragmentPath!==file||fields.DropInPaths)return"CONFLICT";return fields.LoadState==="loaded"&&fields.UnitFileState==="enabled"?"REGISTERED":"INCOMPLETE"};return{inspect,async install(){await userDirectory(dirs,true);await installFile(file,content);if(mac)await requireSuccess(command,["bootstrap",domain,file]);else{await requireSuccess(command,["--user","daemon-reload"]);await requireSuccess(command,["--user","enable",name])}},async start(){await requireSuccess(command,mac?["kickstart",target]:["--user","start",name])},async remove(){const state=await inspect();if(state==="ABSENT")return;if(!["REGISTERED","INCOMPLETE"].includes(state))fail("LOGIN_SERVICE_OS_UNCONFIRMED");if(mac&&state==="REGISTERED"){await run(command,["bootout",target]);const deadline=Date.now()+3e3;for(;;){const observed=await inspect();if(observed==="INCOMPLETE"||observed==="ABSENT")break;if(observed==="CONFLICT")fail("LOGIN_SERVICE_CONFLICT");if(Date.now()>=deadline)fail("LOGIN_SERVICE_OS_UNCONFIRMED");await wait(150)}}if(!mac)await requireSuccess(command,["--user","disable",name]);await removeFile(file,content);if(!mac)await requireSuccess(command,["--user","daemon-reload"])}}}function xmlText(value){return value.replace(/&(amp|lt|gt|quot|apos);/g,(_,code)=>({amp:"&",lt:"<",gt:">",quot:'"',apos:"'"})[code])}function matchesWindowsLoginTask(source,expected,sid){const section=tag=>new RegExp(`<${tag}(?:\\s[^>]*)?>\\s*([\\s\\S]*?)\\s*</${tag}>`).exec(source)?.[1];const actions=section("Actions"),trigger=section("Triggers"),principal=section("Principals");if(!actions||!trigger||!principal||/<!|<\?(?!xml\s)/i.test(source))return false;const exec=/^<Exec>\s*<Command>([^<]*)<\/Command>\s*<Arguments>([^<]*)<\/Arguments>\s*<\/Exec>$/.exec(actions);return!!exec&&xmlText(exec[1])===expected.action.node&&xmlText(exec[2])===expected.action.arguments&&section("Description")===expected.description&&(expected.xml.includes("<RestartOnFailure>")||!/<RestartOnFailure\b/i.test(source))&&/^<LogonTrigger>\s*[\s\S]*?\s*<\/LogonTrigger>$/.test(trigger)&&!trigger.slice(1).includes("<LogonTrigger")&&trigger.includes(`<UserId>${sid}</UserId>`)&&/^<Principal(?:\s[^>]*)?>[\s\S]*<\/Principal>$/.test(principal)&&!principal.slice(1).includes("<Principal")&&principal.includes(`<UserId>${sid}</UserId>`)&&principal.includes("<LogonType>InteractiveToken</LogonType>")&&principal.includes("<RunLevel>LeastPrivilege</RunLevel>")}async function windowsScheduler(home,definition){const system=process.env.SystemRoot??process.env.SYSTEMROOT;if(!system||!/^[A-Z]:\\[^%"\r\n]+$/i.test(system))fail("LOGIN_SERVICE_OS_UNCONFIRMED");const directory=win32.join(system,"System32"),command=win32.join(directory,"schtasks.exe"),whoami=win32.join(directory,"whoami.exe"),task="\\"+definition.label;await assertWindowsSystemTool(command);await assertWindowsSystemTool(whoami);const identity=await run(whoami,["/user","/fo","csv","/nh"]);const sid=/,"(S-1-(?:\d+-){1,16}\d+)"\s*$/i.exec(identity.stdout.trim())?.[1];if(identity.code!==0||!sid)fail("LOGIN_SERVICE_USER_UNAVAILABLE");const expected=windowsLoginTask(definition,sid);const inspect=async()=>{const result=await run(command,["/query","/tn",task,"/xml","/hresult"]);if(result.code!==null&&[2,2147942402].includes(result.code>>>0))return"ABSENT";if(result.code!==0)return"UNAVAILABLE";if(!matchesWindowsLoginTask(result.stdout,expected,sid))return"CONFLICT";return/<Enabled>\s*false\s*<\/Enabled>/i.test(result.stdout)?"INCOMPLETE":"REGISTERED"};const file=join(home,"runtime-login-task.xml");const bytes=Buffer.from("\uFEFF"+expected.xml,"utf16le");const stagedTask=async()=>{const stored=await read(file,65536).catch(error=>{if(error.code==="ENOENT")return null;throw error});if(stored&&!stored.equals(bytes))fail("LOGIN_SERVICE_CONFLICT");return stored};return{inspect,async install(){if(!await stagedTask())await write(file,bytes,true);await requireSuccess(command,["/create","/tn",task,"/xml",file])},async start(){await requireSuccess(command,["/run","/tn",task])},async remove(){const stored=await stagedTask(),state=await inspect();if(state!=="ABSENT"){if(!["REGISTERED","INCOMPLETE"].includes(state))fail("LOGIN_SERVICE_OS_UNCONFIRMED");await requireSuccess(command,["/delete","/tn",task,"/f"])}if(stored)await unlink(file)}}}function loginScheduler(home,definition,platform){return platform==="win32"?windowsScheduler(home,definition):unixScheduler(definition,platform)}import{realpath as realpath2,unlink as unlink2}from"node:fs/promises";import{join as join2}from"node:path";import{setTimeout as wait2}from"node:timers/promises";var disablingFile="runtime-login-disabling.json";var deviceConfiguration=LocalDeviceTransportConfigurationSchema.safeExtend({tools:LocalToolSelectionSchema});function loginCommand(value){return value==="service-plan"||value==="service-enable"||value==="service-status"||value==="service-start"||value==="service-disable"}async function saved(home,file){try{const bytes=await read(join2(home,file),32768);return{bytes,value:parseRuntimeLoginApproval(bytes),fingerprint:sha256(bytes)}}catch(error){if(error.code==="ENOENT")return null;fail("LOGIN_SERVICE_RECEIPT_INVALID")}}async function plan(manager,supervision){const{active,transition,revision}=(await manager.ledger.current()).value;if(transition)fail("ACTIVATION_IN_PROGRESS");if(!active)fail("INSTALL_REQUIRED");const home=manager.ledger.root,root=manager.ledger.slotPath(active);await verifySlot(root,active);if(!await supportsLoginService(root))fail("LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED");const configuration=await read(join2(home,"configuration.json"));const c=await manager.configuration();if(!c.cloudConfigFile)fail("DEVICE_CONNECTION_REQUIRED");const parsed=JSON.parse(configuration.toString());if(parsed.stateDirectory!==c.stateDirectory||parsed.cloudConfigFile!==c.cloudConfigFile)fail("LOGIN_SERVICE_PLAN_CHANGED");const node=await realpath2(process.execPath);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(node))fail("LOGIN_SERVICE_NODE_LOCATION_UNSUPPORTED");await assertExecutable(node);const pin=async path=>({path,sha256:sha256(await read(path,32768))});const deviceBytes=await read(c.cloudConfigFile,32768);const{tenantId,deviceId,deviceRevision}=deviceConfiguration.parse(JSON.parse(deviceBytes.toString()));const value={protocol:runtimeLoginProtocol,revision,version:active.descriptor.version,stateDirectory:c.stateDirectory,configurationSha256:sha256(configuration),revisionSha256:sha256(await read(join2(home,"revisions",loginRevisionName(revision)),262144,true)),node:{path:node,sha256:await loginExecutableDigest(node)},entry:{path:join2(root,"dist/entry.js"),sha256:active.files["dist/entry.js"]},device:{path:c.cloudConfigFile,sha256:sha256(deviceBytes)},tools:active.toolsConfigPath?await pin(active.toolsConfigPath):null,...supervision&&{supervision}};const bytes=Buffer.from(canonicalLocalJson(value));parseRuntimeLoginApproval(bytes);if(!await loginInputsCurrent(home,value,read))fail("LOGIN_SERVICE_PLAN_CHANGED");return{bytes,value,fingerprint:sha256(bytes),device:{tenantId,deviceId,deviceRevision}}}async function running(value){try{await privateAccess(value.stateDirectory,"directory")}catch{return"UNCONFIRMED"}if(await socketAbsent(value.stateDirectory))return"STOPPED";try{const status=await(await ownerClient(value.stateDirectory)).status();const entry=status.versions.find(v=>v.component==="RUNTIME")?.executablePath;return!entry?"UNCONFIRMED":entry===value.entry.path?"RUNNING":"OTHER_RUNTIME"}catch{return"UNCONFIRMED"}}async function drain(value){const state=await running(value);if(state==="STOPPED"||state==="OTHER_RUNTIME")return;if(state!=="RUNNING")fail("LOGIN_SERVICE_RUNTIME_UNCONFIRMED");const client=await ownerClient(value.stateDirectory),inventory=await client.inventory();const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:inventory.runtimeRevision});if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,value.stateDirectory);await waitStopped(value.stateDirectory)}async function runLoginService(command,path,approval,supervision){const platform=loginPlatform();const base={protocol:runtimeLoginProtocol,platform,architecture:process.arch};const manager=await LocalInstallationManager.openExisting(path);const absent=(observed=false)=>({...base,registration:observed?"ABSENT":"UNOBSERVED",binding:"NONE"});if(!manager){if(command==="service-status")return absent();fail("INSTALL_REQUIRED")}const home=await realpath2(manager.ledger.root),permit=join2(home,runtimeLoginApprovalFile);const current=async()=>await saved(home,runtimeLoginApprovalFile);const disabling=async()=>await saved(home,disablingFile);const scheduler=receipt=>loginScheduler(home,loginDefinition(home,receipt.value,receipt.fingerprint),platform);const status=async()=>{const disabled=await disabling(),receipt=disabled??await current();if(!receipt)return absent();const{value,fingerprint}=receipt;let binding=disabled?"DISABLING":"STALE";if(!disabled&&await loginInputsCurrent(home,value,read)){try{if(await loginExecutableDigest(value.node.path)===value.node.sha256&&await digestPrivateFile(value.entry.path,64*1024*1024)===value.entry.sha256)binding="CURRENT"}catch{}}return{...base,binding,fingerprint,runtimeVersion:value.version,installationRevision:value.revision,...value.supervision&&{supervision:value.supervision},registration:await(await scheduler(receipt)).inspect(),runtime:await running(value)}};if(command==="service-status")return status();if(command==="service-plan"){const{value,fingerprint,device}=await plan(manager,supervision);return{...base,fingerprint,device,runtimeVersion:value.version,installationRevision:value.revision}}if(!approval||!/^[a-f0-9]{64}$/.test(approval))fail("USER_APPROVAL_REQUIRED");return withProfileLock(permit,async()=>{const disabled=await disabling(),existing=await current();if(command==="service-enable"){if(disabled)fail("LOGIN_SERVICE_DISABLE_PENDING");const proposed=await plan(manager,supervision);if(proposed.fingerprint!==approval)fail("LOGIN_SERVICE_PLAN_CHANGED");if(existing&&existing.fingerprint!==approval)fail("LOGIN_SERVICE_REPLACE_REQUIRED");const target2=await scheduler(proposed);const observed2=await target2.inspect();if(observed2==="CONFLICT")fail("LOGIN_SERVICE_CONFLICT");if(observed2==="UNAVAILABLE")fail("LOGIN_SERVICE_OS_UNCONFIRMED");if(!existing)await write(permit,proposed.bytes,true);if(!await loginInputsCurrent(home,proposed.value,read))fail("LOGIN_SERVICE_PLAN_CHANGED");if(observed2!=="REGISTERED")await target2.install();const result=await status();if(result.registration!=="REGISTERED")fail("LOGIN_SERVICE_OS_UNCONFIRMED");return result}const receipt=disabled??existing;if(!receipt){if(command==="service-start"||command==="service-restart")fail("LOGIN_SERVICE_UNAVAILABLE");return absent()}if(receipt.fingerprint!==approval)fail("LOGIN_SERVICE_PLAN_CHANGED");const target=await scheduler(receipt);if(command==="service-disable"){if(!disabled){await atomicMove(permit,join2(home,disablingFile),false)}const observed2=await target.inspect();if(observed2==="CONFLICT")fail("LOGIN_SERVICE_CONFLICT");if(observed2==="UNAVAILABLE")fail("LOGIN_SERVICE_OS_UNCONFIRMED");if(observed2!=="ABSENT")await drain(receipt.value);await target.remove();if(await target.inspect()!=="ABSENT")fail("LOGIN_SERVICE_OS_UNCONFIRMED");await unlink2(join2(home,disablingFile));await syncDirectory(home);return absent(true)}const observed=await status();if(observed.binding!=="CURRENT"||observed.registration!=="REGISTERED")fail("LOGIN_SERVICE_UNAVAILABLE");if(observed.runtime==="UNCONFIRMED"||observed.runtime==="OTHER_RUNTIME")fail("LOGIN_SERVICE_RUNTIME_UNCONFIRMED");if(command==="service-restart"){if(receipt.value.supervision!=="EXPLICIT_RECOVERY")fail("LOGIN_SERVICE_CONFLICT");await drain(receipt.value)}if(observed.runtime!=="RUNNING"||command==="service-restart"){await target.start();const deadline=Date.now()+25e3;while(await running(receipt.value)!=="RUNNING"){if(Date.now()>=deadline)fail("LOGIN_SERVICE_RUNTIME_UNCONFIRMED");await wait2(150)}}await manager.reconnect();return status()})}export{observeLoginHost,loginCommand,runLoginService};
@@ -0,0 +1 @@
1
+ import{LocalCompositionBrowserSelectionSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeComponentSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,RuntimeCaptionAssets,asset,catalogue,newerVersion,select}from"./chunk-6EZX2TRX.js";import{canonicalLocalJson,importedNormalizationValidationProfile,localLibraryProfile,referenceThumbnailProfile,tenantRenderValidationProfile,whisperCppRecognitionProfile}from"./chunk-APNZQZFB.js";import{assertExecutable,digestPrivateFile,directory,entries,fail,localSocketPath,optional,privateAccess,read,runtimeLoginProtocol,sha256,sha512,verifyBackup,write}from"./chunk-DLW42PJ6.js";import{z}from"zod";import{constants,createReadStream}from"node:fs";import{open,realpath}from"node:fs/promises";import{isAbsolute}from"node:path";import{createHash}from"node:crypto";var InstalledToolPathsSchema=z.strictObject({mode:z.literal("INSTALLED").optional(),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096),compositionBrowser:z.string().min(1).max(4096).optional(),captionAssetsDirectory:z.string().min(1).max(4096).optional(),whisper:z.strictObject({binary:z.string().min(1).max(4096),model:z.string().min(1).max(4096)}).optional()});async function toolPreference(previous,cloud,explicit){if(explicit)return LocalToolChoiceSchema.parse(explicit);const raw=previous?JSON.parse((await read(previous,32768)).toString()):cloud?JSON.parse((await read(cloud,32768)).toString()).tools:null;const selected=raw?LocalToolSelectionSchema.parse(raw):null;return selected?.mode==="INSTALLED"?{...selected,mode:"INSTALLED"}:{mode:"MANAGED",...selected?.cpuSpeech?{cpuSpeech:selected.cpuSpeech}:{}}}async function captureInstalledTools(input,host=process){const paths=InstalledToolPathsSchema.parse(input);if(paths.compositionBrowser&&(host.platform!=="linux"||host.arch!=="x64"))fail("COMPOSITION_BROWSER_PLATFORM_UNAVAILABLE");if(paths.whisper&&(host.platform!=="darwin"||host.arch!=="arm64"))fail("LOCAL_PROFILE_UNAVAILABLE");async function capture(candidate,executable=true){if(!isAbsolute(candidate))fail("TOOL_PATH_INVALID");const path=await realpath(candidate);if(executable)await assertExecutable(path);const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await file.stat();if(!before.isFile()||before.size<1||before.size>256*1024*1024)fail("TOOL_PATH_INVALID");const h=createHash("sha256");let count=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){count+=chunk.length;if(count>before.size)fail("TOOL_CHANGED");h.update(chunk)}const after=await file.stat();if(count!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs)fail("TOOL_CHANGED");return{path,digest:h.digest("hex")}}finally{await file.close()}}const compositionBrowser=paths.compositionBrowser?await capture(paths.compositionBrowser):void 0;if(compositionBrowser&&!LocalCompositionBrowserSelectionSchema.safeParse(compositionBrowser).success)fail("COMPOSITION_BROWSER_INTEGRITY_INVALID");const model=paths.whisper?await capture(paths.whisper.model,false):void 0;if(model&&model.digest!==whisperCppRecognitionProfile.modelSha256)fail("LOCAL_ASR_IDENTITY_MISMATCH");const binary=paths.whisper?await capture(paths.whisper.binary):void 0;if(paths.captionAssetsDirectory&&!isAbsolute(paths.captionAssetsDirectory))fail("CAPTION_ASSET_LOCATION_INVALID");return LocalToolChoiceSchema.parse({mode:"INSTALLED",ffmpeg:await capture(paths.ffmpeg),ffprobe:await capture(paths.ffprobe),...compositionBrowser?{compositionBrowser}:{},...paths.captionAssetsDirectory?{captionAssetsDirectory:await realpath(paths.captionAssetsDirectory)}:{},...binary&&model?{whisper:{binaryPath:binary.path,binarySha256:binary.digest,modelPath:model.path}}:{}})}import{constants as constants2}from"node:fs";import{open as open2}from"node:fs/promises";import{createHash as createHash2}from"node:crypto";async function bytesAt(base,name,maximum){const f=await open2(new URL(name,base),constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const stat=await f.stat();if(!stat.isFile()||stat.size<1||stat.size>maximum)fail("BUNDLED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let used=0;while(used<bytes.length){const{bytesRead}=await f.read(bytes,used,bytes.length-used,null);if(!bytesRead)break;used+=bytesRead}if(used!==stat.size)fail("BUNDLED_COMPONENT_CHANGED");return bytes.subarray(0,used)}finally{await f.close()}}async function readEmbeddedRuntime(base,manifestDigest){const raw=await bytesAt(base,"components/runtime.json",32768);if(sha256(raw)!==manifestDigest)fail("BUNDLED_COMPONENT_CHANGED");const component=LocalRuntimeComponentSchema.parse(JSON.parse(raw.toString()));const product=JSON.parse((await bytesAt(base,"package.json",32768)).toString());if(product.name!=="@nativestudio/cli"||product.version!==component.version)fail("BUNDLED_COMPONENT_IDENTITY_INVALID");const bytes=await bytesAt(base,"components/runtime.tgz",64*1024*1024);if(bytes.length!==component.byteSize||createHash2("sha512").update(bytes).digest("hex")!==component.sha512)fail("BUNDLED_COMPONENT_INTEGRITY_INVALID");const descriptor=LocalRuntimeDescriptorSchema.parse({...component.descriptor,platform:{os:process.platform,architecture:process.arch}});return{component,bytes,descriptor,trustFingerprint:manifestDigest}}async function embeddedRuntime(version){if(false)return null;const base=new URL(".",import.meta.resolve("@nativestudio/cli/package.json"));const value=await readEmbeddedRuntime(base,"d142c923fafc6e8047cd28ec08824e284817c7895dfd3d519c472ca56420b136");return version&&version!=="latest"&&version!==value.component.version?null:value}async function installationSource(c,version,bundled,dependencies){if(!bundled){const trusted2=await catalogue(c);return{release:select(trusted2.signed,version,c.rejectedVersions),origin:trusted2.origin,catalogueFingerprint:trusted2.fingerprint,trustFingerprint:trusted2.trustFingerprint,expiresAt:trusted2.signed.catalogue.expiresAt}}const core=await embeddedRuntime(version);if(!core||c.rejectedVersions.includes(core.descriptor.version))fail("BUNDLED_VERSION_UNAVAILABLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==core.descriptor.node.major||minor<core.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");const trusted=dependencies?await catalogue(c):null;const remote=trusted?select(trusted.signed,core.descriptor.version):null;if(remote&&(remote.package.sha512!==core.component.sha512||remote.package.byteSize!==core.component.byteSize||canonicalLocalJson(remote.descriptor)!==canonicalLocalJson(core.descriptor)||remote.resources&&(remote.resources.captions.sha512!==core.component.resources.captions.sha512||remote.resources.captions.byteSize!==core.component.resources.captions.byteSize)))fail("BUNDLED_COMPONENT_RELEASE_MISMATCH");return{release:{descriptor:core.descriptor,package:{source:"CLI",byteSize:core.component.byteSize,sha512:core.component.sha512},tools:remote?.tools??null,...remote?.resources?{resources:remote.resources}:{}},origin:trusted?.origin??"",catalogueFingerprint:trusted?.fingerprint??null,trustFingerprint:trusted?sha256(canonicalLocalJson([core.trustFingerprint,trusted.trustFingerprint])):core.trustFingerprint,expiresAt:trusted?.signed.catalogue.expiresAt??new Date(Date.now()+18e5).toISOString()}}async function approvedSource(c,plan){const source=await installationSource(c,plan.release.descriptor.version,"source"in plan.release.package,plan.catalogueFingerprint!==null);if(Date.parse(plan.expiresAt)<=Date.now()||source.trustFingerprint!==plan.trustFingerprint||canonicalLocalJson(source.release)!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");return source}function needsDependencyChannel(c,choice,haveCaptions=false){return!!choice&&(choice.mode==="MANAGED"&&!choice.reuseMedia||choice.mode==="INSTALLED"&&!choice.captionAssetsDirectory&&!haveCaptions&&!!c.catalogueUrl&&!!c.publicKeyFile)}var requiredRuntimeFiles=["package.json","dist/entry.js","dist/supervisor.mjs","dist/parent-lifetime.mjs","dist/execution-identity.json"];var allowedRuntimeFiles=new Set([...requiredRuntimeFiles,"README.md","LICENSE","dist/THIRD_PARTY_NOTICES.md","dist/BUNDLED_DEPENDENCIES.json","dist/agent-supervisor.mjs","dist/kokoro-worker.mjs","dist/capture.mjs","dist/hyperframe.manifest.json","dist/hyperframe.runtime.iife.js","dist/hyperframe-gsap.js","dist/hyperframe-dependencies.json","dist/hyperframe-notices.txt","dist/captions/NotoSansSC.ttf","dist/captions/NativeStudioSC-Regular.ttf","dist/captions/OFL.txt",...["helper.exe","helper.json"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open as open3}from"node:fs/promises";import{dirname,join,delimiter}from"node:path";import{z as z2}from"zod";var runtimeEnvironment=()=>({...Object.fromEntries(["HOME","USER","LOGNAME","TMPDIR","CODEX_HOME","SystemRoot","SYSTEMROOT","USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP"].flatMap(k=>process.env[k]?[[k,process.env[k]]]:[])),PATH:dirname(process.execPath)+(process.platform==="win32"?"":delimiter+["/usr/bin","/bin"].join(delimiter)),LANG:"C",LC_ALL:"C",UV_THREADPOOL_SIZE:"2",NVS_INSTALL_OWNER:"MANAGED"});async function verifySlot(root,slot){if(requiredRuntimeFiles.some(name=>!Object.hasOwn(slot.files,name)))fail("SLOT_FILES_MISSING");for(const[name,hash]of Object.entries(slot.files)){if(!allowedRuntimeFiles.has(name))fail("SLOT_PATH_INVALID");if(await digestPrivateFile(join(root,name),64*1024*1024)!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probeEntry(root,option,args=[]){return new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),option,...args],{env:runtimeEnvironment(),stdio:["ignore","pipe","ignore"],shell:false});const parts=[];let size=0;const timer=setTimeout(()=>child.kill("SIGKILL"),1e4);child.stdout.on("data",b=>{size+=b.length;if(size>65536)child.kill("SIGKILL");else parts.push(b)});child.on("error",reject);child.on("close",code=>{clearTimeout(timer);if(code!==0||size>65536)reject(Error("Runtime descriptor unavailable"));else resolve(Buffer.concat(parts))})})}async function probeProfile(root,slot,option,profile){await verifySlot(root,slot);try{const digest=(await probeEntry(root,option)).toString().trim();return digest===sha256(canonicalLocalJson(profile))}catch{return false}}function probeTenantMediaValidation(root,slot){return probeProfile(root,slot,"--tenant-media-validation-profile",tenantRenderValidationProfile)}function probeTenantMediaProcessing(root,slot){return probeProfile(root,slot,"--tenant-media-processing-profile",importedNormalizationValidationProfile)}function probeReferenceThumbnail(root,slot){return probeProfile(root,slot,"--reference-thumbnail-profile",referenceThumbnailProfile)}async function probeLocalLibrary(root,slot){await verifySlot(root,slot);try{return(await probeEntry(root,"--local-library-profile")).toString().trim()===sha256(canonicalLocalJson(localLibraryProfile))}catch{return false}}async function probeTenantComposition(root,slot){if(process.platform!=="linux"||process.arch!=="x64"||!slot.toolsConfigPath)return false;const selected=LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString()));if(selected.mode!=="INSTALLED"||!selected.compositionBrowser)return false;await verifySlot(root,slot);try{const result=await probeEntry(root,"--tenant-composition-capability",["--tools-config",slot.toolsConfigPath]);return result.toString().trim()===selected.compositionBrowser.digest}catch{return false}}async function probeTenantSpeech(root,slot){if(process.platform!=="darwin")return false;await verifySlot(root,slot);try{return/^[a-f0-9]{64}$/.test((await probeEntry(root,"--tenant-speech-capability")).toString().trim())}catch{return false}}async function probeTenantTranscription(root,slot){if(process.platform!=="darwin"||process.arch!=="arm64"||!slot.toolsConfigPath)return false;await verifySlot(root,slot);try{return/^[a-f0-9]{64}$/.test((await probeEntry(root,"--tenant-transcription-capability",["--tools-config",slot.toolsConfigPath])).toString().trim())}catch{return false}}async function probeTenantQwenGeneration(root,slot,kind){await verifySlot(root,slot);return probeEntry(root,`--tenant-qwen-${kind}-capability`).then(value=>value.toString().trim()==="QWEN_"+kind.toUpperCase()+"_V1",()=>false)}async function probe(root,expected){const bytes=await probeEntry(root,"--describe");const descriptor=LocalRuntimeDescriptorSchema.parse(JSON.parse(bytes.toString()));if(canonicalLocalJson(descriptor)!==canonicalLocalJson(expected))fail("RUNTIME_DESCRIPTOR_MISMATCH");return descriptor}function supportsLoginService(root){return probeEntry(root,"--login-protocol").then(output=>output.toString().trim()===runtimeLoginProtocol,()=>false)}async function ownerClient(stateDirectory){await directory(stateDirectory);return new NativeStudioLocalRuntimeClient({stateDirectory,authorization:async()=>"Bearer "+(await read(join(stateDirectory,"control-token"),128)).toString()})}async function runningInventory(client,root,slot){const inventory=await client.inventory(),status=await client.status();if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(slot.descriptor)||status.versions.find(v=>v.component==="RUNTIME")?.executablePath!==join(root,"dist/entry.js"))fail("RUNTIME_ALREADY_RUNNING");return inventory}async function launch(root,slot,stateDirectory,cloudConfig,toolsConfig){await verifySlot(root,slot);await probe(root,slot.descriptor);await directory(stateDirectory);const existing=await ownerClient(stateDirectory);try{return await runningInventory(existing,root,slot)}catch(e){if(e instanceof Error&&e.message.includes("RUNTIME_ALREADY_RUNNING"))throw e}const log=await open3(join(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:runtimeEnvironment(),detached:true,windowsHide:true,stdio:["ignore",log.fd,log.fd],shell:false});let spawnError=false;child.once("error",()=>{spawnError=true});child.unref();await log.close();const deadline=Date.now()+15e3;while(Date.now()<deadline){if(spawnError||child.exitCode!==null)fail("RUNTIME_START_FAILED");try{return await runningInventory(existing,root,slot)}catch{}await new Promise(r=>setTimeout(r,100))}child.kill("SIGTERM");fail("RUNTIME_START_UNCONFIRMED")}async function waitStopped(stateDirectory){const client=await ownerClient(stateDirectory),deadline=Date.now()+1e4;while(Date.now()<deadline){try{await client.inventory()}catch{const{lstat:lstat3}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat3(localSocketPath(stateDirectory))}catch(e){if(e.code==="ENOENT")return}const{createConnection}=await import("node:net");const closed=await new Promise(resolve=>{const s=createConnection(localSocketPath(stateDirectory));s.once("connect",()=>{s.destroy();resolve(false)});s.once("error",e=>resolve(["ECONNREFUSED","ENOENT"].includes(e.code??"")));s.setTimeout(300,()=>{s.destroy();resolve(false)})});if(closed)return}await new Promise(r=>setTimeout(r,100))}fail("RUNTIME_STOP_UNCONFIRMED")}async function socketAbsent(stateDirectory){const{createConnection}=await import("node:net");return new Promise(resolve=>{const socket=createConnection(localSocketPath(stateDirectory));socket.once("connect",()=>{socket.destroy();resolve(false)});socket.once("error",error=>resolve(["ECONNREFUSED","ENOENT"].includes(error.code??"")));socket.setTimeout(500,()=>{socket.destroy();resolve(false)})})}async function probeTools(root,stateDirectory,selection){const{execFile}=await import("node:child_process");const diagnostic=z2.strictObject({tool:z2.enum(["FFMPEG","FFPROBE"]),stage:z2.enum(["IDENTITY","VERSION","ENCODERS","DECODERS","FILTERS","DEMUXERS","MUXERS","FINAL_IDENTITY"]),cause:z2.enum(["IDENTITY_INVALID","VERSION_INVALID","CAPABILITY_MISSING","PROCESS_FAILED","TIMEOUT","CANCELLED"])});const failures=[];for(let attempt=0;attempt<2;attempt++){const result=await new Promise((resolve,reject)=>execFile(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:runtimeEnvironment(),timeout:5e4,maxBuffer:65536},(error,stdout,stderr)=>error?reject(Error("Tool probe failed")):resolve({stdout,stderr})));const report=LocalDoctorReportSchema.parse(JSON.parse(result.stdout));let failure;for(const line of result.stderr.split("\n")){try{const parsed=diagnostic.safeParse(JSON.parse(line).toolProbe);if(parsed.success)failure=parsed.data}catch{}}if(failure)failures.push(failure);if(failures.length)await write(join(stateDirectory,"tool-qualification.json"),JSON.stringify({checkedAt:new Date().toISOString(),availability:report.availability,failures}));if(report.availability==="AVAILABLE")return report;if(!failure||!["TIMEOUT","PROCESS_FAILED"].includes(failure.cause))break}fail("TOOL_QUALIFICATION_FAILED")}import{constants as constants3}from"node:fs";import{open as open4,chmod}from"node:fs/promises";import{join as join2,isAbsolute as isAbsolute2}from"node:path";import{gunzipSync}from"node:zlib";function packageFiles(bytes,allowed2,directories){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024});const files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0)){if(!data.subarray(offset).every(b=>b===0))fail("PACKAGE_FORMAT_INVALID");break}const text=(a,b)=>header.subarray(a,b).toString().replace(/\0.*$/s,"");const number=(a,b)=>{const v=text(a,b).trim();if(!/^[0-7]+$/.test(v))fail("PACKAGE_FORMAT_INVALID");return parseInt(v,8)};const sum=number(148,156);let actual=0;for(let i=0;i<512;i++)actual+=i>=148&&i<156?32:header[i];if(actual!==sum||!text(257,263).startsWith("ustar"))fail("PACKAGE_FORMAT_INVALID");const prefix=text(345,500),path=(prefix?prefix+"/":"")+text(0,100),size=number(124,136),kind=text(156,157);if(!Number.isSafeInteger(size)||size<0||offset+512+size>data.length)fail("PACKAGE_FORMAT_INVALID");if(kind==="5"){if(!directories.test(path)||size!==0)fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowed2.has(path.slice(8))||files.has(path.slice(8)))fail("PACKAGE_PATH_INVALID");files.set(path.slice(8),data.subarray(offset+512,offset+512+size))}offset+=512+Math.ceil(size/512)*512}return files}var names=Object.keys(RuntimeCaptionAssets);var allowed=new Set(names.map(n=>"dist/captions/"+n));async function captionDirectory(path){if(!isAbsolute2(path))fail("CAPTION_ASSET_LOCATION_INVALID");const files=new Map;for(const name of names){const f=await open4(join2(path,name),constants3.O_RDONLY|constants3.O_NOFOLLOW|constants3.O_NONBLOCK);try{const s=await f.stat();if(!s.isFile()||s.size<1||s.size>20*1024*1024)fail("CAPTION_ASSET_INVALID");const bytes=Buffer.alloc(s.size+1);let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used!==s.size||sha256(bytes.subarray(0,used))!==RuntimeCaptionAssets[name])fail("CAPTION_ASSET_INVALID");files.set("dist/captions/"+name,bytes.subarray(0,used))}finally{await f.close()}}return files}async function verifyCaptionDirectory(path){await captionDirectory(path)}async function managedCaptions(ledger,resource,origin){const path=join2(await directory(join2(ledger.root,"resources")),resource.sha512+".tgz");let bytes;let downloaded=false;try{bytes=await read(path,resource.byteSize)}catch(e){if(e.code!=="ENOENT")throw e;bytes=await asset(resource,origin);downloaded=true}if(bytes.length!==resource.byteSize||sha512(bytes)!==resource.sha512)fail("CAPTION_RESOURCE_INTEGRITY_INVALID");const files=packageFiles(bytes,allowed,/^package(?:\/dist(?:\/captions)?)?\/?$/);if(files.size!==names.length)fail("CAPTION_ASSET_INVALID");for(const name of names)if(sha256(files.get("dist/captions/"+name))!==RuntimeCaptionAssets[name])fail("CAPTION_ASSET_INVALID");if(downloaded){try{await write(path,bytes,true)}catch(e){if(e.code!=="EEXIST")throw e;const existing=await read(path,resource.byteSize);if(existing.length!==resource.byteSize||sha512(existing)!==resource.sha512)fail("CAPTION_RESOURCE_INTEGRITY_INVALID")}}return files}async function stageResources(ledger,candidate,previous,plan,origin){const root=ledger.slotPath(candidate);const present=[...allowed].filter(p=>candidate.files[p]);if(present.length){await captionDirectory(join2(root,"dist/captions"));return candidate}const choice=plan.toolSelection;let files;if(choice?.mode==="INSTALLED"&&choice.captionAssetsDirectory)files=await captionDirectory(choice.captionAssetsDirectory);else if(previous&&[...allowed].some(p=>previous.files[p]))files=await captionDirectory(join2(ledger.slotPath(previous),"dist/captions"));else if(plan.release.resources)files=await managedCaptions(ledger,plan.release.resources.captions,origin);if(!files)return candidate;await directory(join2(root,"dist/captions"));const hashes={...candidate.files};for(const[path,bytes]of files){await write(join2(root,path),bytes,true);await chmod(join2(root,path),256);hashes[path]=sha256(bytes)}return{...candidate,files:hashes}}async function verifyManagedMedia(previous,reuse){if(!previous)fail("MANAGED_TOOLS_UNAVAILABLE");const current=LocalToolSelectionSchema.parse(JSON.parse((await read(previous,32768)).toString()));if(current.mode!=="MANAGED"||canonicalLocalJson({schemaVersion:1,ffmpeg:current.ffmpeg,ffprobe:current.ffprobe})!==canonicalLocalJson(reuse))fail("MANAGED_TOOLS_CHANGED");const files=await captureInstalledTools({ffmpeg:reuse.ffmpeg.path,ffprobe:reuse.ffprobe.path});if(files.mode!=="INSTALLED"||canonicalLocalJson(files.ffmpeg)!==canonicalLocalJson(reuse.ffmpeg)||canonicalLocalJson(files.ffprobe)!==canonicalLocalJson(reuse.ffprobe))fail("MANAGED_TOOLS_CHANGED");return{mode:"MANAGED",ffmpeg:current.ffmpeg,ffprobe:current.ffprobe}}import{randomUUID}from"node:crypto";import{lstat}from"node:fs/promises";import{join as join3}from"node:path";function toolIdentity(tools){return[tools.ffmpeg.digest,tools.ffprobe.digest,...tools.cpuSpeech?[canonicalLocalJson({...tools.cpuSpeech,voiceIds:[...tools.cpuSpeech.voiceIds].sort((a,b)=>a-b)})]:[],...tools.mode==="INSTALLED"&&tools.compositionBrowser?[tools.compositionBrowser.digest]:[],...tools.mode==="INSTALLED"&&tools.whisper?[tools.whisper.binarySha256,whisperCppRecognitionProfile.modelSha256]:[]].join(":")}async function identity(path,cloud){if(!path)return null;const raw=JSON.parse((await read(path,32768)).toString());const tools=LocalToolSelectionSchema.parse(cloud?raw.tools:raw);return toolIdentity(tools)}async function effective(path,cloud){return path?identity(path,false):identity(cloud,true)}function supportedRenderer(expected,digest){return expected.rendererDigest===digest||!!expected.compatibleRenderers?.some(r=>r.rendererDigest===digest)}async function assertPendingCompatible(raw,expected,previous,next,cloud){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingRenderers.some(d=>!supportedRenderer(expected,d)))fail("NATIVE_RECOVERY_REQUIRED");if(i.pendingExecutions+i.pendingRequests===0)return;if(i.descriptor.profileDigest!==expected.profileDigest&&!expected.compatibleRenderers?.some(r=>r.profileDigest===i.descriptor.profileDigest))fail("NATIVE_RECOVERY_REQUIRED");const before=await effective(previous,cloud);const after=await effective(next,cloud);if(!before||before!==after)fail("NATIVE_RECOVERY_REQUIRED")}async function assertPendingToolIdentity(raw,previous,cloud,next){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingExecutions+i.pendingRequests>0&&await effective(previous,cloud)!==next)fail("NATIVE_RECOVERY_REQUIRED")}async function assertNoStoppedJournal(state){for(const suffix of["","-wal","-shm","-journal"]){try{await lstat(join3(state,"journal.sqlite"+suffix))}catch(e){if(e.code==="ENOENT")continue;throw e}fail("RUNTIME_STATUS_REQUIRED")}}async function prepareInstallation(manager,version,raw,bundled=false){const c=await manager.configuration(),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const explicit=raw===void 0?void 0:LocalToolChoiceSchema.parse(raw),source=await installationSource(c,version,bundled,needsDependencyChannel(c,explicit,Object.entries(RuntimeCaptionAssets).every(([name,hash])=>current.active?.files["dist/captions/"+name]===hash))),release=source.release,preference=await toolPreference(current.active?.toolsConfigPath??null,c.cloudConfigFile,explicit),toolSelection=explicit||preference.mode==="INSTALLED"||release.tools?preference:void 0;if(toolSelection?.mode==="MANAGED"){if(toolSelection.reuseMedia)await verifyManagedMedia(current.active?.toolsConfigPath??null,toolSelection.reuseMedia);else if(!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE")}let runtimeRevision=null;try{const inventory=await(await ownerClient(c.stateDirectory)).inventory();runtimeRevision=inventory.runtimeRevision;const previous=current.active?.toolsConfigPath??null;await assertPendingCompatible(inventory,release.descriptor,previous,previous,c.cloudConfigFile);const desired=preference.mode==="INSTALLED"?preference:preference.reuseMedia??release.tools;if(desired)await assertPendingToolIdentity(inventory,previous,c.cloudConfigFile,preference.mode==="INSTALLED"?toolIdentity(preference):preference.reuseMedia?toolIdentity({mode:"MANAGED",ffmpeg:preference.reuseMedia.ffmpeg,ffprobe:preference.reuseMedia.ffprobe,...preference.cpuSpeech?{cpuSpeech:preference.cpuSpeech}:{}}):release.tools.ffmpeg.sha256+":"+release.tools.ffprobe.sha256+(preference.cpuSpeech?":"+canonicalLocalJson({...preference.cpuSpeech,voiceIds:[...preference.cpuSpeech.voiceIds].sort((a,b)=>a-b)}):""))}catch(e){if(e instanceof Error&&e.message.includes("NATIVE_RECOVERY_REQUIRED"))throw e;if(!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await assertNoStoppedJournal(c.stateDirectory)}const body={protocol:"NVS_LOCAL_UPDATE_PLAN_V1",planId:randomUUID(),installationRevision:current.revision,runtimeRevision,catalogueFingerprint:source.catalogueFingerprint,trustFingerprint:source.trustFingerprint,release,...toolSelection?{toolSelection}:{},createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(source.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join3(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}import{randomUUID as randomUUID2}from"node:crypto";import{join as join4,dirname as dirname2}from"node:path";import{z as z3}from"zod";async function grant(manager,raw,output){const i=z3.strictObject({tenantId:z3.uuid(),deviceId:z3.uuid(),expiresAt:z3.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname2(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join4(manager.ledger.root,"grants",randomUUID2()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,tenantId:i.tenantId,deviceId:i.deviceId,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-JJ6YOULB.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join4(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z3.strictObject({tenantId:z3.uuid(),deviceId:z3.uuid(),expiresAt:z3.iso.datetime({offset:true}),output:z3.string().min(1)}).parse(await optional(join4(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",tenantId:g.tenantId,deviceId:g.deviceId,expiresAt:g.expiresAt});await write(g.output,canonicalLocalJson(connector));renewed++}catch{blocked++}}return{renewed,blocked}}import{randomUUID as randomUUID4}from"node:crypto";import{join as join9}from"node:path";import{z as z5}from"zod";import{z as z4}from"zod";import{join as join5}from"node:path";var slotSchema=z4.strictObject({id:z4.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z4.string().nullable().default(null),files:z4.record(z4.string().min(1).max(100),z4.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z4.strictObject({id:z4.uuid(),planId:z4.uuid(),fingerprint:z4.string().regex(/^[0-9a-f]{64}$/),phase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z4.string().nullable(),failedPhase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z4.strictObject({revision:z4.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z4.strictObject({previous:z4.string().nullable(),value:installationSchema,digest:z4.string().regex(/^[0-9a-f]{64}$/)});var InstallationLedger=class _InstallationLedger{constructor(root){this.root=root}root;static async open(path){const root=await directory(path);for(const name of["revisions","plans","slots","grants"])await directory(join5(root,name));return new _InstallationLedger(root)}static async openExisting(root){try{await privateAccess(root,"directory");await privateAccess(join5(root,"revisions"),"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _InstallationLedger(root)}current(){return this.load()}async hadCompletedVersion(version){let found=false;await this.load(entry=>{if(!entry.transition&&entry.active?.descriptor.version===version)found=true});return found}async load(visit){const names2=(await entries(join5(this.root,"revisions"))).filter(n=>/^\d{12}\.json$/.test(n)).sort();let previous=null,value={revision:0,active:null,transition:null};for(const[i,name]of names2.entries()){const raw=JSON.parse((await read(join5(this.root,"revisions",name),262144,true)).toString());const r=recordSchema.parse(raw);const expected=sha256(canonicalLocalJson({previous:raw.previous,value:raw.value}));if(r.value.revision!==i+1||r.previous!==previous||r.digest!==expected)fail("INSTALLATION_HISTORY_INVALID");previous=r.digest;value=r.value;visit?.(value)}return{value,digest:previous}}async commit(expected,next){const current=await this.current();if(current.value.revision!==expected.revision)fail("REVISION_CONFLICT");const value=installationSchema.parse({...next,revision:expected.revision+1});const record={previous:current.digest,value,digest:sha256(canonicalLocalJson({previous:current.digest,value}))};try{await write(join5(this.root,"revisions",String(value.revision).padStart(12,"0")+".json"),canonicalLocalJson(record),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return value}slotPath(slot){return join5(this.root,"slots",slot.id)}};import{randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod3}from"node:fs/promises";import{join as join7}from"node:path";import{chmod as chmod2}from"node:fs/promises";import{join as join6}from"node:path";async function unpack(bytes,root,expectedVersion){const files=packageFiles(bytes,allowedRuntimeFiles,/^package(?:\/dist(?:\/(?:native|captions))?)?\/?$/);if(!requiredRuntimeFiles.every(p=>files.has(p)))fail("PACKAGE_FILES_MISSING");const manifest=JSON.parse(files.get("package.json").toString());const deps=manifest.dependencies;if(manifest.name!=="@nativestudio/local-runtime"||manifest.version!==expectedVersion||manifest.type!=="module"||Object.keys(deps??{}).length||Object.keys(manifest.optionalDependencies??{}).length||["preinstall","install","postinstall","prepare"].some(name=>Object.hasOwn(manifest.scripts??{},name))||!["dist/entry.js","./dist/entry.js"].includes(manifest.bin?.["nvs-runtime"]??"")||Object.keys(manifest.bin??{}).length!==1)fail("PACKAGE_IDENTITY_INVALID");const hashes={};await directory(join6(root,"dist"));if([...files.keys()].some(p=>p.startsWith("dist/native/")))await directory(join6(root,"dist/native"));if([...files.keys()].some(p=>p.startsWith("dist/captions/")))await directory(join6(root,"dist/captions"));for(const[path,contents]of files){await write(join6(root,path),contents,true);await chmod2(join6(root,path),path.endsWith("entry.js")?320:256);hashes[path]=sha256(contents)}return hashes}async function stage(ledger,release,origin){const id=randomUUID3(),root=await directory(join7(ledger.root,"slots",id));const bundled=await embeddedRuntime(release.descriptor.version);if(bundled&&(bundled.component.byteSize!==release.package.byteSize||bundled.component.sha512!==release.package.sha512))fail("BUNDLED_COMPONENT_RELEASE_MISMATCH");if("source"in release.package&&!bundled)fail("BUNDLED_VERSION_UNAVAILABLE");const bytes=bundled?.bytes??("url"in release.package?await asset(release.package,origin):fail("BUNDLED_VERSION_UNAVAILABLE")),files=await unpack(bytes,root,release.descriptor.version);const slot={id,files,descriptor:release.descriptor,toolsConfigPath:null};await probe(root,slot.descriptor);return slot}async function managedTools(release,origin,stateDirectory,selectionId,cpuSpeech){if(!release.tools)return null;const result={};for(const name of["ffmpeg","ffprobe"]){const a=release.tools[name],dir=await directory(join7(stateDirectory,"tools",a.sha256)),path2=join7(dir,name+(process.platform==="win32"?".exe":""));try{if(sha256(await read(path2,256*1024*1024))!==a.sha256)fail("TOOL_INTEGRITY_INVALID")}catch(e){if(e.code!=="ENOENT")throw e;const bytes=await asset(a,origin);if(sha256(bytes)!==a.sha256)fail("TOOL_INTEGRITY_INVALID");await write(path2,bytes,true);await chmod3(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe,...cpuSpeech?{cpuSpeech}:{}};const path=join7(await directory(join7(stateDirectory,"tool-selections")),selectionId+".json");await write(path,JSON.stringify(selection));return path}async function selectedTools(release,origin,state,slotId,cloudConfig,previousSelection,explicit){const preference=await toolPreference(previousSelection,cloudConfig,explicit);if(preference.mode==="INSTALLED"){const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");const selection={...preference};delete selection.captionAssetsDirectory;await write(path,JSON.stringify(selection),true);return path}if(preference.mode==="MANAGED"&&preference.reuseMedia){const media=await verifyManagedMedia(previousSelection,preference.reuseMedia);const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");await write(path,JSON.stringify({...media,...preference.cpuSpeech?{cpuSpeech:preference.cpuSpeech}:{}}),true);return path}if(explicit?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");return await managedTools(release,origin,state,slotId,preference.cpuSpeech)??previousSelection}import{lstat as lstat2,opendir}from"node:fs/promises";import{join as join8}from"node:path";async function containsLibraryFiles(root){let visited=0;async function walk(path,depth){if(depth>8||++visited>1e4)fail("NATIVE_RECOVERY_REQUIRED");const info=await lstat2(path);if(info.isFile()){await privateAccess(path,"file");return true}if(!info.isDirectory()||info.isSymbolicLink())fail("NATIVE_RECOVERY_REQUIRED");await privateAccess(path,"directory");const directory2=await opendir(path,{bufferSize:16});for await(const entry of directory2)if(await walk(join8(path,entry.name),depth+1))return true;return false}const library=join8(root,"library");try{await lstat2(library)}catch(error){if(error.code==="ENOENT")return false;throw error}try{return await walk(library,0)}catch(error){if(error.code==="ENOENT")fail("NATIVE_RECOVERY_REQUIRED");throw error}}async function assertLibraryCompatible(configuration,root,slot){let configured=false;if(configuration.cloudConfigFile){try{const value=JSON.parse((await read(configuration.cloudConfigFile,32768)).toString());if(!value||typeof value!=="object"||Array.isArray(value))fail("NATIVE_RECOVERY_REQUIRED");const capabilities=value.processorCapabilities;if(capabilities!==void 0&&!Array.isArray(capabilities))fail("NATIVE_RECOVERY_REQUIRED");configured=Array.isArray(capabilities)&&capabilities.some(kind=>kind==="LOCAL_MEDIA_INSPECT"||kind==="LOCAL_MEDIA_PUBLISH")}catch(error){if(error instanceof SyntaxError)fail("NATIVE_RECOVERY_REQUIRED");throw error}}if(!configured&&!await containsLibraryFiles(configuration.stateDirectory))return;if(!await probeLocalLibrary(root,slot))fail("NATIVE_RECOVERY_REQUIRED")}var configurationSchema=z5.strictObject({stateDirectory:z5.string().min(1).max(4096),catalogueUrl:z5.string().url().nullable().default(null),publicKeyFile:z5.string().min(1).max(4096).nullable().default(null),cloudConfigFile:z5.string().nullable().default(null),notifications:z5.boolean().default(true),rejectedVersions:z5.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])}).refine(c=>!!c.catalogueUrl===!!c.publicKeyFile,"Release channel requires URL and key together");var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}static async openExisting(root){const ledger=await InstallationLedger.openExisting(root);return ledger?new _LocalInstallationManager(ledger):null}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join9(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join9(this.ledger.root,"configuration.json"));if(!value)fail("CONFIGURATION_REQUIRED");return configurationSchema.parse(value)}async status(){const s=(await this.ledger.current()).value;let c;try{c=await this.configuration()}catch(error){if(error instanceof Error&&error.message.includes("CONFIGURATION_REQUIRED"))return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,running:null,phase:s.transition?.phase??"IDLE",nextActions:[{surface:"CLI",operation:"local.configure",availability:"AVAILABLE",reason:"INSTALL_REQUIRED"}]};throw error}let running=null;try{running=await(await ownerClient(c.stateDirectory)).status()}catch{}return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,entryPath:s.active?join9(this.ledger.slotPath(s.active),"dist/entry.js"):null,installOwner:"MANAGED",phase:s.transition?.phase??"IDLE",running,nextActions:[{surface:"CLI",operation:s.transition?"local.update.reconcile":s.active?"local.start":"local.install",availability:"AVAILABLE",reason:s.transition?"RECOVERY_REQUIRED":s.active?"READY":"INSTALL_REQUIRED"}]}}async reject(version){LocalRuntimeDescriptorSchema.shape.version.parse(version);const c=await this.configuration();await this.configure({...c,rejectedVersions:[...new Set([...c.rejectedVersions,version])]});return{rejected:true,version,selectedVersion:(await this.ledger.current()).value.active?.descriptor.version??null}}async check(){const c=await this.configuration();if(!c.catalogueUrl)return{installation:await this.status(),channel:"UNCONFIGURED",available:[],notifications:c.notifications,rejectedVersions:c.rejectedVersions};const v=await catalogue(c);return{installation:await this.status(),catalogueFingerprint:v.fingerprint,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),notifications:c.notifications,rejectedVersions:c.rejectedVersions}}prepare(version,choice){return prepareInstallation(this,version,choice)}prepareBundled(version,choice){return prepareInstallation(this,version,choice,true)}async plan(id){if(!z5.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join9(this.ledger.root,"plans",id+".json"))).toString()));const{fingerprint,...body}=p;if(sha256(canonicalLocalJson(body))!==fingerprint)fail("PLAN_CHANGED");return p}async transition(s,phase,patch={}){if(!s.transition)fail("TRANSITION_REQUIRED");return this.ledger.commit(s,{active:s.active,transition:{...s.transition,...patch,phase}})}async apply(id,approval){const plan=await this.plan(id),c=await this.configuration();if(approval!==plan.fingerprint)fail("USER_APPROVAL_REQUIRED");const source=await approvedSource(c,plan);let s=(await this.ledger.current()).value;if(s.revision!==plan.installationRevision||s.transition)fail("REVISION_CONFLICT");if(plan.runtimeRevision!==null){const i=await(await ownerClient(c.stateDirectory)).inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(plan.release.descriptor,d)))fail("REVISION_CONFLICT")}if(plan.runtimeRevision===null){if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory)}s=await this.ledger.commit(s,{active:s.active,transition:{id:randomUUID4(),planId:id,fingerprint:approval,phase:"STAGING",previous:s.active,candidate:null,backupPath:null,failedPhase:null}});try{let candidate=await stage(this.ledger,plan.release,source.origin);candidate=await stageResources(this.ledger,candidate,s.active,plan,source.origin);await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);const tools=await selectedTools(plan.release,source.origin,c.stateDirectory,candidate.id,c.cloudConfigFile,s.active?.toolsConfigPath??null,plan.toolSelection);candidate={...candidate,toolsConfigPath:tools};if(tools)await probeTools(this.ledger.slotPath(candidate),c.stateDirectory,tools);s=await this.transition(s,"STAGED",{candidate});if(plan.runtimeRevision!==null){const client=await ownerClient(c.stateDirectory),i=await client.inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(candidate.descriptor,d)))fail("REVISION_CONFLICT");await assertPendingCompatible(i,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile);await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);s=await this.transition(s,"DRAINING");const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:plan.runtimeRevision});if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,c.stateDirectory);s=await this.transition(s,"ACTIVATING",{backupPath:result.backupPath});await waitStopped(c.stateDirectory);await assertPendingCompatible("inventory"in result?result.inventory:null,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile)}else{if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory);s=await this.transition(s,"ACTIVATING")}await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);s=await this.ledger.commit(s,{active:candidate,transition:{...s.transition,phase:"VERIFYING"}});await this.startSlot(candidate,c);s=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{activated:true,revision:s.revision,version:candidate.descriptor.version}}catch(error){const actual=(await this.ledger.current()).value;if(actual.transition?.planId===id)await this.transition(actual,"ROLLBACK_REQUIRED",{failedPhase:actual.transition.phase});throw error}}async startSlot(slot,c){await assertLibraryCompatible(c,this.ledger.slotPath(slot),slot);return launch(this.ledger.slotPath(slot),slot,c.stateDirectory,c.cloudConfigFile??void 0,slot.toolsConfigPath??void 0)}async start(){const s=(await this.ledger.current()).value;if(s.transition)fail("ACTIVATION_IN_PROGRESS");if(!s.active)fail("INSTALL_REQUIRED");const c=await this.configuration(),inventory=await this.startSlot(s.active,c);const clients=await this.reconnect();let updateNotice={status:"DISABLED"};if(c.notifications&&c.catalogueUrl){try{const v=await catalogue(c,AbortSignal.timeout(1500));updateNotice={status:"CHECKED",versions:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&newerVersion(r.descriptor.version,s.active.descriptor.version)&&!c.rejectedVersions.includes(r.descriptor.version)).map(r=>r.descriptor.version)}}catch{updateNotice={status:"UNAVAILABLE"}}}return{...inventory,clients,updateNotice}}async stop(){const c=await this.configuration(),client=await ownerClient(c.stateDirectory),i=await client.inventory();const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:i.runtimeRevision});await waitStopped(c.stateDirectory);return result}async reconcile(id,approval){const s=(await this.ledger.current()).value,c=await this.configuration();if(!s.transition||s.transition.planId!==id||s.transition.fingerprint!==approval)fail("USER_APPROVAL_REQUIRED");if(s.active?.id===s.transition.previous?.id&&["STAGING","STAGED"].includes(s.transition.failedPhase??s.transition.phase)){const next2=await this.ledger.commit(s,{active:s.transition.previous,transition:null});return{rolledBack:true,revision:next2.revision,version:next2.active?.descriptor.version??null}}const candidate=s.transition.candidate;if(candidate){await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);try{const i=await runningInventory(await ownerClient(c.stateDirectory),this.ledger.slotPath(candidate),candidate);if(canonicalLocalJson(i.descriptor)===canonicalLocalJson(candidate.descriptor)){await verifySlot(this.ledger.slotPath(candidate),candidate);const next2=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{recovered:true,revision:next2.revision,version:candidate.descriptor.version}}}catch{}}const previous=s.transition.previous;if(previous)await assertLibraryCompatible(c,this.ledger.slotPath(previous),previous);await waitStopped(c.stateDirectory);const next=await this.ledger.commit(s,{active:previous,transition:null});if(previous)await this.startSlot(previous,c);await this.reconnect();return{rolledBack:true,revision:next.revision,version:previous?.descriptor.version??null}}grant(raw,output){return grant(this,raw,output)}reconnect(){return reconnect(this)}};export{InstalledToolPathsSchema,toolPreference,captureInstalledTools,embeddedRuntime,installationSource,runtimeEnvironment,verifySlot,probeTenantMediaValidation,probeTenantMediaProcessing,probeReferenceThumbnail,probeLocalLibrary,probeTenantComposition,probeTenantSpeech,probeTenantTranscription,probeTenantQwenGeneration,supportsLoginService,ownerClient,waitStopped,socketAbsent,verifyCaptionDirectory,LocalInstallationManager};
@@ -1 +1 @@
1
- import{embeddedRuntime,runtimeEnvironment,toolPreference,verifySlot}from"./chunk-IF6AUKH3.js";import{CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,LocalToolSelectionSchema}from"./chunk-CTCEGOC7.js";import{canonicalLocalJson}from"./chunk-LZPPTW2K.js";import{directory,fail,read,write}from"./chunk-DLW42PJ6.js";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{join}from"node:path";import{unlink}from"node:fs/promises";async function assertCpuPreparationCurrent(manager,original,planRevision=original.revision){const current=(await manager.ledger.current()).value;const configuration=await manager.configuration();if(current.revision!==original.revision||planRevision!==original.revision||canonicalLocalJson(configuration)!==canonicalLocalJson(original.configuration))fail("REVISION_CONFLICT")}async function prepareInstalledCpuSpeech(manager,raw){const input=CpuSpeechPrepareInputSchema.parse(raw),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");if(!current.active)fail("INSTALLATION_REQUIRED");const slot=current.active,root=manager.ledger.slotPath(slot),configuration=await manager.configuration();const context={revision:current.revision,configuration};await verifySlot(root,slot);const file=join(await directory(join(manager.ledger.root,"preparations")),randomUUID()+".json");await write(file,JSON.stringify(input),true);try{const prepared=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--prepare-cpu-speech","--state-dir",configuration.stateDirectory,"--input-config",file],{env:runtimeEnvironment(),stdio:["ignore","pipe","pipe","ipc"],shell:false});const parts=[],errors=[];let used=0,errorBytes=0,killed=false;const timer=setTimeout(()=>{killed=true;child.kill("SIGTERM")},23e4);const kill=setTimeout(()=>{killed=true;child.kill("SIGKILL")},235e3);const abort=()=>{killed=true;child.kill("SIGTERM")};process.once("SIGINT",abort);process.once("SIGTERM",abort);child.stdout.on("data",chunk=>{used+=chunk.length;if(used>32768)child.kill("SIGTERM");else parts.push(chunk)});child.stderr.on("data",chunk=>{errorBytes+=chunk.length;if(errorBytes>4096)child.kill("SIGTERM");else errors.push(chunk)});child.once("error",reject);child.once("close",code=>{clearTimeout(timer);clearTimeout(kill);process.off("SIGINT",abort);process.off("SIGTERM",abort);try{if(killed)fail("CPU_PREPARATION_CANCELLED");if(code!==0||used>32768||errorBytes>4096){const last=Buffer.concat(errors).toString().trim().split("\n").at(-1);let reason;try{reason=JSON.parse(last??"{}").error?.code}catch{}if(reason==="CPU_BZIP2_REQUIRED")fail("CPU_BZIP2_REQUIRED");if(reason==="CPU_SPEECH_PLATFORM_UNAVAILABLE")fail("CPU_SPEECH_PLATFORM_UNAVAILABLE");fail("CPU_PREPARATION_FAILED")}resolve(CpuSpeechPreparedSchema.parse(JSON.parse(Buffer.concat(parts).toString())))}catch(error){reject(error)}})});await assertCpuPreparationCurrent(manager,context);const previous=await toolPreference(slot.toolsConfigPath,configuration.cloudConfigFile);const existing=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;const reuseMedia=previous.mode==="MANAGED"&&existing?.mode==="MANAGED"?{schemaVersion:1,ffmpeg:existing.ffmpeg,ffprobe:existing.ffprobe}:void 0;const choice={...previous,cpuSpeech:prepared.selection,...reuseMedia?{reuseMedia}:{}};const plan=await embeddedRuntime(slot.descriptor.version)?await manager.prepareBundled(slot.descriptor.version,choice):await manager.prepare(slot.descriptor.version,choice);await assertCpuPreparationCurrent(manager,context,plan.installationRevision);return{semanticStatus:"PREPARED",capability:prepared.capability,reused:prepared.reused,plan}}finally{await unlink(file).catch(error=>{if(error.code!=="ENOENT")throw error})}}export{prepareInstalledCpuSpeech};
1
+ import{embeddedRuntime,runtimeEnvironment,toolPreference,verifySlot}from"./chunk-ELUJ44BO.js";import{CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import{canonicalLocalJson}from"./chunk-APNZQZFB.js";import{directory,fail,read,write}from"./chunk-DLW42PJ6.js";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{join}from"node:path";import{unlink}from"node:fs/promises";async function assertCpuPreparationCurrent(manager,original,planRevision=original.revision){const current=(await manager.ledger.current()).value;const configuration=await manager.configuration();if(current.revision!==original.revision||planRevision!==original.revision||canonicalLocalJson(configuration)!==canonicalLocalJson(original.configuration))fail("REVISION_CONFLICT")}async function prepareInstalledCpuSpeech(manager,raw){const input=CpuSpeechPrepareInputSchema.parse(raw),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");if(!current.active)fail("INSTALLATION_REQUIRED");const slot=current.active,root=manager.ledger.slotPath(slot),configuration=await manager.configuration();const context={revision:current.revision,configuration};await verifySlot(root,slot);const file=join(await directory(join(manager.ledger.root,"preparations")),randomUUID()+".json");await write(file,JSON.stringify(input),true);try{const prepared=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--prepare-cpu-speech","--state-dir",configuration.stateDirectory,"--input-config",file],{env:runtimeEnvironment(),stdio:["ignore","pipe","pipe","ipc"],shell:false});const parts=[],errors=[];let used=0,errorBytes=0,killed=false;const timer=setTimeout(()=>{killed=true;child.kill("SIGTERM")},23e4);const kill=setTimeout(()=>{killed=true;child.kill("SIGKILL")},235e3);const abort=()=>{killed=true;child.kill("SIGTERM")};process.once("SIGINT",abort);process.once("SIGTERM",abort);child.stdout.on("data",chunk=>{used+=chunk.length;if(used>32768)child.kill("SIGTERM");else parts.push(chunk)});child.stderr.on("data",chunk=>{errorBytes+=chunk.length;if(errorBytes>4096)child.kill("SIGTERM");else errors.push(chunk)});child.once("error",reject);child.once("close",code=>{clearTimeout(timer);clearTimeout(kill);process.off("SIGINT",abort);process.off("SIGTERM",abort);try{if(killed)fail("CPU_PREPARATION_CANCELLED");if(code!==0||used>32768||errorBytes>4096){const last=Buffer.concat(errors).toString().trim().split("\n").at(-1);let reason;try{reason=JSON.parse(last??"{}").error?.code}catch{}if(reason==="CPU_BZIP2_REQUIRED")fail("CPU_BZIP2_REQUIRED");if(reason==="CPU_SPEECH_PLATFORM_UNAVAILABLE")fail("CPU_SPEECH_PLATFORM_UNAVAILABLE");fail("CPU_PREPARATION_FAILED")}resolve(CpuSpeechPreparedSchema.parse(JSON.parse(Buffer.concat(parts).toString())))}catch(error){reject(error)}})});await assertCpuPreparationCurrent(manager,context);const previous=await toolPreference(slot.toolsConfigPath,configuration.cloudConfigFile);const existing=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;const reuseMedia=previous.mode==="MANAGED"&&existing?.mode==="MANAGED"?{schemaVersion:1,ffmpeg:existing.ffmpeg,ffprobe:existing.ffprobe}:void 0;const choice={...previous,cpuSpeech:prepared.selection,...reuseMedia?{reuseMedia}:{}};const plan=await embeddedRuntime(slot.descriptor.version)?await manager.prepareBundled(slot.descriptor.version,choice):await manager.prepare(slot.descriptor.version,choice);await assertCpuPreparationCurrent(manager,context,plan.installationRevision);return{semanticStatus:"PREPARED",capability:prepared.capability,reused:prepared.reused,plan}}finally{await unlink(file).catch(error=>{if(error.code!=="ENOENT")throw error})}}export{prepareInstalledCpuSpeech};
@@ -1 +1 @@
1
- import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-LZPPTW2K.js";import{boundedRemoteFetch,secureEndpoint}from"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId,options={}){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});const stop=()=>{void client.close().catch(()=>{})};options.signal?.throwIfAborted();options.signal?.addEventListener("abort",stop,{once:true});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:boundedRemoteFetch(options.maxJsonBytes??32*1024*1024,options.signal)});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client,...options.maxJsonBytes?{maxJsonBytes:options.maxJsonBytes}:{}}),close:()=>{options.signal?.removeEventListener("abort",stop);return client.close()}}}catch{options.signal?.removeEventListener("abort",stop);await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
1
+ import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-APNZQZFB.js";import{boundedRemoteFetch,secureEndpoint}from"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId,options={}){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});const stop=()=>{void client.close().catch(()=>{})};options.signal?.throwIfAborted();options.signal?.addEventListener("abort",stop,{once:true});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:boundedRemoteFetch(options.maxJsonBytes??32*1024*1024,options.signal)});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client,...options.maxJsonBytes?{maxJsonBytes:options.maxJsonBytes}:{}}),close:()=>{options.signal?.removeEventListener("abort",stop);return client.close()}}}catch{options.signal?.removeEventListener("abort",stop);await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
@@ -1 +1 @@
1
- import{probeLocalLibrary,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription}from"./chunk-IF6AUKH3.js";import{LocalToolSelectionSchema}from"./chunk-CTCEGOC7.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-LZPPTW2K.js";import{directory,fail,read,write}from"./chunk-DLW42PJ6.js";import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";import{z}from"zod";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.safeExtend({compositionBrowser:z.never().optional(),macSpeechIdentity:z.never().optional(),whisperIdentity:z.never().optional(),whisperTools:z.never().optional(),qwenIdentities:z.never().optional(),tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);const active=(await manager.ledger.current()).value.active;if(input.processorCapabilities?.some(kind=>kind==="LOCAL_MEDIA_INSPECT"||kind==="LOCAL_MEDIA_PUBLISH")&&(!active||!await probeLocalLibrary(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");if(input.processorCapabilities?.includes("SPEECH_SYNTHESIZE")&&(!active||!await probeTenantSpeech(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");if(input.processorCapabilities?.includes("TRANSCRIBE_AUDIO")&&(!active||!await probeTenantTranscription(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");const qwenProcessors=[["KEYFRAME_GENERATE","keyframe"],["VIDEO_GENERATE","video"],["SPEECH_EXTERNAL_QWEN","speech"],["TRANSCRIBE_EXTERNAL_QWEN","asr"]];const selectedQwen=qwenProcessors.filter(([processor])=>input.processorCapabilities?.includes(processor));if(selectedQwen.some(([,kind])=>kind!=="speech")!==Boolean(input.qwenDeviceCredentials?.length))fail("LOCAL_PROFILE_UNAVAILABLE");for(const[,kind]of selectedQwen){if(!active||!await probeTenantQwenGeneration(manager.ledger.slotPath(active),active,kind))fail("LOCAL_PROFILE_UNAVAILABLE")}for(const credential of input.qwenDeviceCredentials??[]){if(credential.tenantId!==input.tenantId)fail("LOCAL_PROFILE_UNAVAILABLE");(await read(credential.privateKeyFile,4096)).fill(0)}const actual=active?.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;if(input.tools&&active&&(!actual||canonicalLocalJson(input.tools)!==canonicalLocalJson(actual)))fail("TOOL_SELECTION_PLAN_REQUIRED");let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");const cloudTools=active?{mode:tools.mode,ffmpeg:tools.ffmpeg,ffprobe:tools.ffprobe}:tools;await write(file,canonicalLocalJson({...input,tools:cloudTools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,tenantId:input.tenantId,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}export{generateDeviceKey,connectDevice};
1
+ import{probeLocalLibrary,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription}from"./chunk-ELUJ44BO.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-APNZQZFB.js";import{directory,fail,read,write}from"./chunk-DLW42PJ6.js";import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";import{z}from"zod";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.safeExtend({compositionBrowser:z.never().optional(),macSpeechIdentity:z.never().optional(),whisperIdentity:z.never().optional(),whisperTools:z.never().optional(),qwenIdentities:z.never().optional(),tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);const active=(await manager.ledger.current()).value.active;if(input.processorCapabilities?.some(kind=>kind==="LOCAL_MEDIA_INSPECT"||kind==="LOCAL_MEDIA_PUBLISH")&&(!active||!await probeLocalLibrary(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");if(input.processorCapabilities?.includes("SPEECH_SYNTHESIZE")&&(!active||!await probeTenantSpeech(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");if(input.processorCapabilities?.includes("TRANSCRIBE_AUDIO")&&(!active||!await probeTenantTranscription(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");const qwenProcessors=[["KEYFRAME_GENERATE","keyframe"],["VIDEO_GENERATE","video"],["SPEECH_EXTERNAL_QWEN","speech"],["TRANSCRIBE_EXTERNAL_QWEN","asr"]];const selectedQwen=qwenProcessors.filter(([processor])=>input.processorCapabilities?.includes(processor));if(selectedQwen.some(([,kind])=>kind!=="speech")!==Boolean(input.qwenDeviceCredentials?.length))fail("LOCAL_PROFILE_UNAVAILABLE");for(const[,kind]of selectedQwen){if(!active||!await probeTenantQwenGeneration(manager.ledger.slotPath(active),active,kind))fail("LOCAL_PROFILE_UNAVAILABLE")}for(const credential of input.qwenDeviceCredentials??[]){if(credential.tenantId!==input.tenantId)fail("LOCAL_PROFILE_UNAVAILABLE");(await read(credential.privateKeyFile,4096)).fill(0)}const actual=active?.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;if(input.tools&&active&&(!actual||canonicalLocalJson(input.tools)!==canonicalLocalJson(actual)))fail("TOOL_SELECTION_PLAN_REQUIRED");let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");const cloudTools=active?{mode:tools.mode,ffmpeg:tools.ffmpeg,ffprobe:tools.ffprobe}:tools;await write(file,canonicalLocalJson({...input,tools:cloudTools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,tenantId:input.tenantId,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}export{generateDeviceKey,connectDevice};
@@ -1 +1 @@
1
- import{DeviceEnrollmentScopeSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema}from"./chunk-LZPPTW2K.js";import{z}from"zod";var DesktopDeviceScopeSchema=DeviceEnrollmentScopeSchema;var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("media-validation-capability")}),z.strictObject({action:z.literal("media-processing-capability")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120),expectedRevision:z.int().nonnegative().optional(),bindWorkspaceMember:z.literal(true).optional(),agentEnrollment:z.literal(true).optional()}),z.strictObject({action:z.literal("revoke")}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),tenantMediaProcessing:z.literal(true).optional(),processorCapabilities:LocalDeviceTransportConfigurationSchema.shape.processorCapabilities,deviceRevision:z.int().positive(),tenantMediaValidation:z.literal(true).optional()}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"]),agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120),revision:z.int().positive(),revokedAt:z.iso.datetime().nullable()}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","REVOKE_DEVICE","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest,agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional(),mediaValidationSupported:z.boolean().optional(),mediaProcessingSupported:z.boolean().optional(),localLibrarySupported:z.boolean().optional(),compositionProcessingSupported:z.boolean().optional()});export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceStateSchema,DesktopDeviceReplySchema};
1
+ import{DeviceEnrollmentScopeSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema}from"./chunk-APNZQZFB.js";import{z}from"zod";var DesktopDeviceScopeSchema=DeviceEnrollmentScopeSchema;var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("media-validation-capability")}),z.strictObject({action:z.literal("media-processing-capability")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120),expectedRevision:z.int().nonnegative().optional(),bindWorkspaceMember:z.literal(true).optional(),agentEnrollment:z.literal(true).optional()}),z.strictObject({action:z.literal("revoke")}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),tenantMediaProcessing:z.literal(true).optional(),processorCapabilities:LocalDeviceTransportConfigurationSchema.shape.processorCapabilities,deviceRevision:z.int().positive(),tenantMediaValidation:z.literal(true).optional()}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"]),agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120),revision:z.int().positive(),revokedAt:z.iso.datetime().nullable()}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","REVOKE_DEVICE","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest,agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional(),mediaValidationSupported:z.boolean().optional(),mediaProcessingSupported:z.boolean().optional(),localLibrarySupported:z.boolean().optional(),compositionProcessingSupported:z.boolean().optional()});export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceStateSchema,DesktopDeviceReplySchema};
@@ -1 +1 @@
1
- import{runDesktopDeviceRequest}from"./chunk-67QDMD7M.js";import{DesktopDeviceRecords}from"./chunk-BZPQB66Z.js";import{DesktopDeviceScopeSchema}from"./chunk-5TKBEFRX.js";import{DeviceEnrollmentReceiptSchema,DeviceEnrollmentTicketSchema,LocalDeviceViewSchema,LocalManagementReceiptSchema,canonicalLocalJson,deviceEnrollmentSigningInput,validateDeviceEnrollmentHandoff}from"./chunk-LZPPTW2K.js";import{fail,read,sha256}from"./chunk-DLW42PJ6.js";import{z}from"zod";import{createPrivateKey,sign}from"node:crypto";async function redeemEnrollment(home,handoff,ticket){if(ticket.tenantId!==handoff.scope.tenantId||ticket.requestId!==handoff.command.input.requestId||ticket.fingerprint!==handoff.fingerprint)fail("DEVICE_ENROLLMENT_RESPONSE_INVALID");const records=await DesktopDeviceRecords.open(home,handoff.scope);const privateKey=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const signature=sign("sha256",Buffer.from(deviceEnrollmentSigningInput(ticket)),{key:privateKey,dsaEncoding:"ieee-p1363"}).toString("base64url");const response=await fetch(handoff.scope.origin+"/v1/local-execution/devices/enrollments/redeem",{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{"content-type":"application/json"},body:JSON.stringify({tenantId:ticket.tenantId,enrollmentId:ticket.enrollmentId,signature})});if(response.status!==200&&response.status!==409){await response.body?.cancel();fail(response.status===403?"FORBIDDEN":"DEVICE_ENROLLMENT_OUTCOME_UNKNOWN")}let length=0;const chunks=[];for await(const chunk of response.body??[]){length+=chunk.byteLength;if(length>16384)fail("DEVICE_ENROLLMENT_RESPONSE_INVALID");chunks.push(chunk)}const raw=JSON.parse(Buffer.concat(chunks).toString());if(response.status===409)fail(raw?.code==="ENROLLMENT_EXPIRED"?"ENROLLMENT_EXPIRED":"DEVICE_ENROLLMENT_OUTCOME_UNKNOWN");const receipt=DeviceEnrollmentReceiptSchema.parse(raw);if(receipt.fingerprint!==handoff.fingerprint||receipt.result.deviceId!==ticket.deviceId)fail("DEVICE_ENROLLMENT_RESPONSE_INVALID");return receipt}var digest=z.string().regex(/^[a-f0-9]{64}$/);var HostEnrollmentRequestSchema=z.strictObject({scope:DesktopDeviceScopeSchema,call:z.discriminatedUnion("action",[z.strictObject({action:z.literal("prepare"),label:z.string().trim().min(1).max(120),authority:z.literal("OAUTH_AGENT").optional()}),z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("accept"),receipt:LocalManagementReceiptSchema}),z.strictObject({action:z.literal("redeem"),ticket:DeviceEnrollmentTicketSchema}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest})])});async function runHostEnrollment(home,request){const{scope,call}=request;const owner=action=>runDesktopDeviceRequest(home,{operation:"device",scope,call:action},{allowedPendingKinds:["ENROLL"]});let current=await owner({action:"inspect"});const cloud=deviceId=>({name:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:"device_status",arguments:{tenantId:scope.tenantId,deviceId}}});const enrolled=()=>{const device=current.view.device;if(!device)fail("DEVICE_ENROLLMENT_REQUIRED");return{state:device.revokedAt?"REVOKED":"ENROLLED",view:current.view,cloud:cloud(device.deviceId)}};if(call.action==="connect"){const{revision,installation,device}=current.view;if(!device||device.revokedAt)fail("DEVICE_ENROLLMENT_REQUIRED");if(revision!==call.expectedRevision||installation?.fingerprint!==call.installationFingerprint)fail("DEVICE_PLAN_CHANGED");if(current.view.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");await owner({action:"prove"});current=await owner(call);return{state:"CONNECTED_LOCAL",view:current.view,cloud:cloud(device.deviceId)}}if(current.view.device){if(call.action==="accept"){const saved=await DesktopDeviceRecords.inspect(home,scope);const result=LocalDeviceViewSchema.safeParse(call.receipt.result);if(!saved?.device||!saved.enrollment||!result.success||sha256(canonicalLocalJson({kind:"ENROLL",input:saved.enrollment}))!==call.receipt.fingerprint||canonicalLocalJson(result.data)!==canonicalLocalJson(saved.device))fail("DEVICE_RESULT_INVALID")}if(call.action==="redeem"){const saved=await DesktopDeviceRecords.inspect(home,scope);if(!saved?.device||!saved.enrollment||call.ticket.deviceId!==saved.device.deviceId||call.ticket.requestId!==saved.enrollment.requestId||call.ticket.tenantId!==scope.tenantId||call.ticket.fingerprint!==sha256(canonicalLocalJson({kind:"ENROLL",input:saved.enrollment})))fail("DEVICE_ENROLLMENT_RESPONSE_INVALID")}return enrolled()}if(!current.view.pending){if(call.action==="inspect")return{state:"UNENROLLED",view:current.view};if(call.action!=="prepare")fail("DEVICE_PLAN_CHANGED");current=await owner({action:"enroll",label:call.label,expectedRevision:current.view.revision,bindWorkspaceMember:true,...call.authority==="OAUTH_AGENT"&&{agentEnrollment:true}})}const pending=current.view.pending;if(!pending||current.command?.kind!=="ENROLL")fail("DEVICE_PLAN_CHANGED");if(!current.command.input.expectedPrincipalId)fail("DEVICE_ORIGINAL_ENROLLMENT_REQUIRED");const handoff=validateDeviceEnrollmentHandoff({protocol:"NVS_DEVICE_ENROLLMENT_HANDOFF_V1",scope,command:current.command,fingerprint:pending.fingerprint});const lookup={name:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:pending.agentEnrollment?"device_enrollment_lookup":"device_management_receipt",arguments:pending.agentEnrollment?{tenantId:scope.tenantId,requestId:handoff.command.input.requestId}:{tenantId:scope.tenantId,command:handoff.command}}};if(call.action==="redeem"){if(!pending.agentEnrollment||pending.phase!=="SENDING"||current.view.installation?.version!==handoff.command.input.runtimeVersion)fail("DEVICE_PLAN_CHANGED");const receipt=await redeemEnrollment(home,handoff,call.ticket);current=await owner({action:"record",fingerprint:handoff.fingerprint,result:receipt.result});return enrolled()}if(call.action==="accept"){if(pending.phase!=="SENDING"||call.receipt.fingerprint!==handoff.fingerprint)fail("DEVICE_PLAN_CHANGED");if(!call.receipt.result)return{state:"LOOKUP_REQUIRED",handoff,lookup};current=await owner({action:"record",fingerprint:handoff.fingerprint,result:call.receipt.result});return enrolled()}if(pending.phase==="SENDING")return{state:"LOOKUP_REQUIRED",handoff,lookup};if(pending.phase==="REFUSED")return{state:"REFUSED",handoff,lookup};if(call.action==="inspect")return{state:"PREPARED",handoff,lookup};if(call.label!==handoff.command.input.label||!!pending.agentEnrollment!==(call.authority==="OAUTH_AGENT")||current.view.installation?.version!==handoff.command.input.runtimeVersion)fail("DEVICE_PLAN_CHANGED");await owner({action:"dispatch",fingerprint:handoff.fingerprint});return{state:"DISPATCH",handoff,lookup,invoke:{name:"studio_capability_invoke",arguments:{tenantId:scope.tenantId,tool:pending.agentEnrollment?"device_enrollment_issue":"device_enroll",arguments:handoff.command.input}}}}export{HostEnrollmentRequestSchema,runHostEnrollment};
1
+ import{runDesktopDeviceRequest}from"./chunk-ROGOASYF.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import{DesktopDeviceScopeSchema}from"./chunk-IYDHDLTR.js";import{DeviceEnrollmentReceiptSchema,DeviceEnrollmentTicketSchema,LocalDeviceViewSchema,LocalManagementReceiptSchema,canonicalLocalJson,deviceEnrollmentSigningInput,validateDeviceEnrollmentHandoff}from"./chunk-APNZQZFB.js";import{fail,read,sha256}from"./chunk-DLW42PJ6.js";import{z}from"zod";import{createPrivateKey,sign}from"node:crypto";async function redeemEnrollment(home,handoff,ticket){if(ticket.tenantId!==handoff.scope.tenantId||ticket.requestId!==handoff.command.input.requestId||ticket.fingerprint!==handoff.fingerprint)fail("DEVICE_ENROLLMENT_RESPONSE_INVALID");const records=await DesktopDeviceRecords.open(home,handoff.scope);const privateKey=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const signature=sign("sha256",Buffer.from(deviceEnrollmentSigningInput(ticket)),{key:privateKey,dsaEncoding:"ieee-p1363"}).toString("base64url");const response=await fetch(handoff.scope.origin+"/v1/local-execution/devices/enrollments/redeem",{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{"content-type":"application/json"},body:JSON.stringify({tenantId:ticket.tenantId,enrollmentId:ticket.enrollmentId,signature})});if(response.status!==200&&response.status!==409){await response.body?.cancel();fail(response.status===403?"FORBIDDEN":"DEVICE_ENROLLMENT_OUTCOME_UNKNOWN")}let length=0;const chunks=[];for await(const chunk of response.body??[]){length+=chunk.byteLength;if(length>16384)fail("DEVICE_ENROLLMENT_RESPONSE_INVALID");chunks.push(chunk)}const raw=JSON.parse(Buffer.concat(chunks).toString());if(response.status===409)fail(raw?.code==="ENROLLMENT_EXPIRED"?"ENROLLMENT_EXPIRED":"DEVICE_ENROLLMENT_OUTCOME_UNKNOWN");const receipt=DeviceEnrollmentReceiptSchema.parse(raw);if(receipt.fingerprint!==handoff.fingerprint||receipt.result.deviceId!==ticket.deviceId)fail("DEVICE_ENROLLMENT_RESPONSE_INVALID");return receipt}var digest=z.string().regex(/^[a-f0-9]{64}$/);var HostEnrollmentRequestSchema=z.strictObject({scope:DesktopDeviceScopeSchema,call:z.discriminatedUnion("action",[z.strictObject({action:z.literal("prepare"),label:z.string().trim().min(1).max(120),authority:z.literal("OAUTH_AGENT").optional()}),z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("accept"),receipt:LocalManagementReceiptSchema}),z.strictObject({action:z.literal("redeem"),ticket:DeviceEnrollmentTicketSchema}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest})])});async function runHostEnrollment(home,request){const{scope,call}=request;const owner=action=>runDesktopDeviceRequest(home,{operation:"device",scope,call:action},{allowedPendingKinds:["ENROLL"]});let current=await owner({action:"inspect"});const cloud=deviceId=>({name:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:"device_status",arguments:{tenantId:scope.tenantId,deviceId}}});const enrolled=()=>{const device=current.view.device;if(!device)fail("DEVICE_ENROLLMENT_REQUIRED");return{state:device.revokedAt?"REVOKED":"ENROLLED",view:current.view,cloud:cloud(device.deviceId)}};if(call.action==="connect"){const{revision,installation,device}=current.view;if(!device||device.revokedAt)fail("DEVICE_ENROLLMENT_REQUIRED");if(revision!==call.expectedRevision||installation?.fingerprint!==call.installationFingerprint)fail("DEVICE_PLAN_CHANGED");if(current.view.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");await owner({action:"prove"});current=await owner(call);return{state:"CONNECTED_LOCAL",view:current.view,cloud:cloud(device.deviceId)}}if(current.view.device){if(call.action==="accept"){const saved=await DesktopDeviceRecords.inspect(home,scope);const result=LocalDeviceViewSchema.safeParse(call.receipt.result);if(!saved?.device||!saved.enrollment||!result.success||sha256(canonicalLocalJson({kind:"ENROLL",input:saved.enrollment}))!==call.receipt.fingerprint||canonicalLocalJson(result.data)!==canonicalLocalJson(saved.device))fail("DEVICE_RESULT_INVALID")}if(call.action==="redeem"){const saved=await DesktopDeviceRecords.inspect(home,scope);if(!saved?.device||!saved.enrollment||call.ticket.deviceId!==saved.device.deviceId||call.ticket.requestId!==saved.enrollment.requestId||call.ticket.tenantId!==scope.tenantId||call.ticket.fingerprint!==sha256(canonicalLocalJson({kind:"ENROLL",input:saved.enrollment})))fail("DEVICE_ENROLLMENT_RESPONSE_INVALID")}return enrolled()}if(!current.view.pending){if(call.action==="inspect")return{state:"UNENROLLED",view:current.view};if(call.action!=="prepare")fail("DEVICE_PLAN_CHANGED");current=await owner({action:"enroll",label:call.label,expectedRevision:current.view.revision,bindWorkspaceMember:true,...call.authority==="OAUTH_AGENT"&&{agentEnrollment:true}})}const pending=current.view.pending;if(!pending||current.command?.kind!=="ENROLL")fail("DEVICE_PLAN_CHANGED");if(!current.command.input.expectedPrincipalId)fail("DEVICE_ORIGINAL_ENROLLMENT_REQUIRED");const handoff=validateDeviceEnrollmentHandoff({protocol:"NVS_DEVICE_ENROLLMENT_HANDOFF_V1",scope,command:current.command,fingerprint:pending.fingerprint});const lookup={name:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:pending.agentEnrollment?"device_enrollment_lookup":"device_management_receipt",arguments:pending.agentEnrollment?{tenantId:scope.tenantId,requestId:handoff.command.input.requestId}:{tenantId:scope.tenantId,command:handoff.command}}};if(call.action==="redeem"){if(!pending.agentEnrollment||pending.phase!=="SENDING"||current.view.installation?.version!==handoff.command.input.runtimeVersion)fail("DEVICE_PLAN_CHANGED");const receipt=await redeemEnrollment(home,handoff,call.ticket);current=await owner({action:"record",fingerprint:handoff.fingerprint,result:receipt.result});return enrolled()}if(call.action==="accept"){if(pending.phase!=="SENDING"||call.receipt.fingerprint!==handoff.fingerprint)fail("DEVICE_PLAN_CHANGED");if(!call.receipt.result)return{state:"LOOKUP_REQUIRED",handoff,lookup};current=await owner({action:"record",fingerprint:handoff.fingerprint,result:call.receipt.result});return enrolled()}if(pending.phase==="SENDING")return{state:"LOOKUP_REQUIRED",handoff,lookup};if(pending.phase==="REFUSED")return{state:"REFUSED",handoff,lookup};if(call.action==="inspect")return{state:"PREPARED",handoff,lookup};if(call.label!==handoff.command.input.label||!!pending.agentEnrollment!==(call.authority==="OAUTH_AGENT")||current.view.installation?.version!==handoff.command.input.runtimeVersion)fail("DEVICE_PLAN_CHANGED");await owner({action:"dispatch",fingerprint:handoff.fingerprint});return{state:"DISPATCH",handoff,lookup,invoke:{name:"studio_capability_invoke",arguments:{tenantId:scope.tenantId,tool:pending.agentEnrollment?"device_enrollment_issue":"device_enroll",arguments:handoff.command.input}}}}export{HostEnrollmentRequestSchema,runHostEnrollment};
@@ -1 +1 @@
1
- import{desktopAutomation,desktopInstallationIdentity}from"./chunk-J2IYRUVM.js";import{LocalInstallationManager,ownerClient,socketAbsent}from"./chunk-IF6AUKH3.js";import{LocalLibraryCallSchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryReferenceSchema,LocalLibraryUsageSchema}from"./chunk-LZPPTW2K.js";import{LocalClientError,fail}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{isAbsolute}from"node:path";import{constants}from"node:fs";import{open}from"node:fs/promises";import{createHash}from"node:crypto";var same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size&&a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs;async function captureLibraryImport(path,seed){const file2=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW).catch(()=>{throw new NativeStudioSdkError("LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")});try{const before=await file2.stat(),hash=createHash("sha256");if(!before.isFile()||before.size>128*1024*1024)fail("LOCAL_LIBRARY_FILE_INVALID");let size=0;for await(const bytes of file2.createReadStream({autoClose:false,start:0})){size+=bytes.length;if(size>before.size)fail("LOCAL_LIBRARY_FILE_CHANGED");hash.update(bytes)}if(size!==before.size||!same(before,await file2.stat()))fail("LOCAL_LIBRARY_FILE_CHANGED");const{tenantId,projectId,deviceId,contentType,...fields}=seed;return LocalLibraryImportSchema.parse({...fields,reference:{tenantId,projectId,deviceId,fileId:seed.requestId,versionId:seed.requestId,contentType,byteSize:size,checksumSha256:hash.digest("hex")}})}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(error instanceof LocalClientError?error.code:"LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")}finally{await file2.close()}}async function importLibraryFile(library,path,raw){const input=LocalLibraryImportSchema.parse(raw),file2=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW).catch(()=>{throw new NativeStudioSdkError("LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")});let dispatched=false;try{const before=await file2.stat();if(!before.isFile()||before.size!==input.reference.byteSize)fail("LOCAL_LIBRARY_FILE_CHANGED");dispatched=true;const result=await library.import(input,file2.createReadStream({autoClose:false,start:0}));if(!same(before,await file2.stat()))fail("LOCAL_LIBRARY_IMPORT_UNKNOWN");return result}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(error instanceof LocalClientError?error.code:"LOCAL_LIBRARY_IMPORT_UNAVAILABLE","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{await file2.close()}}var file=z.string().min(1).max(4096).refine(isAbsolute);var DesktopLibraryImportSeedSchema=LocalLibraryImportSchema.omit({reference:true}).extend({...LocalLibraryReferenceSchema.pick({tenantId:true,projectId:true,deviceId:true,contentType:true}).shape});var DesktopLibraryRequestSchema=z.strictObject({operation:z.literal("library"),call:LocalLibraryCallSchema});var DesktopLibraryImportRequestSchema=z.strictObject({operation:z.literal("library-import"),input:LocalLibraryImportSchema,file});var DesktopLibraryPrepareRequestSchema=z.strictObject({operation:z.literal("library-import-prepare"),seed:DesktopLibraryImportSeedSchema,file});var DesktopLibraryMediaRequestSchema=z.strictObject({operation:z.literal("library-media"),input:LocalLibraryGetSchema,method:z.enum(["GET","HEAD"]).default("GET"),range:z.string().min(1).max(100).optional()});var DesktopLibraryReplySchema=z.union([LocalLibraryItemSchema.nullable(),LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryUsageSchema,LocalLibraryReadReplySchema]);async function client(home){const manager=await LocalInstallationManager.open(home),config=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(config.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}return ownerClient(config.stateDirectory)}async function runDesktopLibraryRequest(home,raw){const input=DesktopLibraryRequestSchema.parse(raw);return(await client(home)).library.call(input.call)}async function prepareDesktopLibraryImport(raw){const input=DesktopLibraryPrepareRequestSchema.parse(raw);return DesktopLibraryImportRequestSchema.parse({operation:"library-import",file:input.file,input:await captureLibraryImport(input.file,input.seed)})}async function runDesktopLibraryImport(home,raw){const input=DesktopLibraryImportRequestSchema.parse(raw);return importLibraryFile((await client(home)).library,input.file,input.input)}async function runDesktopLibraryMedia(home,raw){const input=DesktopLibraryMediaRequestSchema.parse(raw);return(await client(home)).library.media(input.input,{method:input.method,...input.range?{range:input.range}:{}})}export{DesktopLibraryImportSeedSchema,DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryReplySchema,runDesktopLibraryRequest,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia};
1
+ import{desktopAutomation,desktopInstallationIdentity}from"./chunk-MLZ3ZPGU.js";import{LocalInstallationManager,ownerClient,socketAbsent}from"./chunk-ELUJ44BO.js";import{LocalLibraryCallSchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryReferenceSchema,LocalLibraryUsageSchema}from"./chunk-APNZQZFB.js";import{LocalClientError,fail}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{isAbsolute}from"node:path";import{constants}from"node:fs";import{open}from"node:fs/promises";import{createHash}from"node:crypto";var same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size&&a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs;async function captureLibraryImport(path,seed){const file2=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW).catch(()=>{throw new NativeStudioSdkError("LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")});try{const before=await file2.stat(),hash=createHash("sha256");if(!before.isFile()||before.size>128*1024*1024)fail("LOCAL_LIBRARY_FILE_INVALID");let size=0;for await(const bytes of file2.createReadStream({autoClose:false,start:0})){size+=bytes.length;if(size>before.size)fail("LOCAL_LIBRARY_FILE_CHANGED");hash.update(bytes)}if(size!==before.size||!same(before,await file2.stat()))fail("LOCAL_LIBRARY_FILE_CHANGED");const{tenantId,projectId,deviceId,contentType,...fields}=seed;return LocalLibraryImportSchema.parse({...fields,reference:{tenantId,projectId,deviceId,fileId:seed.requestId,versionId:seed.requestId,contentType,byteSize:size,checksumSha256:hash.digest("hex")}})}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(error instanceof LocalClientError?error.code:"LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")}finally{await file2.close()}}async function importLibraryFile(library,path,raw){const input=LocalLibraryImportSchema.parse(raw),file2=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW).catch(()=>{throw new NativeStudioSdkError("LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")});let dispatched=false;try{const before=await file2.stat();if(!before.isFile()||before.size!==input.reference.byteSize)fail("LOCAL_LIBRARY_FILE_CHANGED");dispatched=true;const result=await library.import(input,file2.createReadStream({autoClose:false,start:0}));if(!same(before,await file2.stat()))fail("LOCAL_LIBRARY_IMPORT_UNKNOWN");return result}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(error instanceof LocalClientError?error.code:"LOCAL_LIBRARY_IMPORT_UNAVAILABLE","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{await file2.close()}}var file=z.string().min(1).max(4096).refine(isAbsolute);var DesktopLibraryImportSeedSchema=LocalLibraryImportSchema.omit({reference:true}).extend({...LocalLibraryReferenceSchema.pick({tenantId:true,projectId:true,deviceId:true,contentType:true}).shape});var DesktopLibraryRequestSchema=z.strictObject({operation:z.literal("library"),call:LocalLibraryCallSchema});var DesktopLibraryImportRequestSchema=z.strictObject({operation:z.literal("library-import"),input:LocalLibraryImportSchema,file});var DesktopLibraryPrepareRequestSchema=z.strictObject({operation:z.literal("library-import-prepare"),seed:DesktopLibraryImportSeedSchema,file});var DesktopLibraryMediaRequestSchema=z.strictObject({operation:z.literal("library-media"),input:LocalLibraryGetSchema,method:z.enum(["GET","HEAD"]).default("GET"),range:z.string().min(1).max(100).optional()});var DesktopLibraryReplySchema=z.union([LocalLibraryItemSchema.nullable(),LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryUsageSchema,LocalLibraryReadReplySchema]);async function client(home){const manager=await LocalInstallationManager.open(home),config=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(config.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}return ownerClient(config.stateDirectory)}async function runDesktopLibraryRequest(home,raw){const input=DesktopLibraryRequestSchema.parse(raw);return(await client(home)).library.call(input.call)}async function prepareDesktopLibraryImport(raw){const input=DesktopLibraryPrepareRequestSchema.parse(raw);return DesktopLibraryImportRequestSchema.parse({operation:"library-import",file:input.file,input:await captureLibraryImport(input.file,input.seed)})}async function runDesktopLibraryImport(home,raw){const input=DesktopLibraryImportRequestSchema.parse(raw);return importLibraryFile((await client(home)).library,input.file,input.input)}async function runDesktopLibraryMedia(home,raw){const input=DesktopLibraryMediaRequestSchema.parse(raw);return(await client(home)).library.media(input.input,{method:input.method,...input.range?{range:input.range}:{}})}export{DesktopLibraryImportSeedSchema,DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryReplySchema,runDesktopLibraryRequest,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia};
@@ -0,0 +1 @@
1
+ import{runLoginService}from"./chunk-D74NHT4I.js";import{ComponentCommandSchema}from"./chunk-QE7O57PQ.js";import{configureDesktopChannel,desktopRuntimeChannel}from"./chunk-4PAVWOPA.js";import{LocalInstallationManager,socketAbsent}from"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import{AgentComponentScopeSchema,AgentComponentStatusSchema,LocalRuntimeStatusSchema}from"./chunk-6EZX2TRX.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-APNZQZFB.js";import{directory,entries,fail,optional,privateAccess,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";import{realpath}from"node:fs/promises";var namespace=scope=>sha256(canonicalLocalJson(scope)).slice(0,24);function deviceScope(scope){return{origin:scope.origin,tenantId:scope.tenantId,principalId:scope.principalId}}async function privateRoot(path){try{await privateAccess(path,"directory");return await realpath(path)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async function componentHome(parent,scope,initialize){const canonical=initialize?await directory(parent):await privateRoot(parent)??parent;const base=join(canonical,"components"),home=join(base,namespace(scope)),marker=join(home,"component-owner.json");const checked=await privateRoot(base);if(checked&&checked!==base)fail("COMPONENT_OWNER_CONFLICT");const existing=checked&&await privateRoot(home);if(existing&&existing!==home)fail("COMPONENT_OWNER_CONFLICT");let saved=existing?await optional(marker):null;if(!saved&&initialize){if(await directory(base)!==base||await directory(home)!==home)fail("COMPONENT_OWNER_CONFLICT");if((await entries(home)).length)fail("COMPONENT_OWNER_CONFLICT");try{await write(marker,canonicalLocalJson(scope),true)}catch(error){if(error.code!=="EEXIST")throw error}saved=await optional(marker)}if(!saved&&existing&&(await entries(home)).length)fail("COMPONENT_OWNER_CONFLICT");if(saved&&canonicalLocalJson(AgentComponentScopeSchema.parse(saved))!==canonicalLocalJson(scope))fail("COMPONENT_OWNER_CONFLICT");return{home,claimed:saved!==null}}async function initializeComponent(home,scope,channel){const stateDirectory=join(home,"rt");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const manager=await LocalInstallationManager.open(home);if(!await optional(join(home,"configuration.json")))await manager.configure({stateDirectory},{ifAbsent:true});await assertComponentConfiguration(manager,scope);if(channel!==void 0){const trusted=desktopRuntimeChannel({...channel,protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1"});await configureDesktopChannel(manager,trusted.fingerprint,trusted.value)}return manager}async function componentDevice(home,scope){return(await DesktopDeviceRecords.inspect(home,deviceScope(scope)))?.device??null}async function assertComponentConfiguration(manager,scope){const{root}=manager.ledger;const configuration=await manager.configuration();if(configuration.stateDirectory!==join(root,"rt")||await privateRoot(configuration.stateDirectory)!==configuration.stateDirectory)fail("COMPONENT_CONFIGURATION_CONFLICT");if(configuration.cloudConfigFile){const cloud=configuration.cloudConfigFile;if(cloud!==join(configuration.stateDirectory,"cloud-device.json"))fail("COMPONENT_CONFIGURATION_CONFLICT");const raw=await optional(cloud),device=await componentDevice(root,scope);if(!raw||typeof raw!=="object"||!("tools"in raw)||!device)fail("COMPONENT_CONFIGURATION_CONFLICT");const{tools:_tools,...transport}=raw;void _tools;const actual=LocalDeviceTransportConfigurationSchema.parse(transport);const privateKeyFile=join(root,"devices",sha256(canonicalLocalJson(deviceScope(scope))),"device-key.json");if(actual.endpoint!==scope.origin||actual.tenantId!==scope.tenantId||actual.deviceId!==device.deviceId||actual.deviceRevision!==device.revision||actual.privateKeyFile!==privateKeyFile)fail("COMPONENT_CONFIGURATION_CONFLICT")}return configuration}import{opendir}from"node:fs/promises";import{join as join2}from"node:path";import{z}from"zod";var event=z.strictObject({at:z.iso.datetime(),reasonCode:z.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/)});var receipt=event.extend({command:ComponentCommandSchema,phase:z.enum(["SENDING","COMPLETE","DEGRADED"]),outcome:z.enum(["UNKNOWN","OBSERVED","SUCCESS"]),installationRevision:z.int().nonnegative(),runningVersion:z.string().min(1).max(120).nullable()});var head=z.strictObject({requestId:z.uuid(),lastSuccess:event.nullable(),lastFailure:event.nullable()});var at=()=>new Date().toISOString();var print=command=>sha256(canonicalLocalJson(command));async function withComponentLock(root,work){const locks=join2(root,"control-locks");if(await directory(locks)!==locks)fail("COMPONENT_OWNER_CONFLICT");const file=generation=>join2(locks,String(generation).padStart(12,"0")+".json");let previous=0;for await(const entry of await opendir(locks)){if(/^\d{12}\.json$/.test(entry.name))previous=Math.max(previous,Number(entry.name.slice(0,12)))}if(previous&&!await optional(file(previous)+".released")){const owner=z.strictObject({pid:z.int().positive()}).parse(await optional(file(previous)));try{process.kill(owner.pid,0);fail("COMPONENT_BUSY","NO_WRITE")}catch(error){if(error.code!=="ESRCH")fail("COMPONENT_BUSY","NO_WRITE")}}const current=file(previous+1);try{await write(current,canonicalLocalJson({pid:process.pid}),true)}catch(error){if(error.code==="EEXIST")fail("COMPONENT_BUSY","NO_WRITE");throw error}try{return await work()}finally{await write(current+".released","true",true)}}var ComponentReceipts=class{constructor(root){this.root=root}root;path(requestId){return join2(this.root,"request-"+z.uuid().parse(requestId).toLowerCase()+".json")}async find(requestId){const result=receipt.nullable().parse(await optional(this.path(requestId)));if(result&&result.command.requestId.toLowerCase()!==requestId.toLowerCase())fail("COMPONENT_RECEIPT_INVALID");return result}async original(command){const result=await this.find(command.requestId);if(result&&print(command)!==print(result.command))fail("COMPONENT_REQUEST_CONFLICT","NO_WRITE");return result}async snapshot(){const state=head.nullable().parse(await optional(join2(this.root,"head.json")));const latest=state&&await this.find(state.requestId);if(state&&!latest)fail("COMPONENT_RECEIPT_INVALID");const eventOf=value=>({at:value.at,reasonCode:value.reasonCode});return{latest,lastSuccess:latest?.phase==="COMPLETE"?eventOf(latest):state?.lastSuccess??null,lastFailure:latest?.phase==="DEGRADED"?eventOf(latest):state?.lastFailure??null}}async begin(command,runningVersion){const{latest,lastSuccess,lastFailure}=await this.snapshot();if(latest?.phase==="SENDING")fail("COMPONENT_ORIGINAL_OUTCOME_UNKNOWN");const value=receipt.parse({command,phase:"SENDING",outcome:"UNKNOWN",reasonCode:"COMPONENT_ACTION_SENDING",installationRevision:command.expectedRevision,runningVersion,at:at()});await write(this.path(command.requestId),canonicalLocalJson(value),true);await write(join2(this.root,"head.json"),canonicalLocalJson({requestId:command.requestId,lastSuccess,lastFailure}));return value}async finish(original,result){if(original.phase!=="SENDING")return original;const value=receipt.parse({...original,...result,at:at()});await write(this.path(original.command.requestId),canonicalLocalJson(value));return value}};async function observeLoginService(home){const result=await runLoginService("service-status",home);if(!("registration"in result))fail("COMPONENT_SERVICE_UNCONFIRMED");return result}async function observeComponent(home,scope,manager,receipts){const configuration=manager&&await assertComponentConfiguration(manager,scope);const installation=manager&&await manager.status(),observed=installation&&LocalRuntimeStatusSchema.safeParse(installation.running).data;const version=observed&&installation&&"entryPath"in installation?observed.versions.find(entry=>entry.component==="RUNTIME"&&entry.runningVersion===installation.activeVersion&&entry.installOwner==="MANAGED"&&entry.executablePath===installation.entryPath):void 0;const stopped=!observed&&configuration&&await socketAbsent(configuration.stateDirectory);const service=manager&&installation?.activeVersion?await observeLoginService(home):null;const loginService=!service||!("fingerprint"in service)?"NONE":"supervision"in service&&service.supervision==="EXPLICIT_RECOVERY"?service.registration==="REGISTERED"?service.binding==="CURRENT"?"REGISTERED":"STALE":["ABSENT","INCOMPLETE"].includes(service.registration)?"INCOMPLETE":"UNKNOWN":"UNKNOWN";const{latest,lastSuccess,lastFailure}=await receipts.snapshot();const device=manager&&await componentDevice(home,scope);const at2=new Date().toISOString();const ready=version&&observed&&!observed.capabilityMismatch&&["IDLE","EXECUTING"].includes(observed.state)&&installation?.phase==="IDLE";const reason=version?"OWNED_RUNTIME_RESPONDING":stopped?"OWNED_RUNTIME_STOPPED":manager?"OWNED_RUNTIME_UNCONFIRMED":"COMPONENT_NOT_INITIALIZED";const event2=value=>value?{state:"OBSERVED",...value}:{state:"NONE"};return AgentComponentStatusSchema.parse({protocol:"NVS_COMPONENT_STATUS_V1",component:"HOST_RUNTIME",source:"OWNED_INSTALLATION_IPC",observedAt:at2,componentHome:home,initialized:!!manager,installationRevision:installation?.revision??0,installedVersion:installation?.activeVersion??null,runningVersion:version?.runningVersion??null,loginService,deviceId:device?.deviceId??null,...version&&observed?.capabilityMismatch&&{capabilityMismatch:observed.capabilityMismatch},liveness:{state:version?"ALIVE":stopped?"STOPPED":"UNKNOWN",reasonCode:reason,at:manager?at2:null},readiness:{state:ready?"READY":manager?"BLOCKED":"UNKNOWN",reasonCode:version&&observed?.capabilityMismatch?"CAPABILITY_VERSION_MISMATCH":ready||!version?reason:"OWNED_RUNTIME_RECOVERY_REQUIRED",at:manager?at2:null},lastRequestId:latest?.command.requestId??null,lastSuccess:event2(lastSuccess),lastFailure:event2(lastFailure),queueDepth:{state:"NOT_APPLICABLE"},nextRetry:{state:"NONE"}})}export{componentHome,initializeComponent,componentDevice,assertComponentConfiguration,withComponentLock,ComponentReceipts,observeLoginService,observeComponent};
@@ -1 +1 @@
1
- import{DesktopDeviceScopeSchema}from"./chunk-5TKBEFRX.js";import{canonicalLocalJson}from"./chunk-LZPPTW2K.js";import{fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";import{z}from"zod";var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z.strictObject({enabled:z.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z.uuid(),deviceRevision:z.int().positive(),installationFingerprint:digest});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;return state.device.revokedAt===null}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint});await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}export{desktopInstallationIdentity,desktopAutomation,canResumeDesktop,rememberDesktopAutomation,disableDesktopAutomation};
1
+ import{DesktopDeviceScopeSchema}from"./chunk-IYDHDLTR.js";import{canonicalLocalJson}from"./chunk-APNZQZFB.js";import{fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";import{z}from"zod";var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z.strictObject({enabled:z.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z.uuid(),deviceRevision:z.int().positive(),installationFingerprint:digest});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;return state.device.revokedAt===null}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint});await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}export{desktopInstallationIdentity,desktopAutomation,canResumeDesktop,rememberDesktopAutomation,disableDesktopAutomation};
@@ -1 +1 @@
1
- import{selectedProject}from"./chunk-H46NB5FL.js";import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-4NCE337I.js";import{profileHttpOrigin}from"./chunk-7P2NA6TH.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-27KI24GK.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";async function resolveCaller(env,explicitProject,workspaceOnly=false){const home=await clientHome(env),account=await readAccount(home);const saved=await loadConnection(env);const assertCurrent=async()=>{const latest=await loadConnection(env),current=await readAccount(home);if(latest?.profile!==saved?.profile||latest?.resource!==saved?.resource||account?.epoch!==current?.epoch||account?.state!==current?.state||account?.principalId!==current?.principalId||account?.workspaceId!==current?.workspaceId||account?.serverOrigin!==current?.serverOrigin)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(latest?.exchangeUnresolved)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");if(account&&!saved)requireAccount(current)};if(saved){const auth=await profileAuthorization(saved.profile);if(auth.resource!==saved.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const projectId=workspaceOnly?void 0:await selectedProject(saved,env,explicitProject);const c=await connectRemoteMcp(saved.resource,auth.authorization,saved.tenantId);try{const caller=await c.studio.call("workspace.caller",{});if(caller.tenantId!==saved.tenantId||account&&(account.principalId!==caller.principalId||account.serverOrigin!==caller.serverOrigin))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(projectId){const selected=await c.studio.call("project.get",{projectId});if(selected.project.id!==projectId||selected.project.tenantId!==caller.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}await assertCurrent();return{tenantId:caller.tenantId,principalId:caller.principalId,serverOrigin:caller.serverOrigin,home,projectId,resource:saved.resource,profile:saved.profile,assertCurrent}}finally{await c.close().catch(()=>{})}}if(!account)return null;const human=requireAccount(account);if(!human.workspaceId||!workspaceOnly&&!(explicitProject??human.projectId))throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{home,tenantId:human.workspaceId,projectId:workspaceOnly?void 0:z.uuid().parse(explicitProject??human.projectId),principalId:human.principalId,serverOrigin:human.serverOrigin,resource:void 0,profile:void 0,assertCurrent}}async function localCaller(env,explicitProject){const caller=await resolveCaller(env,explicitProject);if(!caller)return null;if(!caller.projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{...caller,projectId:caller.projectId}}function workspaceCaller(env){return resolveCaller(env,void 0,true)}async function callerOriginMatches(origin,caller){if(origin===caller.serverOrigin)return true;if(!caller.resource||!caller.profile)return false;return origin===new URL(caller.resource).origin||origin===await profileHttpOrigin(caller.profile,caller.resource)}export{localCaller,workspaceCaller,callerOriginMatches};
1
+ import{selectedProject}from"./chunk-OSO6KRE2.js";import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import{profileHttpOrigin}from"./chunk-7P2NA6TH.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-27KI24GK.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";async function resolveCaller(env,explicitProject,workspaceOnly=false){const home=await clientHome(env),account=await readAccount(home);const saved=await loadConnection(env);const assertCurrent=async()=>{const latest=await loadConnection(env),current=await readAccount(home);if(latest?.profile!==saved?.profile||latest?.resource!==saved?.resource||account?.epoch!==current?.epoch||account?.state!==current?.state||account?.principalId!==current?.principalId||account?.workspaceId!==current?.workspaceId||account?.serverOrigin!==current?.serverOrigin)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(latest?.exchangeUnresolved)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");if(account&&!saved)requireAccount(current)};if(saved){const auth=await profileAuthorization(saved.profile);if(auth.resource!==saved.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const projectId=workspaceOnly?void 0:await selectedProject(saved,env,explicitProject);const c=await connectRemoteMcp(saved.resource,auth.authorization,saved.tenantId);try{const caller=await c.studio.call("workspace.caller",{});if(caller.tenantId!==saved.tenantId||account&&(account.principalId!==caller.principalId||account.serverOrigin!==caller.serverOrigin))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(projectId){const selected=await c.studio.call("project.get",{projectId});if(selected.project.id!==projectId||selected.project.tenantId!==caller.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}await assertCurrent();return{tenantId:caller.tenantId,principalId:caller.principalId,serverOrigin:caller.serverOrigin,home,projectId,resource:saved.resource,profile:saved.profile,assertCurrent}}finally{await c.close().catch(()=>{})}}if(!account)return null;const human=requireAccount(account);if(!human.workspaceId||!workspaceOnly&&!(explicitProject??human.projectId))throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{home,tenantId:human.workspaceId,projectId:workspaceOnly?void 0:z.uuid().parse(explicitProject??human.projectId),principalId:human.principalId,serverOrigin:human.serverOrigin,resource:void 0,profile:void 0,assertCurrent}}async function localCaller(env,explicitProject){const caller=await resolveCaller(env,explicitProject);if(!caller)return null;if(!caller.projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{...caller,projectId:caller.projectId}}function workspaceCaller(env){return resolveCaller(env,void 0,true)}async function callerOriginMatches(origin,caller){if(origin===caller.serverOrigin)return true;if(!caller.resource||!caller.profile)return false;return origin===new URL(caller.resource).origin||origin===await profileHttpOrigin(caller.profile,caller.resource)}export{localCaller,workspaceCaller,callerOriginMatches};
@@ -0,0 +1 @@
1
+ import{workspaceProject}from"./chunk-UYKCN5DU.js";import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import{clientHome,loadConnection,readAccount,tenantConnection}from"./chunk-27KI24GK.js";import{sha256}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";async function selectedProject(scope,env,explicit){if(explicit)return z.uuid().parse(explicit);const selected=await workspaceProject(scope,env);if(selected)return selected;const account=await readAccount(await clientHome(env));const projectId=explicit??(account?.workspaceId===scope.tenantId?account.projectId:null);if(!projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return z.uuid().parse(projectId)}async function renderConnection(env,signal,write=true,projectId){const scope=await loadConnection(env);if(!scope||write&&!scope.scope.split(/\s+/).includes("nvs:write"))throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const auth=await profileAuthorization(scope.profile,signal);if(auth.resource!==scope.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const selected=await selectedProject(scope,env,projectId);return{externalCredential:false,scope:{...scope,projectId:selected},...await connectRemoteMcp(scope.resource,auth.authorization,scope.tenantId)}}async function callerRenderConnection(env,flags,write=true){const url=flags.get("--mcp-url");if(!url&&!flags.has("--token-file"))return renderConnection(env,void 0,write,flags.get("--project"));if(!url||!flags.has("--token-file"))throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const scope=tenantConnection(url),auth=await readCredential(flags,env);return{externalCredential:true,scope:{...scope,projectId:await selectedProject(scope,env,flags.get("--project")),profile:"grant:"+sha256(auth)},...await connectRemoteMcp(scope.resource,auth,scope.tenantId)}}async function renderReceiptScope(studio,scope){const[caller,status]=await Promise.all([studio.call("workspace.caller",{}),studio.call("workspace.status",{})]);if(caller.tenantId!==scope.tenantId||status.tenantId!==scope.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(!status.agentGrantId)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");return{resource:scope.resource,tenantId:scope.tenantId,projectId:scope.projectId,principalId:caller.principalId,grantId:status.agentGrantId}}export{selectedProject,renderConnection,callerRenderConnection,renderReceiptScope};
@@ -0,0 +1 @@
1
+ import{DesktopRuntimeChannelSchema}from"./chunk-4M2SOMSN.js";import{InstalledToolPathsSchema}from"./chunk-ELUJ44BO.js";import{AgentComponentScopeSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema}from"./chunk-6EZX2TRX.js";import{z}from"zod";var digest=z.string().regex(/^[0-9a-f]{64}$/);var version=LocalRuntimeDescriptorSchema.shape.version;var revision=z.int().nonnegative();var request={requestId:z.uuid(),expectedRevision:revision};var planRequest={...request,planId:z.uuid(),fingerprint:digest};var planSelection={version,source:z.enum(["BUNDLED","SIGNED_CHANNEL"]).default("BUNDLED"),tools:z.union([LocalToolChoiceSchema,InstalledToolPathsSchema]).optional()};var componentChannel=DesktopRuntimeChannelSchema.extend({protocol:z.enum(["NVS_RUNTIME_RELEASE_CHANNEL_V1","NVS_DESKTOP_RUNTIME_CHANNEL_V1"])});var selectionVersion=z.union([version,z.literal("latest")]);var ComponentCommandSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("apply"),...planRequest}),z.strictObject({action:z.literal("rollback"),...planRequest}),z.strictObject({action:z.literal("reconcile-install"),...planRequest}),z.strictObject({action:z.literal("start"),...request}),z.strictObject({action:z.literal("stop"),...request}),z.strictObject({action:z.literal("recover"),...request}),z.strictObject({action:z.literal("service-enable"),...request,fingerprint:digest})]);var HostComponentRequestSchema=z.strictObject({scope:AgentComponentScopeSchema,call:z.discriminatedUnion("action",[z.strictObject({action:z.literal("initialize"),channel:componentChannel.optional()}),z.strictObject({action:z.literal("status")}),z.strictObject({action:z.literal("preflight"),kind:z.enum(["library","preview","final"]),source:planSelection.source,version:selectionVersion.default("latest"),channel:componentChannel.optional(),tools:InstalledToolPathsSchema.pick({ffmpeg:true,ffprobe:true,captionAssetsDirectory:true}).partial().optional()}),z.strictObject({action:z.literal("receipt"),requestId:z.uuid()}),z.strictObject({action:z.literal("observe-original"),requestId:z.uuid()}),z.strictObject({action:z.literal("install-plan"),...planSelection,version:selectionVersion.describe("Use latest for the code bundled in this CLI. SIGNED_CHANNEL requires an exact version.")}),z.strictObject({action:z.literal("rollback-plan"),...planSelection}),z.strictObject({action:z.literal("service-plan")}),...ComponentCommandSchema.options])});export{ComponentCommandSchema,HostComponentRequestSchema};
@@ -1 +1 @@
1
- import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalMcpOutputSchemas,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-CTCEGOC7.js";import{LocalLibraryGetSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema}from"./chunk-LZPPTW2K.js";import{fail,optional}from"./chunk-DLW42PJ6.js";import{z}from"zod";import{join}from"node:path";var localTools={local_library_list:{description:"Read bounded metadata projections of this device library in an explicitly authorized Project. No paths, bytes, import or native admission.",input:LocalLibraryProjectionQuerySchema},local_library_get:{description:"Read metadata for one exact authorized local-file version. This does not inspect/decode bytes or create a Job.",input:LocalLibraryGetSchema.omit({ownerKey:true})},local_navigate:{description:"Local execution entry. Discover Project-scoped Runtime progress, recovery and updates. Native writes remain with the cloud owner.",input:z.strictObject({intent:z.string().max(500).optional()})},local_capability_describe:{description:"Inspect the exact public schema for a local capability. Standard discovery stays stable; each call validates current Runtime authority.",input:z.strictObject({tool:z.enum(["local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"])})},local_runtime_status:{description:"Read current authorized local Runtime status. Does not start, stop or mutate native work.",input:z.strictObject({})},local_execution_list:{description:"List a bounded page of pending local execution identities in one authorized Project, then inspect an exact native Job.",input:LocalExecutionListInputSchema},local_execution_inspect:{description:"Inspect one exact native Job in the authorized Project. Native Job/Attempt identity remains authoritative.",input:LocalExecutionInspectInputSchema},local_update_check:{description:"Read signed compatible release metadata only. No executable download, approval, installation or restart.",input:z.strictObject({})}};var LocalMcpTools=class _LocalMcpTools{constructor(client,home,library=false){this.client=client;this.home=home;this.library=library}client;home;library;static async open(connector,home,library=false){const client=await NativeStudioLocalRuntimeClient.fromConnector(connector);let enabled=false;if(library){try{enabled=(await client.library.capability()).available}catch{}}return new _LocalMcpTools(client,home,enabled)}get names(){return Object.keys(localTools).filter(name=>this.library||!name.startsWith("local_library_"))}schema(name){if(!this.names.includes(name))fail("CAPABILITY_UNAVAILABLE");return{name,description:localTools[name].description,inputSchema:z.toJSONSchema(localTools[name].input,{io:"input"}),outputSchema:z.toJSONSchema(LocalMcpOutputSchemas[name],{io:"output",reused:"ref"}),annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:name==="local_update_check"}}}async call(name,raw,signal){return LocalMcpOutputSchemas[name].parse(await this.invoke(name,raw,signal))}async invoke(name,raw,signal){const input=localTools[name].input.parse(raw);if(name==="local_library_list"){if(!this.library)fail("CAPABILITY_UNAVAILABLE");return{location:"LOCAL",...LocalLibraryProjectionPageSchema.parse(await this.client.library.call({...input,action:"scoped-list"},signal))}}if(name==="local_library_get"){if(!this.library)fail("CAPABILITY_UNAVAILABLE");return{location:"LOCAL",item:await this.client.library.call({...input,action:"scoped-get"},signal)}}if(name==="local_capability_describe")return{location:"LOCAL",tool:input.tool,schema:this.schema(input.tool)};if(name==="local_navigate"){let status;try{status=await this.client.status(signal,true)}catch{return{location:"LOCAL",state:"UNAVAILABLE",groups:[],nextActions:[{surface:"CLI",operation:"local.grant",availability:"BLOCKED",reason:"AUTHORIZATION_REQUIRED"}]}}return{location:"LOCAL",state:status.state,...status.deviceAuthority?{deviceAuthority:status.deviceAuthority}:{},groups:[...this.library?[{id:"library",label:"Scoped local media metadata",tools:["local_library_list","local_library_get"]}]:[],{id:"execution",label:"Local execution and recovery",tools:["local_runtime_status","local_execution_list","local_execution_inspect"]},{id:"versions",label:"Versions and updates",tools:["local_update_check"]}],nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"},availability:"AVAILABLE",reason:"READY"},...status.state==="RECOVERY_REQUIRED"?[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:"RECOVERY_REQUIRED"}]:[]]}}if(name==="local_runtime_status")return{...await this.client.status(signal),nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"}}]};if(name==="local_execution_list"){const page=await this.client.executions(LocalExecutionListInputSchema.parse(input),signal);return{...page,nextActions:page.items.map(item=>({tool:"local_execution_inspect",arguments:{tenantId:item.binding.tenantId,projectId:item.binding.projectId,productionId:item.binding.productionId,runtimeJobId:item.binding.runtimeJobId}}))}}if(name==="local_execution_inspect")return{location:"LOCAL",execution:await this.client.inspect(LocalExecutionInspectInputSchema.parse(input),signal),nextActions:[]};if(name==="local_update_check"){const current=await this.client.status(signal);const raw2=await optional(join(this.home,"configuration.json"));const config=z.object({catalogueUrl:z.string().url(),publicKeyFile:z.string()}).parse(raw2);const v=await catalogue(config,signal);return{location:"LOCAL",running:current.versions,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),nextActions:[{surface:"CLI",operation:"local.update.prepare",availability:"BLOCKED",reason:"USER_APPROVAL_REQUIRED"}]}}fail("CAPABILITY_UNAVAILABLE")}};export{localTools,LocalMcpTools};
1
+ import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalMcpOutputSchemas,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-6EZX2TRX.js";import{LocalLibraryGetSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema}from"./chunk-APNZQZFB.js";import{fail,optional}from"./chunk-DLW42PJ6.js";import{z}from"zod";import{join}from"node:path";var localTools={local_library_list:{description:"Read bounded metadata projections of this device library in an explicitly authorized Project. No paths, bytes, import or native admission.",input:LocalLibraryProjectionQuerySchema},local_library_get:{description:"Read metadata for one exact authorized local-file version. This does not inspect/decode bytes or create a Job.",input:LocalLibraryGetSchema.omit({ownerKey:true})},local_navigate:{description:"Local execution entry. Discover Project-scoped Runtime progress, recovery and updates. Native writes remain with the cloud owner.",input:z.strictObject({intent:z.string().max(500).optional()})},local_capability_describe:{description:"Inspect the exact public schema for a local capability. Standard discovery stays stable; each call validates current Runtime authority.",input:z.strictObject({tool:z.enum(["local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"])})},local_runtime_status:{description:"Read current authorized local Runtime status. Does not start, stop or mutate native work.",input:z.strictObject({})},local_execution_list:{description:"List a bounded page of pending local execution identities in one authorized Project, then inspect an exact native Job.",input:LocalExecutionListInputSchema},local_execution_inspect:{description:"Inspect one exact native Job in the authorized Project. Native Job/Attempt identity remains authoritative.",input:LocalExecutionInspectInputSchema},local_update_check:{description:"Read signed compatible release metadata only. No executable download, approval, installation or restart.",input:z.strictObject({})}};var LocalMcpTools=class _LocalMcpTools{constructor(client,home,library=false){this.client=client;this.home=home;this.library=library}client;home;library;static async open(connector,home,library=false){const client=await NativeStudioLocalRuntimeClient.fromConnector(connector);let enabled=false;if(library){try{enabled=(await client.library.capability()).available}catch{}}return new _LocalMcpTools(client,home,enabled)}get names(){return Object.keys(localTools).filter(name=>this.library||!name.startsWith("local_library_"))}schema(name){if(!this.names.includes(name))fail("CAPABILITY_UNAVAILABLE");return{name,description:localTools[name].description,inputSchema:z.toJSONSchema(localTools[name].input,{io:"input"}),outputSchema:z.toJSONSchema(LocalMcpOutputSchemas[name],{io:"output",reused:"ref"}),annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:name==="local_update_check"}}}async call(name,raw,signal){return LocalMcpOutputSchemas[name].parse(await this.invoke(name,raw,signal))}async invoke(name,raw,signal){const input=localTools[name].input.parse(raw);if(name==="local_library_list"){if(!this.library)fail("CAPABILITY_UNAVAILABLE");return{location:"LOCAL",...LocalLibraryProjectionPageSchema.parse(await this.client.library.call({...input,action:"scoped-list"},signal))}}if(name==="local_library_get"){if(!this.library)fail("CAPABILITY_UNAVAILABLE");return{location:"LOCAL",item:await this.client.library.call({...input,action:"scoped-get"},signal)}}if(name==="local_capability_describe")return{location:"LOCAL",tool:input.tool,schema:this.schema(input.tool)};if(name==="local_navigate"){let status;try{status=await this.client.status(signal,true)}catch{return{location:"LOCAL",state:"UNAVAILABLE",groups:[],nextActions:[{surface:"CLI",operation:"local.grant",availability:"BLOCKED",reason:"AUTHORIZATION_REQUIRED"}]}}return{location:"LOCAL",state:status.state,...status.deviceAuthority?{deviceAuthority:status.deviceAuthority}:{},groups:[...this.library?[{id:"library",label:"Scoped local media metadata",tools:["local_library_list","local_library_get"]}]:[],{id:"execution",label:"Local execution and recovery",tools:["local_runtime_status","local_execution_list","local_execution_inspect"]},{id:"versions",label:"Versions and updates",tools:["local_update_check"]}],nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"},availability:"AVAILABLE",reason:"READY"},...status.state==="RECOVERY_REQUIRED"?[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:"RECOVERY_REQUIRED"}]:[]]}}if(name==="local_runtime_status")return{...await this.client.status(signal),nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"}}]};if(name==="local_execution_list"){const page=await this.client.executions(LocalExecutionListInputSchema.parse(input),signal);return{...page,nextActions:page.items.map(item=>({tool:"local_execution_inspect",arguments:{tenantId:item.binding.tenantId,projectId:item.binding.projectId,productionId:item.binding.productionId,runtimeJobId:item.binding.runtimeJobId}}))}}if(name==="local_execution_inspect")return{location:"LOCAL",execution:await this.client.inspect(LocalExecutionInspectInputSchema.parse(input),signal),nextActions:[]};if(name==="local_update_check"){const current=await this.client.status(signal);const raw2=await optional(join(this.home,"configuration.json"));const config=z.object({catalogueUrl:z.string().url(),publicKeyFile:z.string()}).parse(raw2);const v=await catalogue(config,signal);return{location:"LOCAL",running:current.versions,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),nextActions:[{surface:"CLI",operation:"local.update.prepare",availability:"BLOCKED",reason:"USER_APPROVAL_REQUIRED"}]}}fail("CAPABILITY_UNAVAILABLE")}};export{localTools,LocalMcpTools};
@@ -1 +1 @@
1
- import{connectDevice,generateDeviceKey}from"./chunk-GQ32ZQTM.js";import{canResumeDesktop,desktopAutomation,desktopInstallationIdentity,rememberDesktopAutomation}from"./chunk-J2IYRUVM.js";import{LocalInstallationManager,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantSpeech,probeTenantTranscription,socketAbsent}from"./chunk-IF6AUKH3.js";import{DesktopDeviceRecords}from"./chunk-BZPQB66Z.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema}from"./chunk-5TKBEFRX.js";import{LocalDeviceChallengeSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalPreviewAdmissionSchema,canonicalLocalJson,processorFamilies}from"./chunk-LZPPTW2K.js";import{fail,read,sha256}from"./chunk-DLW42PJ6.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","REFERENCE_PREVIEW","TRANSCRIBE_EXTERNAL_QWEN"].includes(kind)):[];if(processing){if(await probeReferenceThumbnail(root,active))processors.push("REFERENCE_PREVIEW");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,...s.pending.agentEnrollment&&{agentEnrollment:true}}: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");if(call.expectedRevision!==void 0&&s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");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(),...call.bindWorkspaceMember||call.agentEnrollment?{expectedPrincipalId:s.scope.principalId}:{},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",...call.action==="enroll"&&call.agentEnrollment&&{agentEnrollment:true}}});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};
1
+ import{connectDevice,generateDeviceKey}from"./chunk-HBDPYWMI.js";import{canResumeDesktop,desktopAutomation,desktopInstallationIdentity,rememberDesktopAutomation}from"./chunk-MLZ3ZPGU.js";import{LocalInstallationManager,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantSpeech,probeTenantTranscription,socketAbsent}from"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema}from"./chunk-IYDHDLTR.js";import{LocalDeviceChallengeSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalPreviewAdmissionSchema,canonicalLocalJson,processorFamilies}from"./chunk-APNZQZFB.js";import{fail,read,sha256}from"./chunk-DLW42PJ6.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","REFERENCE_PREVIEW","TRANSCRIBE_EXTERNAL_QWEN"].includes(kind)):[];if(processing){if(await probeReferenceThumbnail(root,active))processors.push("REFERENCE_PREVIEW");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,...s.pending.agentEnrollment&&{agentEnrollment:true}}: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");if(call.expectedRevision!==void 0&&s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");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(),...call.bindWorkspaceMember||call.agentEnrollment?{expectedPrincipalId:s.scope.principalId}:{},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",...call.action==="enroll"&&call.agentEnrollment&&{agentEnrollment:true}}});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};
@@ -1 +1 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-4NCE337I.js";import{clientHome,loadConnection}from"./chunk-27KI24GK.js";import{optional,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{join}from"node:path";import{z}from"zod";var selection=z.strictObject({version:z.literal(1),tenantId:z.uuid(),resource:z.url(),projectId:z.uuid()});async function workspaceProject(scope,env){const value=await optional(join(await clientHome(env),"selection.json"));if(value===null)return null;const parsed=selection.safeParse(value);if(!parsed.success)throw new NativeStudioSdkError("PROJECT_SELECTION_INVALID","BLOCKED","NO_WRITE");return parsed.data.tenantId===scope.tenantId&&(!scope.resource||parsed.data.resource===scope.resource)?parsed.data.projectId:null}async function workspaceCommand(argv,env){const[command,...args]=argv;if(!["workspaces","workspace","projects","project"].includes(command??""))return null;let connection;try{connection=await loadConnection(env)}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="CONNECTION_ACCOUNT_MISMATCH")return null;throw error}if(!connection)return null;const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!value||value.startsWith("--")||flags.has(key)||!["--id","--limit","--next"].includes(key))throw Error();flags.set(key,value)}if(command==="projects"?flags.has("--id"):command==="workspaces"?flags.size>0:flags.size!==1||!flags.has("--id"))throw Error();const auth=await profileAuthorization(connection.profile);const remote=await connectRemoteMcp(connection.resource,auth.authorization,connection.tenantId);try{if(command==="workspaces"){const page=await remote.studio.call("workspace.query",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaces:page.items}}}if(command==="projects"){const page=await remote.studio.call("project.query",{...flags.has("--limit")?{limit:z.coerce.number().int().min(1).max(100).parse(flags.get("--limit"))}:{},...flags.has("--next")?{next:flags.get("--next")}:{}});return{exitCode:0,output:{semanticStatus:"SUCCESS",...page}}}const id=z.uuid().parse(flags.get("--id"));if(command==="workspace"){if(id!==connection.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value2=await remote.studio.call("workspace.get",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:value2.id}}}const value=await remote.studio.call("project.get",{projectId:id});await write(join(await clientHome(env),"selection.json"),JSON.stringify({version:1,tenantId:connection.tenantId,resource:connection.resource,projectId:value.project.id}));return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project}}}finally{await remote.close().catch(()=>{})}}export{workspaceProject,workspaceCommand};
1
+ import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import{clientHome,loadConnection}from"./chunk-27KI24GK.js";import{optional,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{join}from"node:path";import{z}from"zod";var selection=z.strictObject({version:z.literal(1),tenantId:z.uuid(),resource:z.url(),projectId:z.uuid()});async function workspaceProject(scope,env){const value=await optional(join(await clientHome(env),"selection.json"));if(value===null)return null;const parsed=selection.safeParse(value);if(!parsed.success)throw new NativeStudioSdkError("PROJECT_SELECTION_INVALID","BLOCKED","NO_WRITE");return parsed.data.tenantId===scope.tenantId&&(!scope.resource||parsed.data.resource===scope.resource)?parsed.data.projectId:null}async function workspaceCommand(argv,env){const[command,...args]=argv;if(!["workspaces","workspace","projects","project"].includes(command??""))return null;let connection;try{connection=await loadConnection(env)}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="CONNECTION_ACCOUNT_MISMATCH")return null;throw error}if(!connection)return null;const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!value||value.startsWith("--")||flags.has(key)||!["--id","--limit","--next"].includes(key))throw Error();flags.set(key,value)}if(command==="projects"?flags.has("--id"):command==="workspaces"?flags.size>0:flags.size!==1||!flags.has("--id"))throw Error();const auth=await profileAuthorization(connection.profile);const remote=await connectRemoteMcp(connection.resource,auth.authorization,connection.tenantId);try{if(command==="workspaces"){const page=await remote.studio.call("workspace.query",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaces:page.items}}}if(command==="projects"){const page=await remote.studio.call("project.query",{...flags.has("--limit")?{limit:z.coerce.number().int().min(1).max(100).parse(flags.get("--limit"))}:{},...flags.has("--next")?{next:flags.get("--next")}:{}});return{exitCode:0,output:{semanticStatus:"SUCCESS",...page}}}const id=z.uuid().parse(flags.get("--id"));if(command==="workspace"){if(id!==connection.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value2=await remote.studio.call("workspace.get",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:value2.id}}}const value=await remote.studio.call("project.get",{projectId:id});await write(join(await clientHome(env),"selection.json"),JSON.stringify({version:1,tenantId:connection.tenantId,resource:connection.resource,projectId:value.project.id}));return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project}}}finally{await remote.close().catch(()=>{})}}export{workspaceProject,workspaceCommand};