@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
@@ -1,45 +0,0 @@
1
- import{LocalInstallationManager,ownerClient,runtimeEnvironment,socketAbsent,supportsLoginService,verifySlot,waitStopped}from"./chunk-IF6AUKH3.js";import{LocalToolSelectionSchema}from"./chunk-CTCEGOC7.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-LZPPTW2K.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{realpath as realpath2,unlink as unlink2}from"node:fs/promises";import{join as join2}from"node:path";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
- `}}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 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}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{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{loginCommand,runLoginService};
@@ -1 +0,0 @@
1
- import{ComponentCommandSchema,HostComponentRequestSchema}from"./chunk-226SBV53.js";import"./chunk-WXEERCXN.js";import"./chunk-HIBT6NXN.js";import"./chunk-J2IYRUVM.js";import"./chunk-IF6AUKH3.js";import"./chunk-5TKBEFRX.js";import"./chunk-CTCEGOC7.js";import"./chunk-LZPPTW2K.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";export{ComponentCommandSchema,HostComponentRequestSchema};
@@ -1 +0,0 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-4NCE337I.js";import"./chunk-2UYKJ6YN.js";import"./chunk-LZPPTW2K.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";var operations={status:"device.status",enroll:"device.enroll","enrollment-issue":"device.enrollment.issue","enrollment-lookup":"device.enrollment.lookup",revoke:"device.revoke",receipt:"device.management-receipt"};async function deviceManagementCommand(action,args,env,stdin){if(!action||!Object.hasOwn(operations,action))throw Error();const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--input","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}if(!flags.has("--input"))throw Error();await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(k=>flags.has(k)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=tenantConnection(resource);const raw=await readInput(flags.get("--input"),stdin);const nested=action==="receipt"?raw.input:raw;if(nested?.tenantId!==void 0&&String(nested.tenantId).toLowerCase()!==scope.tenantId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const key=operations[action];const input=action==="receipt"?{command:raw}:{...raw,tenantId:scope.tenantId};const output=await connection.studio.call(key,input);return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceManagementCommand};
@@ -1 +0,0 @@
1
- import{runLoginService}from"./chunk-UITIQHVU.js";import{ComponentCommandSchema}from"./chunk-226SBV53.js";import{configureDesktopChannel,desktopRuntimeChannel}from"./chunk-2GV47BUV.js";import"./chunk-WXEERCXN.js";import"./chunk-HIBT6NXN.js";import"./chunk-J2IYRUVM.js";import{InstalledToolPathsSchema,LocalInstallationManager,captureInstalledTools,socketAbsent}from"./chunk-IF6AUKH3.js";import{DesktopDeviceRecords}from"./chunk-BZPQB66Z.js";import"./chunk-5TKBEFRX.js";import{AgentComponentScopeSchema,AgentComponentStatusSchema,LocalRuntimeStatusSchema}from"./chunk-CTCEGOC7.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-LZPPTW2K.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,directory,entries,fail,optional,privateAccess,sha256,write}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.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 reason2=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:reason2,at:manager?at2:null},readiness:{state:ready?"READY":manager?"BLOCKED":"UNKNOWN",reasonCode:version&&observed?.capabilityMismatch?"CAPABILITY_VERSION_MISMATCH":ready||!version?reason2:"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"}})}var ok=output=>({exitCode:0,output});var acknowledged=output=>({exitCode:output.phase==="COMPLETE"?0:2,output});async function serviceFingerprint(home){const service=await observeLoginService(home);if(!("fingerprint"in service)||!service.fingerprint||!("supervision"in service)||service.supervision!=="EXPLICIT_RECOVERY")fail("COMPONENT_SERVICE_UNCONFIRMED");return service.fingerprint}async function applyComponentCommand(manager,command,before){const home=manager.ledger.root;switch(command.action){case"apply":case"rollback":{if(command.action==="rollback"){const plan=await manager.plan(command.planId),version=plan.release.descriptor.version;if(version===before.installedVersion||!await manager.ledger.hadCompletedVersion(version))fail("COMPONENT_ROLLBACK_VERSION_UNAVAILABLE")}await manager.apply(command.planId,command.fingerprint);return"COMPONENT_VERSION_ACTIVATED"}case"reconcile-install":await manager.reconcile(command.planId,command.fingerprint);return"COMPONENT_INSTALLATION_RECONCILED";case"service-enable":await runLoginService("service-enable",home,command.fingerprint,"EXPLICIT_RECOVERY");return"COMPONENT_SERVICE_REGISTERED";case"start":if(before.loginService==="REGISTERED")await runLoginService("service-start",home,await serviceFingerprint(home));else await manager.start();return"COMPONENT_STARTED";case"stop":if(before.loginService!=="NONE")await runLoginService("service-disable",home,await serviceFingerprint(home));if((await manager.status()).running)await manager.stop();return"COMPONENT_STOPPED";case"recover":if(before.readiness.state==="READY")return"COMPONENT_HEALTHY";if(before.loginService==="REGISTERED")await runLoginService("service-restart",home,await serviceFingerprint(home));else{if(before.liveness.state==="ALIVE")await manager.stop();await manager.start()}return"COMPONENT_RECOVERED"}}function outcomeObserved(command,current){switch(command.action){case"stop":return current.liveness.state==="STOPPED"&&current.loginService==="NONE";case"service-enable":return current.loginService==="REGISTERED";case"reconcile-install":return true;default:return current.readiness.state==="READY"}}function reason(error){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:"COMPONENT_ACTION_UNAVAILABLE"}async function runHostComponent(parent,{scope,call}){const target=await componentHome(parent,scope,call.action==="initialize"),home=target.home,receipts=new ComponentReceipts(home);if(call.action==="initialize")return withComponentLock(home,async()=>{const manager2=await initializeComponent(home,scope,call.channel);return ok(await observeComponent(home,scope,manager2,receipts))});if(call.action==="receipt")return ok({receipt:target.claimed?await receipts.find(call.requestId):null});const manager=target.claimed?await LocalInstallationManager.openExisting(home):null;const observe=()=>observeComponent(home,scope,manager,receipts);if(call.action==="status")return ok(await observe());if(!manager)fail("COMPONENT_INITIALIZATION_REQUIRED","NO_WRITE");if(call.action==="service-plan"){await observe();return ok(await runLoginService("service-plan",home,void 0,"EXPLICIT_RECOVERY"))}if(call.action==="install-plan"||call.action==="rollback-plan"){if(call.source==="SIGNED_CHANNEL"&&call.version==="latest")fail("EXACT_RELEASE_VERSION_REQUIRED","NO_WRITE");return withComponentLock(home,async()=>{const before=await observe();if(call.action==="rollback-plan"&&(call.version===before.installedVersion||!await manager.ledger.hadCompletedVersion(call.version)))fail("COMPONENT_ROLLBACK_VERSION_UNAVAILABLE","NO_WRITE");const paths=InstalledToolPathsSchema.safeParse(call.tools);const tools=paths.success?await captureInstalledTools(paths.data):call.tools;return ok(call.source==="SIGNED_CHANNEL"?await manager.prepare(call.version,tools):await manager.prepareBundled(call.version,tools))})}if(call.action==="observe-original")return withComponentLock(home,async()=>{const original=await receipts.find(call.requestId);if(!original)fail("COMPONENT_RECEIPT_NOT_FOUND");if(original.phase!=="SENDING")return ok(original);const current=await observe();const command=original.command;const observed=command.expectedRevision===current.installationRevision&&["start","stop","recover","service-enable"].includes(command.action)&&outcomeObserved(command,current);return ok(await receipts.finish(original,{phase:observed?"COMPLETE":"DEGRADED",outcome:observed?"OBSERVED":"UNKNOWN",reasonCode:observed?"COMPONENT_STATE_OBSERVED":"COMPONENT_ORIGINAL_OUTCOME_UNKNOWN",installationRevision:current.installationRevision,runningVersion:current.runningVersion}))});return withComponentLock(home,async()=>{const replay=await receipts.original(call);if(replay)return acknowledged(replay);const before=await observe();if(call.expectedRevision!==before.installationRevision)fail("REVISION_CONFLICT","NO_WRITE");if(call.action==="recover"&&before.capabilityMismatch)return{exitCode:2,output:{semanticStatus:"CAPABILITY_UNAVAILABLE",error:{code:"CAPABILITY_VERSION_MISMATCH",outcome:"NO_WRITE",details:before.capabilityMismatch}}};if(before.liveness.state==="UNKNOWN"||before.loginService==="UNKNOWN")fail("COMPONENT_OWNERSHIP_UNCONFIRMED","NO_WRITE");if(before.loginService==="INCOMPLETE"&&call.action!=="stop")fail("COMPONENT_SERVICE_NEEDS_STOP","NO_WRITE");const{latest}=await receipts.snapshot();if(call.action==="recover"&&before.readiness.state!=="READY"&&latest?.command.action==="recover"&&latest.phase==="DEGRADED")fail("COMPONENT_RECOVERY_EXHAUSTED","NO_WRITE");const original=await receipts.begin(call,before.runningVersion);let reasonCode,after,phase="DEGRADED";try{reasonCode=await applyComponentCommand(manager,call,before);after=await observe();if(outcomeObserved(call,after))phase="COMPLETE";else reasonCode=call.action==="recover"?"COMPONENT_RESTART_INEFFECTIVE":"COMPONENT_RESULT_UNCONFIRMED"}catch(error){reasonCode=reason(error);after=await observe().catch(()=>before)}return acknowledged(await receipts.finish(original,{phase,outcome:phase==="COMPLETE"?"SUCCESS":"UNKNOWN",reasonCode,installationRevision:after.installationRevision,runningVersion:after.runningVersion}))})}export{runHostComponent};
@@ -1 +0,0 @@
1
- import{HostComponentRequestSchema}from"./chunk-226SBV53.js";import{HostEnrollmentRequestSchema}from"./chunk-2MKMGMA4.js";import"./chunk-WXEERCXN.js";import"./chunk-HIBT6NXN.js";import"./chunk-67QDMD7M.js";import"./chunk-GQ32ZQTM.js";import"./chunk-J2IYRUVM.js";import"./chunk-IF6AUKH3.js";import"./chunk-BZPQB66Z.js";import"./chunk-5TKBEFRX.js";import"./chunk-CTCEGOC7.js";import"./chunk-LZPPTW2K.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";import{z}from"zod";var protocol="NVS_EXTERNAL_HOST_V1";var requests={component:HostComponentRequestSchema,enrollment:HostEnrollmentRequestSchema};function hostOverview(deviceActions){return{exitCode:0,output:{protocol,agentRuntime:"EXTERNAL",commands:["host component --input <private-json|-> [--home <private-parent-home>]","host enrollment --input <private-json|-> [--home <component-home>]","host device --input <json|-> [--home <private-client-home>]"],actions:[...deviceActions],help:["host component help [<action>]","host enrollment help [<action>]"],guidance:"Use workspace_caller and workspace_status on your tenant MCP for component scope. Prepare the bundled install, then prepare enrollment with authority OAUTH_AGENT. Send its invoke on the same MCP and pass its ticket to the same host through private input. Read the original lookup after an interrupted reply. Use workspace_caller.skill or nvs skill for the configured guide."}}}function hostActionHelp(command,action){const request=requests[command],options=request.shape.call.options;const actions=options.map(option=>option.shape.action.value);const selected=action&&options.find(option=>option.shape.action.value===action);const invalid=action!==void 0&&!selected;return{exitCode:invalid?2:0,output:{protocol,command:"host "+command,actions,help:"host "+command+" help <action>",...invalid&&{semanticStatus:"INVALID_INPUT",error:{code:"INVALID_INPUT",outcome:"NO_WRITE"}},...selected&&{action,inputSchema:z.toJSONSchema(z.strictObject({scope:request.shape.scope,call:selected}),{io:"input"})}}}}export{hostActionHelp,hostOverview};
@@ -1 +0,0 @@
1
- import{HostEnrollmentRequestSchema,runHostEnrollment}from"./chunk-2MKMGMA4.js";import{runDesktopDeviceRequest}from"./chunk-67QDMD7M.js";import"./chunk-GQ32ZQTM.js";import"./chunk-J2IYRUVM.js";import"./chunk-IF6AUKH3.js";import"./chunk-BZPQB66Z.js";import{DesktopDeviceRequestSchema}from"./chunk-5TKBEFRX.js";import"./chunk-CTCEGOC7.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-LZPPTW2K.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve}from"node:path";var actions=new Set(["inspect","enroll","revoke","dispatch","record","refused","prove","connect","connection-recover","media-validation-capability","media-processing-capability"]);var helpFlags=["help","--help"];async function runHostCli(argv,stdin=process.stdin){let entered=false;let mutation=false;try{if(!argv.length||argv.length===1&&helpFlags.includes(argv[0]))return(await import("./host-help-SBXGX457.js")).hostOverview(actions);const[command,...rest]=argv,options=new Map;if(command!=="device"&&command!=="enrollment"&&command!=="component")throw Error();if(command!=="device"&&rest.length<=2&&helpFlags.includes(rest[0]??""))return(await import("./host-help-SBXGX457.js")).hostActionHelp(command,rest[1]);for(let i=0;i<rest.length;i+=2){const key=rest[i],value=rest[i+1];if(!key||!["--input","--home"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const file=options.get("--input");if(!file)throw Error();const home=resolve(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(file,stdin,command!=="device");if(command==="component"){const{HostComponentRequestSchema}=await import("./component-contract-HETXQ2J4.js");const request2=HostComponentRequestSchema.parse(raw);entered=true;mutation=!["status","receipt","service-plan"].includes(request2.call.action);return await(await import("./host-component-H3Q7TU5Y.js")).runHostComponent(home,request2)}if(command==="enrollment"){const request2=HostEnrollmentRequestSchema.parse(raw);entered=true;mutation=request2.call.action!=="inspect";return{exitCode:0,output:await runHostEnrollment(home,request2)}}const request=DesktopDeviceRequestSchema.parse(raw);if(!actions.has(request.call.action))throw Error();mutation=!["inspect","media-validation-capability","media-processing-capability"].includes(request.call.action);entered=true;const output=await runDesktopDeviceRequest(home,request,{allowedPendingKinds:["ENROLL","REVOKE_DEVICE"]});return{exitCode:0,output}}catch(error){const code=error instanceof LocalClientError?error.code:!entered?"INVALID_INPUT":"INTERNAL_OPERATIONAL_FAILURE";const knownRefusal=error instanceof LocalClientError&&error.outcome==="NO_WRITE";const uncertain=!knownRefusal&&(entered&&mutation&&code!=="DEVICE_COMMAND_UNSUPPORTED"||/(?:UNKNOWN|RECOVERY_REQUIRED|PROOF_UNAVAILABLE)/.test(code)||code==="INTERNAL_OPERATIONAL_FAILURE");return{exitCode:2,output:{semanticStatus:["INVALID_INPUT","REVISION_CONFLICT"].includes(code)?code:"BLOCKED",error:{code,outcome:uncertain?"UNKNOWN":"NO_WRITE"}}}}}export{runHostCli};
@@ -1 +0,0 @@
1
- import{connectRemoteMcp}from"./chunk-4NCE337I.js";import"./chunk-2UYKJ6YN.js";import"./chunk-LZPPTW2K.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{connectRemoteMcp};
@@ -1 +0,0 @@
1
- import{callerRenderConnection}from"./chunk-H46NB5FL.js";import"./chunk-TIHGZGU3.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-4NCE337I.js";import"./chunk-2UYKJ6YN.js";import{DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,PreparedDeviceRenderSchema}from"./chunk-LZPPTW2K.js";import{clientHome}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{directory,optional,sha256,write}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{join,resolve}from"node:path";async function assertRenderProject(studio,scope,productionId,options){const snapshot=await studio.call("production.snapshot",{productionId},options);if(snapshot.tenantId!==scope.tenantId||snapshot.projectId!==scope.projectId||snapshot.productionId!==productionId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}var receipt=z.strictObject({scope:z.string(),intent:DeviceRenderIntentSchema,prepared:PreparedDeviceRenderSchema});function requestPrefix(root,scope,requestId){const binding=scope.resource+"#"+sha256(scope.profile)+"#"+scope.projectId;return{binding,prefix:join(root,sha256(binding+"\n"+requestId))}}function unknownReceipt(productionId,idempotencyKey){return{exitCode:1,output:{semanticStatus:"BLOCKED",error:{code:"OUTCOME_UNKNOWN",outcome:"UNKNOWN"},idempotencyKey,productionId}}}async function readRenderSetup(kind,flags,env){const allowed=["--kind","--production","--project","--mcp-url","--token-file",kind==="receipt"?"--request":"--device"];if([...flags.keys()].some(key=>!allowed.includes(key)))throw Error();const renderKind=DeviceRenderReadSchema.shape.kind.parse(flags.get("--kind"));const productionId=z.uuid().parse(flags.get("--production"));const requestId=kind==="receipt"?z.uuid().parse(flags.get("--request")):void 0;const deviceId=z.uuid().optional().parse(flags.get("--device"));const conn=await callerRenderConnection(env,flags,false);const{scope,studio}=conn;try{await assertRenderProject(studio,scope,productionId);if(requestId){const home=await clientHome(env).catch(error=>{if(error.code==="ENOENT")return null;throw error});if(!home)return unknownReceipt(productionId,requestId);const{binding,prefix}=requestPrefix(join(home,"renders"),scope,requestId);const saved=await optional(prefix+".request.json");if(!saved)return unknownReceipt(productionId,requestId);const{scope:savedScope,intent,prepared}=receipt.parse(saved);if(savedScope!==binding||intent.kind!==renderKind||prepared.kind!==renderKind||intent.productionId!==productionId||prepared.command.productionId!==productionId||prepared.command.tenantId!==scope.tenantId||intent.idempotencyKey!==requestId||prepared.command.idempotencyKey!==requestId||prepared.command.deviceExecution.deviceId!==intent.deviceId||prepared.command.deviceExecution.validationMode!==intent.validationMode)throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");try{return{exitCode:0,output:await studio.deviceRenders.receipt(prepared)}}catch(error){if(error instanceof NativeStudioSdkError&&!["NOT_FOUND","OUTCOME_UNKNOWN","TRANSPORT_UNAVAILABLE","REQUEST_ABORTED"].includes(error.code))throw error;return unknownReceipt(productionId,requestId)}}const[basis,candidates]=await Promise.all([studio.deviceRenders.basis({kind:renderKind,productionId}),studio.deviceRenders.list({kind:renderKind,projectId:scope.projectId,deviceId})]);const available=candidates.items.some(device=>device.availability==="AVAILABLE");const eligible=basis.basis!==null&&available;return{exitCode:eligible?0:4,output:{semanticStatus:eligible?"SUCCESS":"BLOCKED",productionId,...basis,eligible,candidates,deviceStatus:available?"AVAILABLE":candidates.truncated?"INCONCLUSIVE":"UNAVAILABLE"}}}finally{await conn.close().catch(()=>{})}}async function renderCommand(argv,env){const[kind,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const k=args[i],v=args[i+1];if(!k||!v||v.startsWith("--")||flags.has(k)||!["--production","--project","--request","--device","--profile-id","--validation-mode","--kind","--render","--role","--output","--mcp-url","--token-file"].includes(k))throw Error();flags.set(k,v)}if(kind==="eligibility"||kind==="receipt")return readRenderSetup(kind,flags,env);if(kind==="status"||kind==="download"){const allowed=new Set(["--kind","--project","--production","--render","--mcp-url","--token-file",...kind==="download"?["--role","--output"]:[]]);if(Array.from(flags.keys()).some(key=>!allowed.has(key)))throw Error();const input=DeviceRenderReadSchema.parse({kind:flags.get("--kind"),productionId:flags.get("--production"),renderId:flags.get("--render")});const conn2=await callerRenderConnection(env,flags,false);try{if(kind==="status"){const view=await conn2.studio.deviceRenders.get(input);if(view.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return{exitCode:0,output:view}}const filename=flags.get("--output");if(!filename)throw Error();const request=DeviceRenderDownloadSchema.parse({...input,role:flags.get("--role")??"VIDEO"});const output=await conn2.studio.deviceRenders.download(request,void 0,conn2.scope.projectId);if(output.object.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await write(resolve(filename),output.bytes,true);return{exitCode:0,output:{semanticStatus:"SUCCESS",renderId:output.renderId,representationId:output.representationId,byteSize:output.object.byteSize,checksumSha256:output.object.checksumSha256}}}finally{await conn2.close().catch(()=>{})}}if(["--kind","--render","--role","--output"].some(key=>flags.has(key)))throw Error();const intent=DeviceRenderIntentSchema.parse({kind,productionId:flags.get("--production"),idempotencyKey:z.uuid().parse(flags.get("--request")),...flags.has("--device")?{deviceId:flags.get("--device")}:{},...flags.has("--profile-id")?{profileId:flags.get("--profile-id")}:{},...flags.has("--validation-mode")?{validationMode:flags.get("--validation-mode")}:{}});const conn=await callerRenderConnection(env,flags);try{await assertRenderProject(conn.studio,conn.scope,intent.productionId);const root=await directory(join(await clientHome(env,true),"renders"));const{binding,prefix}=requestPrefix(root,conn.scope,intent.idempotencyKey);const previous=await optional(prefix+".request.json");if(previous){const old=receipt.parse(previous);if(old.scope!==binding||JSON.stringify(old.intent)!==JSON.stringify(intent))throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");const result=await optional(prefix+".result.json");if(result)return{exitCode:0,output:result};const failure=await optional(prefix+".failure.json");if(failure)return{exitCode:1,output:{semanticStatus:"BLOCKED",error:failure}};try{const recovered=await conn.studio.deviceRenders.receipt(old.prepared);await write(prefix+".result.json",JSON.stringify(recovered),true);return{exitCode:0,output:recovered}}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="REVISION_CONFLICT")throw error}const unknown=unknownReceipt(intent.productionId,intent.idempotencyKey);return{...unknown,output:{...unknown.output,nextAction:"Use nvs render receipt with the original kind, Production and request ID."}}}const prepared=await conn.studio.deviceRenders.prepare(intent);await write(prefix+".request.json",JSON.stringify({scope:binding,intent,prepared}),true);let output;try{output=await conn.studio.deviceRenders.start(prepared)}catch(e){if(e instanceof NativeStudioSdkError&&e.outcome!=="UNKNOWN")await write(prefix+".failure.json",JSON.stringify({code:e.code,outcome:e.outcome,semanticStatus:e.semanticStatus}),true);throw e}try{await write(prefix+".result.json",JSON.stringify(output),true)}catch{throw new NativeStudioSdkError("OUTCOME_UNKNOWN","BLOCKED","UNKNOWN")}return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{renderCommand};
@@ -1 +0,0 @@
1
- import{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,DeviceDiscoveryInputSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentObservationSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentTicketSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceStatusInputSchema,DeviceStatusSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WorkspaceStatusSchema,assertCarrierCoverage,issueDeviceEnrollment,lookupDeviceEnrollment,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,recoverDeviceEnrollment,sdkCarrierDifferences,sdkImageMediaTools,sdkMcpTools,sdkOperations,submitDeviceEnrollment,validateDeviceEnrollmentHandoff,verifyWebhookNotification,waitForOperation}from"./chunk-LZPPTW2K.js";import{CapabilityVersionMismatchSchema}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-TT7IA5HB.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,CapabilityVersionMismatchSchema,DeviceDiscoveryInputSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentObservationSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentTicketSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceStatusInputSchema,DeviceStatusSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WorkspaceStatusSchema,assertCarrierCoverage,issueDeviceEnrollment,lookupDeviceEnrollment,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,recoverDeviceEnrollment,sdkCarrierDifferences,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,submitDeviceEnrollment,validateDeviceEnrollmentHandoff,verifyWebhookNotification,waitForOperation};