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

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 (57) 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-APNZQZFB.js → chunk-2S7FI3HF.js} +1 -1
  5. package/dist/_chunks/{chunk-OSO6KRE2.js → chunk-3RNDOAQI.js} +1 -1
  6. package/dist/_chunks/{chunk-QK4XPVKT.js → chunk-4AD4PNUX.js} +1 -1
  7. package/dist/_chunks/{chunk-D74NHT4I.js → chunk-5Y7J2OYL.js} +1 -1
  8. package/dist/_chunks/{chunk-GLAF74UU.js → chunk-76E5R3OC.js} +1 -1
  9. package/dist/_chunks/{chunk-4PAVWOPA.js → chunk-7IVAYDU3.js} +1 -1
  10. package/dist/_chunks/{chunk-L3QA7FLZ.js → chunk-DMA53YVU.js} +1 -1
  11. package/dist/_chunks/{chunk-AFNJRZLJ.js → chunk-ETK7GYCB.js} +1 -1
  12. package/dist/_chunks/{chunk-ELUJ44BO.js → chunk-FFXSXE3G.js} +1 -1
  13. package/dist/_chunks/{chunk-HBDPYWMI.js → chunk-H4FH6STZ.js} +1 -1
  14. package/dist/_chunks/{chunk-6EZX2TRX.js → chunk-LDBXGRCQ.js} +1 -1
  15. package/dist/_chunks/{chunk-K35CWLDH.js → chunk-LTNJ45JP.js} +1 -1
  16. package/dist/_chunks/{chunk-MLZ3ZPGU.js → chunk-MZWEFYHE.js} +1 -1
  17. package/dist/_chunks/{chunk-ROGOASYF.js → chunk-PQCA4X5H.js} +1 -1
  18. package/dist/_chunks/{chunk-IYDHDLTR.js → chunk-SM2I7TJ3.js} +1 -1
  19. package/dist/_chunks/{chunk-FVY3PLG7.js → chunk-VXYZCCCQ.js} +1 -1
  20. package/dist/_chunks/{chunk-UYKCN5DU.js → chunk-VYCNG6TR.js} +1 -1
  21. package/dist/_chunks/{chunk-4M2SOMSN.js → chunk-WLQMICJN.js} +1 -1
  22. package/dist/_chunks/{chunk-NG4BDFEY.js → chunk-X5MVC46N.js} +1 -1
  23. package/dist/_chunks/{chunk-XUSVNPR5.js → chunk-X5PBZTKX.js} +1 -1
  24. package/dist/_chunks/{chunk-LBK42NHW.js → chunk-ZMJYBUS3.js} +1 -1
  25. package/dist/_chunks/{chunk-QE7O57PQ.js → chunk-ZYXHPTT2.js} +1 -1
  26. package/dist/_chunks/component-contract-2JHTRTOB.js +1 -0
  27. package/dist/_chunks/{component-preflight-WECLCZLF.js → component-preflight-6OWDQAZT.js} +1 -1
  28. package/dist/_chunks/{device-management-TLRUMZL5.js → device-management-JPS4HG34.js} +1 -1
  29. package/dist/_chunks/{device-preflight-C7FFUXI2.js → device-preflight-GTQ67H7C.js} +1 -1
  30. package/dist/_chunks/{devices-inventory-BZF53UAU.js → devices-inventory-E6ZLXCVR.js} +1 -1
  31. package/dist/_chunks/{devices-main-V3YHCB2C.js → devices-main-2BMCANKU.js} +1 -1
  32. package/dist/_chunks/{host-component-Q5IHRHRI.js → host-component-ZYQ5ETVL.js} +1 -1
  33. package/dist/_chunks/{host-help-7BGYR4ET.js → host-help-VNLA3YOV.js} +1 -1
  34. package/dist/_chunks/{host-main-JLIBRHC2.js → host-main-KLWW7R47.js} +1 -1
  35. package/dist/_chunks/{library-main-ATRFEAVN.js → library-main-3WWH7UYV.js} +1 -1
  36. package/dist/_chunks/{local-main-KTYCLHDA.js → local-main-5BW63USP.js} +1 -1
  37. package/dist/_chunks/{local-mcp-ISMU6ADI.js → local-mcp-AARKBDU5.js} +1 -1
  38. package/dist/_chunks/{main-MOZS2EK3.js → main-LGYJ3ZCN.js} +1 -1
  39. package/dist/_chunks/mcp-BLSK636Q.js +1 -0
  40. package/dist/_chunks/{observe-entry-E6DFHIMW.js → observe-entry-JVZAMB7N.js} +1 -1
  41. package/dist/_chunks/{remote-client-T75C45JO.js → remote-client-25Z65VJU.js} +1 -1
  42. package/dist/_chunks/{render-main-OGCO2LX4.js → render-main-6Z3DKCWL.js} +1 -1
  43. package/dist/_chunks/{source-import-55JJ26AA.js → source-import-PNMCMTK7.js} +1 -1
  44. package/dist/_chunks/{src-V2K52JDH.js → src-7HSJFRVQ.js} +1 -1
  45. package/dist/_chunks/{workspace-main-3P56DSEQ.js → workspace-main-QX5JGEMR.js} +1 -1
  46. package/dist/_types/contracts/interface/operation.d.ts +59 -0
  47. package/dist/_types/contracts/interface/production-snapshot.d.ts +25 -0
  48. package/dist/_types/contracts/interface/query.d.ts +25 -0
  49. package/dist/_types/contracts/lifecycle-event-projections.d.ts +2 -2
  50. package/dist/_types/contracts/navigation-context.d.ts +49 -1
  51. package/dist/_types/contracts/navigation.d.ts +1 -1
  52. package/dist/entry.js +1 -1
  53. package/dist/local-management.js +1 -1
  54. package/dist/local-navigation.js +1 -1
  55. package/package.json +1 -1
  56. package/dist/_chunks/component-contract-KXK7WIUI.js +0 -1
  57. package/dist/_chunks/mcp-M2SO3J2H.js +0 -1
@@ -1 +1 @@
1
- import{DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema}from"./chunk-L3QA7FLZ.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./chunk-MLZ3ZPGU.js";import{LocalInstallationManager,ownerClient,socketAbsent,waitStopped}from"./chunk-ELUJ44BO.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema}from"./chunk-IYDHDLTR.js";import{CpuSpeechPrepareInputSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema}from"./chunk-6EZX2TRX.js";import{canonicalLocalJson}from"./chunk-APNZQZFB.js";import{atomicMove,directory,entries,fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z as z7}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest3=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest3||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest3}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest3=record.digest}return{plan,digest:digest3}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews","library"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join3(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join3(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join3(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join3(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join4(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join4(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.literal("speech-prepare"),input:CpuSpeechPrepareInputSchema}),z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional(),speech:z7.strictObject({voiceIds:CpuSpeechPrepareInputSchema.shape.voiceIds}).optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,"speech-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};export{runDesktopStorageRequest,runDesktopOfflineRequest,runDesktopAgentRequest,DesktopBootstrapRequestSchema,DesktopBootstrapReplySchema,runDesktopWorkspaceRequest,DesktopRuntimeChannelSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,DesktopChannelInfoSchema,desktopOwnerResponses};
1
+ import{DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema}from"./chunk-DMA53YVU.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./chunk-MZWEFYHE.js";import{LocalInstallationManager,ownerClient,socketAbsent,waitStopped}from"./chunk-FFXSXE3G.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema}from"./chunk-SM2I7TJ3.js";import{CpuSpeechPrepareInputSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema}from"./chunk-LDBXGRCQ.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{atomicMove,directory,entries,fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z as z7}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest3=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest3||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest3}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest3=record.digest}return{plan,digest:digest3}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews","library"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join3(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join3(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join3(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join3(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join4(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join4(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.literal("speech-prepare"),input:CpuSpeechPrepareInputSchema}),z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional(),speech:z7.strictObject({voiceIds:CpuSpeechPrepareInputSchema.shape.voiceIds}).optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,"speech-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};export{runDesktopStorageRequest,runDesktopOfflineRequest,runDesktopAgentRequest,DesktopBootstrapRequestSchema,DesktopBootstrapReplySchema,runDesktopWorkspaceRequest,DesktopRuntimeChannelSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,DesktopChannelInfoSchema,desktopOwnerResponses};
@@ -1 +1 @@
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};
1
+ import{selectedProject}from"./chunk-3RNDOAQI.js";import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.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 +1 @@
1
- import{readCredential}from"./chunk-QGK6G6YS.js";import{NativeStudioAgentClient}from"./chunk-APNZQZFB.js";import{defaultConnection}from"./chunk-27KI24GK.js";async function withRemoteClient(options,environment,httpOnly,action,budgets={}){budgets.signal?.throwIfAborted();await defaultConnection(options,environment,true);budgets.signal?.throwIfAborted();if(!options.has("--tenant")||(options.has("--profile")?["--origin","--mcp-url","--token-file","--token-env"].some(k=>options.has(k)):options.has("--origin")===options.has("--mcp-url")))throw Error();const transport=options.get("--transport");if(transport&&!["http","mcp"].includes(transport))throw Error();if(!options.has("--profile")&&transport&&transport!==(options.has("--origin")?"http":"mcp"))throw Error();const profile=options.has("--profile")?await(await import("./oauth-RPME2XYB.js")).profileAuthorization(options.get("--profile"),budgets.signal):null;const authorization=profile?.authorization??await readCredential(options,environment);budgets.signal?.throwIfAborted();const profileHttp=profile&&(transport==="http"||!transport&&httpOnly);if(!profileHttp&&(profile||options.has("--mcp-url"))){if(httpOnly)throw Error();const connection=await(await import("./mcp-M2SO3J2H.js")).connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,options.get("--tenant"),budgets);try{budgets.signal?.throwIfAborted();return await action(connection.studio)}finally{await connection.close()}}const baseUrl=profileHttp?await(await import("./http-profile-3VVSWYA5.js")).profileHttpOrigin(options.get("--profile"),profile.resource,budgets.signal):options.get("--origin");budgets.signal?.throwIfAborted();return action(new NativeStudioAgentClient({tenantId:options.get("--tenant"),baseUrl,authorization:()=>authorization,...budgets.maxJsonBytes?{maxJsonBytes:budgets.maxJsonBytes}:{}}))}export{withRemoteClient};
1
+ import{readCredential}from"./chunk-QGK6G6YS.js";import{NativeStudioAgentClient}from"./chunk-2S7FI3HF.js";import{defaultConnection}from"./chunk-27KI24GK.js";async function withRemoteClient(options,environment,httpOnly,action,budgets={}){budgets.signal?.throwIfAborted();await defaultConnection(options,environment,true);budgets.signal?.throwIfAborted();if(!options.has("--tenant")||(options.has("--profile")?["--origin","--mcp-url","--token-file","--token-env"].some(k=>options.has(k)):options.has("--origin")===options.has("--mcp-url")))throw Error();const transport=options.get("--transport");if(transport&&!["http","mcp"].includes(transport))throw Error();if(!options.has("--profile")&&transport&&transport!==(options.has("--origin")?"http":"mcp"))throw Error();const profile=options.has("--profile")?await(await import("./oauth-RPME2XYB.js")).profileAuthorization(options.get("--profile"),budgets.signal):null;const authorization=profile?.authorization??await readCredential(options,environment);budgets.signal?.throwIfAborted();const profileHttp=profile&&(transport==="http"||!transport&&httpOnly);if(!profileHttp&&(profile||options.has("--mcp-url"))){if(httpOnly)throw Error();const connection=await(await import("./mcp-BLSK636Q.js")).connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,options.get("--tenant"),budgets);try{budgets.signal?.throwIfAborted();return await action(connection.studio)}finally{await connection.close()}}const baseUrl=profileHttp?await(await import("./http-profile-3VVSWYA5.js")).profileHttpOrigin(options.get("--profile"),profile.resource,budgets.signal):options.get("--origin");budgets.signal?.throwIfAborted();return action(new NativeStudioAgentClient({tenantId:options.get("--tenant"),baseUrl,authorization:()=>authorization,...budgets.maxJsonBytes?{maxJsonBytes:budgets.maxJsonBytes}:{}}))}export{withRemoteClient};
@@ -1 +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
+ import{runLoginService}from"./chunk-5Y7J2OYL.js";import{ComponentCommandSchema}from"./chunk-ZYXHPTT2.js";import{configureDesktopChannel,desktopRuntimeChannel}from"./chunk-7IVAYDU3.js";import{LocalInstallationManager,socketAbsent}from"./chunk-FFXSXE3G.js";import{DesktopDeviceRecords}from"./chunk-ETK7GYCB.js";import{AgentComponentScopeSchema,AgentComponentStatusSchema,LocalRuntimeStatusSchema}from"./chunk-LDBXGRCQ.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-2S7FI3HF.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{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
+ import{DesktopRuntimeChannelSchema}from"./chunk-WLQMICJN.js";import{InstalledToolPathsSchema}from"./chunk-FFXSXE3G.js";import{AgentComponentScopeSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema}from"./chunk-LDBXGRCQ.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};
@@ -0,0 +1 @@
1
+ import{ComponentCommandSchema,HostComponentRequestSchema}from"./chunk-ZYXHPTT2.js";import"./chunk-WLQMICJN.js";import"./chunk-DMA53YVU.js";import"./chunk-MZWEFYHE.js";import"./chunk-FFXSXE3G.js";import"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import"./chunk-2S7FI3HF.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";export{ComponentCommandSchema,HostComponentRequestSchema};
@@ -1 +1 @@
1
- import{assertComponentConfiguration,componentDevice,observeComponent}from"./chunk-LBK42NHW.js";import{observeLoginHost}from"./chunk-D74NHT4I.js";import"./chunk-QE7O57PQ.js";import{desktopRuntimeChannel}from"./chunk-4PAVWOPA.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import{captureInstalledTools,installationSource,verifyCaptionDirectory}from"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,assertExecutable,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";import{realpath}from"node:fs/promises";import{delimiter,isAbsolute,join}from"node:path";function reason(error,fallback){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:fallback}async function toolPath(name,explicit){const path=process.platform==="win32"?name+".exe":name;const choices=explicit?[explicit]:(process.env.PATH??"").split(delimiter).filter(isAbsolute).slice(0,64).map(root=>join(root,path));for(const candidate of choices){if(!isAbsolute(candidate))continue;try{const actual=await realpath(candidate);await assertExecutable(actual);return actual}catch{}}}async function componentPreflight(home,scope,call,manager,receipts){const observedAt=new Date().toISOString();const platform={os:process.platform,architecture:process.arch,node:process.versions.node};const configuration=manager&&await assertComponentConfiguration(manager,scope);const installation=manager&&(await manager.ledger.current()).value;const last=manager&&(await receipts.snapshot()).latest;const status=(body,exitCode=0)=>({exitCode,output:{protocol:"NVS_HOST_PREFLIGHT_V1",observedAt,kind:call.kind,platform,componentHome:home,installationRevision:installation?.revision??0,installedVersion:installation?.active?.descriptor.version??null,...body}});const blocked=(reasonCode,nextAction,facts2={})=>status({state:"BLOCKED",reasonCode,nextAction,...facts2},4);if(last?.phase==="SENDING")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"observe-original",requestId:last.command.requestId});if(installation?.transition)return blocked("INSTALLATION_RECOVERY_REQUIRED",{surface:"HOST_COMPONENT",action:"reconcile-install",planId:installation.transition.planId,fingerprint:installation.transition.fingerprint,expectedRevision:installation.revision});if(last?.outcome==="UNKNOWN")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"receipt",requestId:last.command.requestId});if(process.platform!=="win32"&&Buffer.byteLength(join(home,"rt","runtime.sock"))>100)return blocked("SOCKET_PATH_TOO_LONG",{surface:"HOST_OWNER",action:"SELECT_PRIVATE_HOME"});const login=await observeLoginHost().then(state=>({state,reasonCode:state==="UNAVAILABLE"?"LOGIN_SERVICE_UNAVAILABLE":null}),error=>({state:"UNAVAILABLE",reasonCode:reason(error,"LOGIN_SERVICE_UNAVAILABLE")}));const host={loginService:login};if(call.source==="SIGNED_CHANNEL"&&call.version==="latest")return blocked("EXACT_RELEASE_VERSION_REQUIRED",{surface:"HOST_OWNER",action:"SELECT_EXACT_RELEASE"},host);const configured=configuration?.catalogueUrl&&configuration.publicKeyFile?{catalogueUrl:configuration.catalogueUrl,publicKeyFile:configuration.publicKeyFile}:null;let trust={...configured??{},rejectedVersions:configuration?.rejectedVersions??[]};const bundled=call.source==="BUNDLED";const fullMedia=call.kind!=="library";const active=installation?.active;const pinned=fullMedia&&active?.toolsConfigPath&&!call.tools?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):null;const activeCaptions=active&&manager?join(manager.ledger.slotPath(active),"dist/captions"):void 0;const captionPath=call.tools?.captionAssetsDirectory??activeCaptions;let localCaptions=false;if(fullMedia&&captionPath){try{await verifyCaptionDirectory(captionPath);localCaptions=true}catch(error){if(call.tools?.captionAssetsDirectory)return blocked(reason(error,"CAPTION_ASSET_UNAVAILABLE"),{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_CAPTION_ASSETS"},host)}}const[ffmpeg,ffprobe]=fullMedia?await Promise.all([toolPath("ffmpeg",call.tools?.ffmpeg??pinned?.ffmpeg.path),toolPath("ffprobe",call.tools?.ffprobe??pinned?.ffprobe.path)]):[void 0,void 0];const missingTools=[!ffmpeg&&"FFMPEG",!ffprobe&&"FFPROBE"].filter(name=>name!==false);let release;try{if(call.channel&&(!bundled||fullMedia&&(!localCaptions||missingTools.length))){const{value}=desktopRuntimeChannel({...call.channel,protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1"});if(configured&&(configured.catalogueUrl!==value.catalogueUrl||(await read(configured.publicKeyFile,16384)).toString().trim()!==value.publicKey.trim()))return blocked("DEPENDENCY_CHANNEL_CHANGED",{surface:"HOST_OWNER",action:"CHECK_CONFIGURED_RELEASE_CHANNEL"},host);if(!configured)trust={...trust,catalogueUrl:value.catalogueUrl,publicKey:value.publicKey}}const dependencyChannel=fullMedia&&(!localCaptions||missingTools.length>0)&&!!trust.catalogueUrl;release=(await installationSource(trust,call.version,bundled,dependencyChannel)).release}catch(error){return blocked(reason(error,"RELEASE_OBSERVATION_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_RELEASE_SOURCE"},host)}const facts={...host,release:{version:release.descriptor.version,source:call.source,node:release.descriptor.node,sha512:release.package.sha512}};let tools;if(fullMedia){const explicitMissing=call.tools?.ffmpeg&&!ffmpeg||call.tools?.ffprobe&&!ffprobe;const mediaSource=ffmpeg&&ffprobe?"INSTALLED":!explicitMissing&&release.tools?"SIGNED_CHANNEL":"MISSING";const canReuseCaptions=localCaptions&&(!call.tools?.captionAssetsDirectory||mediaSource==="INSTALLED");const captionSource=canReuseCaptions?"INSTALLED":release.resources?.captions?"SIGNED_CHANNEL":"MISSING";const dependencies={mediaSource,captionSource,missingTools:mediaSource==="MISSING"?missingTools:[]};if(mediaSource==="MISSING"||captionSource==="MISSING")return blocked("MEDIA_DEPENDENCIES_REQUIRED",{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_DEPENDENCIES"},{...facts,dependencies});try{tools=ffmpeg&&ffprobe?await captureInstalledTools({mode:"INSTALLED",ffmpeg,ffprobe,...call.tools?.captionAssetsDirectory&&{captionAssetsDirectory:captionPath}}):{mode:"MANAGED"}}catch(error){return blocked(reason(error,"TOOL_IDENTITY_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies})}if(pinned&&(tools.mode!=="INSTALLED"||tools.ffmpeg.digest!==pinned.ffmpeg.digest||tools.ffprobe.digest!==pinned.ffprobe.digest))return blocked("INSTALLED_TOOL_IDENTITY_CHANGED",{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies});Object.assign(facts,{dependencies})}if(!manager||!configured&&!!trust.catalogueUrl)return status({...facts,state:"INITIALIZATION_REQUIRED",reasonCode:manager?"DEPENDENCY_CHANNEL_CONFIGURATION_REQUIRED":"COMPONENT_NOT_INITIALIZED",nextAction:{surface:"HOST_COMPONENT",call:{action:"initialize"},includeOriginalChannel:!!trust.catalogueUrl}});if(!active||active.descriptor.version!==release.descriptor.version||fullMedia&&(!active.toolsConfigPath||!localCaptions||!!call.tools))return status({...facts,state:"INSTALL_PLAN_REQUIRED",reasonCode:"PIN_CURRENT_INSTALLATION_PLAN",nextAction:{surface:"HOST_COMPONENT",call:{action:"install-plan",version:release.descriptor.version,source:call.source,...tools&&{tools}}}});const device=await componentDevice(home,scope);const component=await observeComponent(home,scope,manager,receipts);if(device&&component.liveness.state==="STOPPED")return status({...facts,component,state:"START_REQUIRED",reasonCode:"OWNED_RUNTIME_STOPPED",nextAction:{surface:"HOST_COMPONENT",action:"start",expectedRevision:component.installationRevision}});return status({...facts,component,state:device?"VERIFY_DEVICE":"ENROLLMENT_REQUIRED",reasonCode:device?"CHECK_DEVICE_HEARTBEAT_AND_TASK":"INSPECT_ORIGINAL_ENROLLMENT",nextAction:device?{surface:"MCP",tool:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:"device_status",arguments:{tenantId:scope.tenantId,deviceId:device.deviceId}}}:{surface:"HOST_ENROLLMENT",call:{action:"inspect"}}})}export{componentPreflight};
1
+ import{assertComponentConfiguration,componentDevice,observeComponent}from"./chunk-ZMJYBUS3.js";import{observeLoginHost}from"./chunk-5Y7J2OYL.js";import"./chunk-ZYXHPTT2.js";import{desktopRuntimeChannel}from"./chunk-7IVAYDU3.js";import"./chunk-WLQMICJN.js";import"./chunk-DMA53YVU.js";import"./chunk-MZWEFYHE.js";import{captureInstalledTools,installationSource,verifyCaptionDirectory}from"./chunk-FFXSXE3G.js";import"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import{LocalToolSelectionSchema}from"./chunk-LDBXGRCQ.js";import"./chunk-2S7FI3HF.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,assertExecutable,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";import{realpath}from"node:fs/promises";import{delimiter,isAbsolute,join}from"node:path";function reason(error,fallback){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:fallback}async function toolPath(name,explicit){const path=process.platform==="win32"?name+".exe":name;const choices=explicit?[explicit]:(process.env.PATH??"").split(delimiter).filter(isAbsolute).slice(0,64).map(root=>join(root,path));for(const candidate of choices){if(!isAbsolute(candidate))continue;try{const actual=await realpath(candidate);await assertExecutable(actual);return actual}catch{}}}async function componentPreflight(home,scope,call,manager,receipts){const observedAt=new Date().toISOString();const platform={os:process.platform,architecture:process.arch,node:process.versions.node};const configuration=manager&&await assertComponentConfiguration(manager,scope);const installation=manager&&(await manager.ledger.current()).value;const last=manager&&(await receipts.snapshot()).latest;const status=(body,exitCode=0)=>({exitCode,output:{protocol:"NVS_HOST_PREFLIGHT_V1",observedAt,kind:call.kind,platform,componentHome:home,installationRevision:installation?.revision??0,installedVersion:installation?.active?.descriptor.version??null,...body}});const blocked=(reasonCode,nextAction,facts2={})=>status({state:"BLOCKED",reasonCode,nextAction,...facts2},4);if(last?.phase==="SENDING")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"observe-original",requestId:last.command.requestId});if(installation?.transition)return blocked("INSTALLATION_RECOVERY_REQUIRED",{surface:"HOST_COMPONENT",action:"reconcile-install",planId:installation.transition.planId,fingerprint:installation.transition.fingerprint,expectedRevision:installation.revision});if(last?.outcome==="UNKNOWN")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"receipt",requestId:last.command.requestId});if(process.platform!=="win32"&&Buffer.byteLength(join(home,"rt","runtime.sock"))>100)return blocked("SOCKET_PATH_TOO_LONG",{surface:"HOST_OWNER",action:"SELECT_PRIVATE_HOME"});const login=await observeLoginHost().then(state=>({state,reasonCode:state==="UNAVAILABLE"?"LOGIN_SERVICE_UNAVAILABLE":null}),error=>({state:"UNAVAILABLE",reasonCode:reason(error,"LOGIN_SERVICE_UNAVAILABLE")}));const host={loginService:login};if(call.source==="SIGNED_CHANNEL"&&call.version==="latest")return blocked("EXACT_RELEASE_VERSION_REQUIRED",{surface:"HOST_OWNER",action:"SELECT_EXACT_RELEASE"},host);const configured=configuration?.catalogueUrl&&configuration.publicKeyFile?{catalogueUrl:configuration.catalogueUrl,publicKeyFile:configuration.publicKeyFile}:null;let trust={...configured??{},rejectedVersions:configuration?.rejectedVersions??[]};const bundled=call.source==="BUNDLED";const fullMedia=call.kind!=="library";const active=installation?.active;const pinned=fullMedia&&active?.toolsConfigPath&&!call.tools?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):null;const activeCaptions=active&&manager?join(manager.ledger.slotPath(active),"dist/captions"):void 0;const captionPath=call.tools?.captionAssetsDirectory??activeCaptions;let localCaptions=false;if(fullMedia&&captionPath){try{await verifyCaptionDirectory(captionPath);localCaptions=true}catch(error){if(call.tools?.captionAssetsDirectory)return blocked(reason(error,"CAPTION_ASSET_UNAVAILABLE"),{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_CAPTION_ASSETS"},host)}}const[ffmpeg,ffprobe]=fullMedia?await Promise.all([toolPath("ffmpeg",call.tools?.ffmpeg??pinned?.ffmpeg.path),toolPath("ffprobe",call.tools?.ffprobe??pinned?.ffprobe.path)]):[void 0,void 0];const missingTools=[!ffmpeg&&"FFMPEG",!ffprobe&&"FFPROBE"].filter(name=>name!==false);let release;try{if(call.channel&&(!bundled||fullMedia&&(!localCaptions||missingTools.length))){const{value}=desktopRuntimeChannel({...call.channel,protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1"});if(configured&&(configured.catalogueUrl!==value.catalogueUrl||(await read(configured.publicKeyFile,16384)).toString().trim()!==value.publicKey.trim()))return blocked("DEPENDENCY_CHANNEL_CHANGED",{surface:"HOST_OWNER",action:"CHECK_CONFIGURED_RELEASE_CHANNEL"},host);if(!configured)trust={...trust,catalogueUrl:value.catalogueUrl,publicKey:value.publicKey}}const dependencyChannel=fullMedia&&(!localCaptions||missingTools.length>0)&&!!trust.catalogueUrl;release=(await installationSource(trust,call.version,bundled,dependencyChannel)).release}catch(error){return blocked(reason(error,"RELEASE_OBSERVATION_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_RELEASE_SOURCE"},host)}const facts={...host,release:{version:release.descriptor.version,source:call.source,node:release.descriptor.node,sha512:release.package.sha512}};let tools;if(fullMedia){const explicitMissing=call.tools?.ffmpeg&&!ffmpeg||call.tools?.ffprobe&&!ffprobe;const mediaSource=ffmpeg&&ffprobe?"INSTALLED":!explicitMissing&&release.tools?"SIGNED_CHANNEL":"MISSING";const canReuseCaptions=localCaptions&&(!call.tools?.captionAssetsDirectory||mediaSource==="INSTALLED");const captionSource=canReuseCaptions?"INSTALLED":release.resources?.captions?"SIGNED_CHANNEL":"MISSING";const dependencies={mediaSource,captionSource,missingTools:mediaSource==="MISSING"?missingTools:[]};if(mediaSource==="MISSING"||captionSource==="MISSING")return blocked("MEDIA_DEPENDENCIES_REQUIRED",{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_DEPENDENCIES"},{...facts,dependencies});try{tools=ffmpeg&&ffprobe?await captureInstalledTools({mode:"INSTALLED",ffmpeg,ffprobe,...call.tools?.captionAssetsDirectory&&{captionAssetsDirectory:captionPath}}):{mode:"MANAGED"}}catch(error){return blocked(reason(error,"TOOL_IDENTITY_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies})}if(pinned&&(tools.mode!=="INSTALLED"||tools.ffmpeg.digest!==pinned.ffmpeg.digest||tools.ffprobe.digest!==pinned.ffprobe.digest))return blocked("INSTALLED_TOOL_IDENTITY_CHANGED",{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies});Object.assign(facts,{dependencies})}if(!manager||!configured&&!!trust.catalogueUrl)return status({...facts,state:"INITIALIZATION_REQUIRED",reasonCode:manager?"DEPENDENCY_CHANNEL_CONFIGURATION_REQUIRED":"COMPONENT_NOT_INITIALIZED",nextAction:{surface:"HOST_COMPONENT",call:{action:"initialize"},includeOriginalChannel:!!trust.catalogueUrl}});if(!active||active.descriptor.version!==release.descriptor.version||fullMedia&&(!active.toolsConfigPath||!localCaptions||!!call.tools))return status({...facts,state:"INSTALL_PLAN_REQUIRED",reasonCode:"PIN_CURRENT_INSTALLATION_PLAN",nextAction:{surface:"HOST_COMPONENT",call:{action:"install-plan",version:release.descriptor.version,source:call.source,...tools&&{tools}}}});const device=await componentDevice(home,scope);const component=await observeComponent(home,scope,manager,receipts);if(device&&component.liveness.state==="STOPPED")return status({...facts,component,state:"START_REQUIRED",reasonCode:"OWNED_RUNTIME_STOPPED",nextAction:{surface:"HOST_COMPONENT",action:"start",expectedRevision:component.installationRevision}});return status({...facts,component,state:device?"VERIFY_DEVICE":"ENROLLMENT_REQUIRED",reasonCode:device?"CHECK_DEVICE_HEARTBEAT_AND_TASK":"INSPECT_ORIGINAL_ENROLLMENT",nextAction:device?{surface:"MCP",tool:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:"device_status",arguments:{tenantId:scope.tenantId,deviceId:device.deviceId}}}:{surface:"HOST_ENROLLMENT",call:{action:"inspect"}}})}export{componentPreflight};
@@ -1 +1 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import"./chunk-APNZQZFB.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import{CapabilityVersionSchema}from"./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","--capability-version"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}if(!flags.has("--input"))throw Error();const capabilityVersion=CapabilityVersionSchema.optional().parse(flags.get("--capability-version"));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 command=input;const output=capabilityVersion?await connection.studio.call(key,command,{capabilityVersion}):await connection.studio.call(key,command);return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceManagementCommand};
1
+ import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import"./chunk-2S7FI3HF.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import{CapabilityVersionSchema}from"./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","--capability-version"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}if(!flags.has("--input"))throw Error();const capabilityVersion=CapabilityVersionSchema.optional().parse(flags.get("--capability-version"));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 command=input;const output=capabilityVersion?await connection.studio.call(key,command,{capabilityVersion}):await connection.studio.call(key,command);return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceManagementCommand};
@@ -1 +1 @@
1
- import{callerOriginMatches,workspaceCaller}from"./chunk-NG4BDFEY.js";import{renderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import{LocalInstallationManager,ownerClient,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema,LocalDeviceTransportConfigurationSchema}from"./chunk-APNZQZFB.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var transportSchema=LocalDeviceTransportConfigurationSchema.safeExtend({tools:LocalToolSelectionSchema.optional()});var nextSteps={ACCOUNT_LOGIN_REQUIRED:"nvs login --server <Studio-origin>",TENANT_CONNECTION_REQUIRED:"nvs connect --mcp-url <tenant-connection-url>",ACCOUNT_REVOCATION_UNCONFIRMED:"nvs logout",PROJECT_SELECTION_REQUIRED:"Run nvs workspaces, nvs projects, then nvs project --id <project-id>",INSTALL_REQUIRED:"Configure the Runtime, check signed releases, then prepare nvs local install --version <exact>",INSTALLATION_RECOVERY_REQUIRED:"Inspect nvs local status, then reconcile the original installation plan",CONFIGURATION_REQUIRED:"nvs local configure --input <private-json>",DEVICE_ENROLLMENT_REQUIRED:"nvs local cloud --action enroll with the approved owner input",DEVICE_RECEIPT_REQUIRED:"nvs local cloud --action receipt with the original management command",PROJECT_CONNECTION_REQUIRED:"nvs connect",DEVICE_AUTHORITY_UNCONFIRMED:"Check the current workspace membership, device proof and revocation",DEVICE_CONNECTION_REQUIRED:"nvs local connect --input <private-device-config>",DEVICE_CONNECTION_RECOVERY_REQUIRED:"Inspect the original device connection and Runtime status",DEVICE_OFFLINE:"Inspect nvs local status, then start the configured Runtime if stopped",DEVICE_BUSY:"Wait for available capacity, then recheck this device",RUNTIME_QUALIFICATION_REQUIRED:"Check the signed Runtime slot and the approved tools",DEVICE_CAPABILITY_UNCONFIRMED:"Check the configured action, tool or provider prerequisites and the current heartbeat",PROJECT_QUERY_UNAVAILABLE:"Check the selected Project connection, then retry this read"};async function qualified(kind,root,slot,validator){if(kind==="library")return true;if(kind==="preview"||kind==="final")return validator?probeTenantMediaValidation(root,slot):true;if(!await probeTenantMediaProcessing(root,slot))return false;switch(kind){case"REFERENCE_PREVIEW":return probeReferenceThumbnail(root,slot);case"LOCAL_MEDIA_INSPECT":case"LOCAL_MEDIA_PUBLISH":return probeLocalLibrary(root,slot);case"COMPOSITION_RENDER":return probeTenantComposition(root,slot);case"SPEECH_SYNTHESIZE":return probeTenantSpeech(root,slot);case"TRANSCRIBE_AUDIO":return probeTenantTranscription(root,slot);case"KEYFRAME_GENERATE":return probeTenantQwenGeneration(root,slot,"keyframe");case"VIDEO_GENERATE":return probeTenantQwenGeneration(root,slot,"video");case"SPEECH_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"speech");case"TRANSCRIBE_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"asr");default:return true}}async function devicePreflight(raw,env,explicitProject){const kind=DeviceDiscoveryInputSchema.shape.kind.parse(raw);const context={};const blocked=reason=>({exitCode:4,output:{semanticStatus:"BLOCKED",kind,...context,error:{code:reason,outcome:"NO_WRITE"},nextStep:nextSteps[reason]}});let caller;try{caller=await workspaceCaller(env)}catch(error){if(error.code==="ENOENT")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error instanceof NativeStudioSdkError){if(error.code==="TENANT_CONNECTION_REQUIRED")return blocked("TENANT_CONNECTION_REQUIRED");if(error.code==="ACCOUNT_LOGIN_REQUIRED")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error.code==="ACCOUNT_LOGOUT_OUTCOME_UNKNOWN")return blocked("ACCOUNT_REVOCATION_UNCONFIRMED");if(error.code==="PROJECT_SELECTION_REQUIRED")return blocked("PROJECT_SELECTION_REQUIRED")}throw error}if(!caller)return blocked("ACCOUNT_LOGIN_REQUIRED");const{home,tenantId,principalId,serverOrigin}=caller;const projectId=explicitProject?z.uuid().parse(explicitProject):void 0;Object.assign(context,{tenantId,projectId});const manager=await LocalInstallationManager.openExisting(home);if(!manager)return blocked("INSTALL_REQUIRED");const{active,transition}=(await manager.ledger.current()).value;if(transition)return blocked("INSTALLATION_RECOVERY_REQUIRED");if(!active)return blocked("INSTALL_REQUIRED");const slotRoot=manager.ledger.slotPath(active);await verifySlot(slotRoot,active);const records=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});const pending=records?.pending?.command;if(records?.pending?.phase==="SENDING"&&(pending?.kind==="ENROLL"||pending?.kind==="REVOKE_DEVICE"))return blocked("DEVICE_RECEIPT_REQUIRED");if(records?.connection?.phase==="CONNECTING")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const config=await manager.configuration().catch(error=>{if(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED")return null;throw error});if(!config)return blocked("CONFIGURATION_REQUIRED");let transport=null;try{if(config.cloudConfigFile)transport=transportSchema.parse(JSON.parse((await read(config.cloudConfigFile,32768)).toString()))}catch(error){if(error.code==="ENOENT")return blocked("DEVICE_CONNECTION_REQUIRED");if(error instanceof SyntaxError||error instanceof z.ZodError)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");throw error}const endpoint=transport?new URL(transport.endpoint):null;const current=endpoint&&await callerOriginMatches(endpoint.origin,caller)&&!endpoint.username&&!endpoint.password&&transport?.tenantId===tenantId?transport:null;const deviceId=records?.device?.deviceId??current?.deviceId;if(!deviceId)return blocked("DEVICE_ENROLLMENT_REQUIRED");context.deviceId=deviceId;const configured=current?.deviceId===deviceId&&current.tenantId===tenantId;if(!configured||!current)return blocked("DEVICE_CONNECTION_REQUIRED");if(!projectId){const local=await ownerClient(config.stateDirectory);const status=await local.status(void 0,true).catch(()=>null);if(!status)return blocked("DEVICE_OFFLINE");if(status.deviceAuthority?.tenantId!==tenantId||status.deviceAuthority.deviceId!==deviceId)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(status.state==="DRAINING")return blocked("DEVICE_BUSY");if(status.state==="RECOVERY_REQUIRED")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const capabilities=status.deviceCapabilities;if(!capabilities)return blocked("DEVICE_CAPABILITY_UNCONFIRMED");if(capabilities.deviceRevision!==current.deviceRevision)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(kind==="preview"||kind==="final"){const doctor=await local.doctor().catch(()=>null);if(!doctor?.nativeExecutionReady||!doctor.executionProfiles?.includes("STUDIO_MEDIA_V2"))return blocked("RUNTIME_QUALIFICATION_REQUIRED");if(current.tenantMediaValidation&&!capabilities.tenantMediaValidation)return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(kind!=="preview"&&kind!=="final"&&kind!=="library"){const configuredKinds=current.processorCapabilities??[];if(!current.tenantMediaProcessing||!configuredKinds.includes(kind)||!capabilities.tenantMediaProcessing||!capabilities.processorCapabilities.includes(kind))return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(!await qualified(kind,slotRoot,active,!!current?.tenantMediaValidation))return blocked("RUNTIME_QUALIFICATION_REQUIRED");await caller.assertCurrent();return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,deviceId,availability:status.state==="EXECUTING"?"BUSY":"AVAILABLE"}}}const conn=await renderConnection(env,void 0,false,projectId).catch(error=>{if(error instanceof NativeStudioSdkError&&error.code==="AUTHORIZATION_REQUIRED")return null;throw error});if(!conn)return blocked("PROJECT_CONNECTION_REQUIRED");try{if(conn.scope.tenantId!==tenantId||conn.scope.projectId!==projectId||(caller.resource?conn.scope.resource!==caller.resource:new URL(conn.scope.resource).origin!==serverOrigin))return blocked("PROJECT_CONNECTION_REQUIRED");const page=await conn.studio.deviceRenders.list({kind,projectId,deviceId}).catch(error=>{if(error instanceof NativeStudioSdkError)return null;throw error});await caller.assertCurrent();if(!page||page.truncated)return blocked("PROJECT_QUERY_UNAVAILABLE");const candidate=page.items[0];if(!candidate)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(!configured)return blocked("DEVICE_CONNECTION_REQUIRED");if(candidate.availability==="OFFLINE")return blocked("DEVICE_OFFLINE");if(candidate.availability==="BUSY")return blocked("DEVICE_BUSY");if(candidate.availability==="UNQUALIFIED")return blocked(await qualified(kind,slotRoot,active,!!page.validationMode)?"DEVICE_CAPABILITY_UNCONFIRMED":"RUNTIME_QUALIFICATION_REQUIRED");return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,projectId,deviceId,availability:candidate.availability,validationMode:page.validationMode}}}finally{await conn.close().catch(()=>{})}}export{devicePreflight};
1
+ import{callerOriginMatches,workspaceCaller}from"./chunk-X5MVC46N.js";import{renderConnection}from"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import{LocalInstallationManager,ownerClient,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-FFXSXE3G.js";import{DesktopDeviceRecords}from"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import{LocalToolSelectionSchema}from"./chunk-LDBXGRCQ.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema,LocalDeviceTransportConfigurationSchema}from"./chunk-2S7FI3HF.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var transportSchema=LocalDeviceTransportConfigurationSchema.safeExtend({tools:LocalToolSelectionSchema.optional()});var nextSteps={ACCOUNT_LOGIN_REQUIRED:"nvs login --server <Studio-origin>",TENANT_CONNECTION_REQUIRED:"nvs connect --mcp-url <tenant-connection-url>",ACCOUNT_REVOCATION_UNCONFIRMED:"nvs logout",PROJECT_SELECTION_REQUIRED:"Run nvs workspaces, nvs projects, then nvs project --id <project-id>",INSTALL_REQUIRED:"Configure the Runtime, check signed releases, then prepare nvs local install --version <exact>",INSTALLATION_RECOVERY_REQUIRED:"Inspect nvs local status, then reconcile the original installation plan",CONFIGURATION_REQUIRED:"nvs local configure --input <private-json>",DEVICE_ENROLLMENT_REQUIRED:"nvs local cloud --action enroll with the approved owner input",DEVICE_RECEIPT_REQUIRED:"nvs local cloud --action receipt with the original management command",PROJECT_CONNECTION_REQUIRED:"nvs connect",DEVICE_AUTHORITY_UNCONFIRMED:"Check the current workspace membership, device proof and revocation",DEVICE_CONNECTION_REQUIRED:"nvs local connect --input <private-device-config>",DEVICE_CONNECTION_RECOVERY_REQUIRED:"Inspect the original device connection and Runtime status",DEVICE_OFFLINE:"Inspect nvs local status, then start the configured Runtime if stopped",DEVICE_BUSY:"Wait for available capacity, then recheck this device",RUNTIME_QUALIFICATION_REQUIRED:"Check the signed Runtime slot and the approved tools",DEVICE_CAPABILITY_UNCONFIRMED:"Check the configured action, tool or provider prerequisites and the current heartbeat",PROJECT_QUERY_UNAVAILABLE:"Check the selected Project connection, then retry this read"};async function qualified(kind,root,slot,validator){if(kind==="library")return true;if(kind==="preview"||kind==="final")return validator?probeTenantMediaValidation(root,slot):true;if(!await probeTenantMediaProcessing(root,slot))return false;switch(kind){case"REFERENCE_PREVIEW":return probeReferenceThumbnail(root,slot);case"LOCAL_MEDIA_INSPECT":case"LOCAL_MEDIA_PUBLISH":return probeLocalLibrary(root,slot);case"COMPOSITION_RENDER":return probeTenantComposition(root,slot);case"SPEECH_SYNTHESIZE":return probeTenantSpeech(root,slot);case"TRANSCRIBE_AUDIO":return probeTenantTranscription(root,slot);case"KEYFRAME_GENERATE":return probeTenantQwenGeneration(root,slot,"keyframe");case"VIDEO_GENERATE":return probeTenantQwenGeneration(root,slot,"video");case"SPEECH_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"speech");case"TRANSCRIBE_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"asr");default:return true}}async function devicePreflight(raw,env,explicitProject){const kind=DeviceDiscoveryInputSchema.shape.kind.parse(raw);const context={};const blocked=reason=>({exitCode:4,output:{semanticStatus:"BLOCKED",kind,...context,error:{code:reason,outcome:"NO_WRITE"},nextStep:nextSteps[reason]}});let caller;try{caller=await workspaceCaller(env)}catch(error){if(error.code==="ENOENT")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error instanceof NativeStudioSdkError){if(error.code==="TENANT_CONNECTION_REQUIRED")return blocked("TENANT_CONNECTION_REQUIRED");if(error.code==="ACCOUNT_LOGIN_REQUIRED")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error.code==="ACCOUNT_LOGOUT_OUTCOME_UNKNOWN")return blocked("ACCOUNT_REVOCATION_UNCONFIRMED");if(error.code==="PROJECT_SELECTION_REQUIRED")return blocked("PROJECT_SELECTION_REQUIRED")}throw error}if(!caller)return blocked("ACCOUNT_LOGIN_REQUIRED");const{home,tenantId,principalId,serverOrigin}=caller;const projectId=explicitProject?z.uuid().parse(explicitProject):void 0;Object.assign(context,{tenantId,projectId});const manager=await LocalInstallationManager.openExisting(home);if(!manager)return blocked("INSTALL_REQUIRED");const{active,transition}=(await manager.ledger.current()).value;if(transition)return blocked("INSTALLATION_RECOVERY_REQUIRED");if(!active)return blocked("INSTALL_REQUIRED");const slotRoot=manager.ledger.slotPath(active);await verifySlot(slotRoot,active);const records=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});const pending=records?.pending?.command;if(records?.pending?.phase==="SENDING"&&(pending?.kind==="ENROLL"||pending?.kind==="REVOKE_DEVICE"))return blocked("DEVICE_RECEIPT_REQUIRED");if(records?.connection?.phase==="CONNECTING")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const config=await manager.configuration().catch(error=>{if(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED")return null;throw error});if(!config)return blocked("CONFIGURATION_REQUIRED");let transport=null;try{if(config.cloudConfigFile)transport=transportSchema.parse(JSON.parse((await read(config.cloudConfigFile,32768)).toString()))}catch(error){if(error.code==="ENOENT")return blocked("DEVICE_CONNECTION_REQUIRED");if(error instanceof SyntaxError||error instanceof z.ZodError)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");throw error}const endpoint=transport?new URL(transport.endpoint):null;const current=endpoint&&await callerOriginMatches(endpoint.origin,caller)&&!endpoint.username&&!endpoint.password&&transport?.tenantId===tenantId?transport:null;const deviceId=records?.device?.deviceId??current?.deviceId;if(!deviceId)return blocked("DEVICE_ENROLLMENT_REQUIRED");context.deviceId=deviceId;const configured=current?.deviceId===deviceId&&current.tenantId===tenantId;if(!configured||!current)return blocked("DEVICE_CONNECTION_REQUIRED");if(!projectId){const local=await ownerClient(config.stateDirectory);const status=await local.status(void 0,true).catch(()=>null);if(!status)return blocked("DEVICE_OFFLINE");if(status.deviceAuthority?.tenantId!==tenantId||status.deviceAuthority.deviceId!==deviceId)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(status.state==="DRAINING")return blocked("DEVICE_BUSY");if(status.state==="RECOVERY_REQUIRED")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const capabilities=status.deviceCapabilities;if(!capabilities)return blocked("DEVICE_CAPABILITY_UNCONFIRMED");if(capabilities.deviceRevision!==current.deviceRevision)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(kind==="preview"||kind==="final"){const doctor=await local.doctor().catch(()=>null);if(!doctor?.nativeExecutionReady||!doctor.executionProfiles?.includes("STUDIO_MEDIA_V2"))return blocked("RUNTIME_QUALIFICATION_REQUIRED");if(current.tenantMediaValidation&&!capabilities.tenantMediaValidation)return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(kind!=="preview"&&kind!=="final"&&kind!=="library"){const configuredKinds=current.processorCapabilities??[];if(!current.tenantMediaProcessing||!configuredKinds.includes(kind)||!capabilities.tenantMediaProcessing||!capabilities.processorCapabilities.includes(kind))return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(!await qualified(kind,slotRoot,active,!!current?.tenantMediaValidation))return blocked("RUNTIME_QUALIFICATION_REQUIRED");await caller.assertCurrent();return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,deviceId,availability:status.state==="EXECUTING"?"BUSY":"AVAILABLE"}}}const conn=await renderConnection(env,void 0,false,projectId).catch(error=>{if(error instanceof NativeStudioSdkError&&error.code==="AUTHORIZATION_REQUIRED")return null;throw error});if(!conn)return blocked("PROJECT_CONNECTION_REQUIRED");try{if(conn.scope.tenantId!==tenantId||conn.scope.projectId!==projectId||(caller.resource?conn.scope.resource!==caller.resource:new URL(conn.scope.resource).origin!==serverOrigin))return blocked("PROJECT_CONNECTION_REQUIRED");const page=await conn.studio.deviceRenders.list({kind,projectId,deviceId}).catch(error=>{if(error instanceof NativeStudioSdkError)return null;throw error});await caller.assertCurrent();if(!page||page.truncated)return blocked("PROJECT_QUERY_UNAVAILABLE");const candidate=page.items[0];if(!candidate)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(!configured)return blocked("DEVICE_CONNECTION_REQUIRED");if(candidate.availability==="OFFLINE")return blocked("DEVICE_OFFLINE");if(candidate.availability==="BUSY")return blocked("DEVICE_BUSY");if(candidate.availability==="UNQUALIFIED")return blocked(await qualified(kind,slotRoot,active,!!page.validationMode)?"DEVICE_CAPABILITY_UNCONFIRMED":"RUNTIME_QUALIFICATION_REQUIRED");return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,projectId,deviceId,availability:candidate.availability,validationMode:page.validationMode}}}finally{await conn.close().catch(()=>{})}}export{devicePreflight};
@@ -1 +1 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{WorkspaceDeviceListInputSchema}from"./chunk-APNZQZFB.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"./chunk-TT7IA5HB.js";var query=WorkspaceDeviceListInputSchema.omit({tenantId:true});async function deviceInventoryCommand(args,env){const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--device","--after","--limit","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}const input=query.parse({...flags.has("--device")&&{deviceId:flags.get("--device")},...flags.has("--after")&&{after:flags.get("--after")},...flags.has("--limit")&&{limit:Number(flags.get("--limit"))}});await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(key=>flags.has(key)))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 authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const output=await connection.studio.call("workspace.devices.list",{...input,tenantId:scope.tenantId});return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceInventoryCommand};
1
+ import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{WorkspaceDeviceListInputSchema}from"./chunk-2S7FI3HF.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"./chunk-TT7IA5HB.js";var query=WorkspaceDeviceListInputSchema.omit({tenantId:true});async function deviceInventoryCommand(args,env){const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--device","--after","--limit","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}const input=query.parse({...flags.has("--device")&&{deviceId:flags.get("--device")},...flags.has("--after")&&{after:flags.get("--after")},...flags.has("--limit")&&{limit:Number(flags.get("--limit"))}});await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(key=>flags.has(key)))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 authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const output=await connection.studio.call("workspace.devices.list",{...input,tenantId:scope.tenantId});return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceInventoryCommand};
@@ -1 +1 @@
1
- import{callerRenderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-APNZQZFB.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var query=DeviceDiscoveryInputSchema.pick({kind:true,deviceId:true});async function devicesCommand(argv,env,stdin=process.stdin){const[action,...args]=argv;if(action==="inventory")return(await import("./devices-inventory-BZF53UAU.js")).deviceInventoryCommand(args,env);if(action!=="list")return(await import("./device-management-TLRUMZL5.js")).deviceManagementCommand(action,args,env,stdin);const flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--kind","--device","--project","--mcp-url","--token-file"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}const input=query.parse({kind:flags.get("--kind"),...flags.has("--device")&&{deviceId:flags.get("--device")}});const conn=await callerRenderConnection(env,flags,false);try{const output=await conn.studio.deviceRenders.list({...input,projectId:conn.scope.projectId});return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{devicesCommand};
1
+ import{callerRenderConnection}from"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-2S7FI3HF.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var query=DeviceDiscoveryInputSchema.pick({kind:true,deviceId:true});async function devicesCommand(argv,env,stdin=process.stdin){const[action,...args]=argv;if(action==="inventory")return(await import("./devices-inventory-E6ZLXCVR.js")).deviceInventoryCommand(args,env);if(action!=="list")return(await import("./device-management-JPS4HG34.js")).deviceManagementCommand(action,args,env,stdin);const flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--kind","--device","--project","--mcp-url","--token-file"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}const input=query.parse({kind:flags.get("--kind"),...flags.has("--device")&&{deviceId:flags.get("--device")}});const conn=await callerRenderConnection(env,flags,false);try{const output=await conn.studio.deviceRenders.list({...input,projectId:conn.scope.projectId});return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{devicesCommand};
@@ -1 +1 @@
1
- import{ComponentReceipts,componentHome,initializeComponent,observeComponent,observeLoginService,withComponentLock}from"./chunk-LBK42NHW.js";import{runLoginService}from"./chunk-D74NHT4I.js";import"./chunk-QE7O57PQ.js";import"./chunk-4PAVWOPA.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import{InstalledToolPathsSchema,LocalInstallationManager,captureInstalledTools}from"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,fail}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";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(call.action==="preflight")return(await import("./component-preflight-WECLCZLF.js")).componentPreflight(home,scope,call,manager,receipts);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
+ import{ComponentReceipts,componentHome,initializeComponent,observeComponent,observeLoginService,withComponentLock}from"./chunk-ZMJYBUS3.js";import{runLoginService}from"./chunk-5Y7J2OYL.js";import"./chunk-ZYXHPTT2.js";import"./chunk-7IVAYDU3.js";import"./chunk-WLQMICJN.js";import"./chunk-DMA53YVU.js";import"./chunk-MZWEFYHE.js";import{InstalledToolPathsSchema,LocalInstallationManager,captureInstalledTools}from"./chunk-FFXSXE3G.js";import"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import"./chunk-2S7FI3HF.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,fail}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";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(call.action==="preflight")return(await import("./component-preflight-6OWDQAZT.js")).componentPreflight(home,scope,call,manager,receipts);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 +1 @@
1
- import{HostComponentRequestSchema}from"./chunk-QE7O57PQ.js";import{HostEnrollmentRequestSchema}from"./chunk-K35CWLDH.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-ROGOASYF.js";import"./chunk-HBDPYWMI.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.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. Use host component help preflight for the read-only host check for library, preview or final. Prepare enrollment with authority OAUTH_AGENT and send its invoke on the same MCP. Pass the ticket by private input and read the original lookup after an interrupted reply."}}}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
+ import{HostComponentRequestSchema}from"./chunk-ZYXHPTT2.js";import{HostEnrollmentRequestSchema}from"./chunk-LTNJ45JP.js";import"./chunk-WLQMICJN.js";import"./chunk-DMA53YVU.js";import"./chunk-PQCA4X5H.js";import"./chunk-H4FH6STZ.js";import"./chunk-MZWEFYHE.js";import"./chunk-FFXSXE3G.js";import"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import"./chunk-2S7FI3HF.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. Use host component help preflight for the read-only host check for library, preview or final. Prepare enrollment with authority OAUTH_AGENT and send its invoke on the same MCP. Pass the ticket by private input and read the original lookup after an interrupted reply."}}}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 +1 @@
1
- import{HostEnrollmentRequestSchema,runHostEnrollment}from"./chunk-K35CWLDH.js";import{runDesktopDeviceRequest}from"./chunk-ROGOASYF.js";import"./chunk-HBDPYWMI.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import{DesktopDeviceRequestSchema}from"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-APNZQZFB.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-7BGYR4ET.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-7BGYR4ET.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-KXK7WIUI.js");const request2=HostComponentRequestSchema.parse(raw);entered=true;mutation=!["status","preflight","receipt","service-plan"].includes(request2.call.action);return await(await import("./host-component-Q5IHRHRI.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:!uncertain&&["INVALID_INPUT","REVISION_CONFLICT"].includes(code)?code:"BLOCKED",error:{code,outcome:uncertain?"UNKNOWN":"NO_WRITE"}}}}}export{runHostCli};
1
+ import{HostEnrollmentRequestSchema,runHostEnrollment}from"./chunk-LTNJ45JP.js";import{runDesktopDeviceRequest}from"./chunk-PQCA4X5H.js";import"./chunk-H4FH6STZ.js";import"./chunk-MZWEFYHE.js";import"./chunk-FFXSXE3G.js";import"./chunk-ETK7GYCB.js";import{DesktopDeviceRequestSchema}from"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-2S7FI3HF.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-VNLA3YOV.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-VNLA3YOV.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-2JHTRTOB.js");const request2=HostComponentRequestSchema.parse(raw);entered=true;mutation=!["status","preflight","receipt","service-plan"].includes(request2.call.action);return await(await import("./host-component-ZYQ5ETVL.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:!uncertain&&["INVALID_INPUT","REVISION_CONFLICT"].includes(code)?code:"BLOCKED",error:{code,outcome:uncertain?"UNKNOWN":"NO_WRITE"}}}}}export{runHostCli};
@@ -1 +1 @@
1
- import{localCaller}from"./chunk-NG4BDFEY.js";import{renderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import{DesktopLibraryImportSeedSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryRequest}from"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-3TOXIJ7K.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{LocalDeviceViewSchema,LocalManagementCommandSchema}from"./chunk-APNZQZFB.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{fail,sha256}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve,basename}from"node:path";async function libraryImportContext(home,raw,enrollment){const caller=await localCaller({...process.env,NATIVESTUDIO_CLIENT_HOME:home},typeof raw.projectId==="string"?raw.projectId:void 0);if(!caller){if(!["tenantId","projectId","deviceId","ownerKey"].every(key=>raw[key]))fail("ACCOUNT_LOGIN_REQUIRED");return{}}const{serverOrigin,tenantId,principalId,projectId}=caller;const ownerKey=sha256(JSON.stringify([serverOrigin,tenantId,principalId]));const denied=()=>{throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")};if(raw.tenantId!==void 0&&raw.tenantId!==tenantId||raw.projectId!==void 0&&raw.projectId!==projectId||raw.ownerKey!==void 0&&raw.ownerKey!==ownerKey)denied();const record=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});if(record?.device&&(record.device.enrolledByPrincipalId!==principalId||record.device.tenantId!==tenantId))denied();if(record?.pending?.phase==="SENDING")fail("DEVICE_RECEIPT_REQUIRED");let deviceId=record?.device?.deviceId;if(!deviceId&&enrollment!==void 0){const command=LocalManagementCommandSchema.parse(enrollment);if(command.kind!=="ENROLL"||command.input.tenantId!==tenantId)denied();const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const c=await renderConnection(env,void 0,false,projectId);try{if(c.scope.profile!==caller.profile||c.scope.resource!==caller.resource)denied();const receipt=await c.studio.call("device.management-receipt",{command});if(!receipt.result)fail("DEVICE_RECEIPT_REQUIRED");const device=LocalDeviceViewSchema.parse(receipt.result);if(device.enrolledByPrincipalId!==principalId||device.tenantId!==tenantId)denied();deviceId=device.deviceId}finally{await c.close().catch(()=>{})}}if(!deviceId)fail("DEVICE_SETUP_REQUIRED");if(raw.deviceId!==void 0&&raw.deviceId!==deviceId)denied();await caller.assertCurrent();return{tenantId,projectId,deviceId,ownerKey,assertCurrent:caller.assertCurrent}}async function runLocalLibrary(argv,stdin){const[action,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--home","--input","--file","--enrollment"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}if(!action||!["import","list","get","read","access","sync","resume-access","import-receipt","usage"].includes(action)||!flags.has("--input")||flags.get("--input")==="-"&&flags.get("--enrollment")==="-"||action!=="import"&&(flags.has("--file")||flags.has("--enrollment")))throw Error();const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(flags.get("--input"),stdin);if(action!=="import")return{exitCode:0,output:await runDesktopLibraryRequest(home,{operation:"library",call:{...raw,action}})};const file=flags.get("--file");if(!file)throw Error();const enrollment=flags.has("--enrollment")?await readInput(flags.get("--enrollment"),stdin):void 0;const{assertCurrent,...defaults}=await libraryImportContext(home,raw,enrollment);const seed=DesktopLibraryImportSeedSchema.parse({...defaults,title:basename(file),contentType:"application/octet-stream",...raw});const request=await prepareDesktopLibraryImport({operation:"library-import-prepare",file:resolve(file),seed});await assertCurrent?.();return{exitCode:0,output:await runDesktopLibraryImport(home,request)}}export{runLocalLibrary};
1
+ import{localCaller}from"./chunk-X5MVC46N.js";import{renderConnection}from"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import{DesktopLibraryImportSeedSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryRequest}from"./chunk-DMA53YVU.js";import"./chunk-MZWEFYHE.js";import"./chunk-FFXSXE3G.js";import{DesktopDeviceRecords}from"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import"./chunk-3TOXIJ7K.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{LocalDeviceViewSchema,LocalManagementCommandSchema}from"./chunk-2S7FI3HF.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{fail,sha256}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve,basename}from"node:path";async function libraryImportContext(home,raw,enrollment){const caller=await localCaller({...process.env,NATIVESTUDIO_CLIENT_HOME:home},typeof raw.projectId==="string"?raw.projectId:void 0);if(!caller){if(!["tenantId","projectId","deviceId","ownerKey"].every(key=>raw[key]))fail("ACCOUNT_LOGIN_REQUIRED");return{}}const{serverOrigin,tenantId,principalId,projectId}=caller;const ownerKey=sha256(JSON.stringify([serverOrigin,tenantId,principalId]));const denied=()=>{throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")};if(raw.tenantId!==void 0&&raw.tenantId!==tenantId||raw.projectId!==void 0&&raw.projectId!==projectId||raw.ownerKey!==void 0&&raw.ownerKey!==ownerKey)denied();const record=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});if(record?.device&&(record.device.enrolledByPrincipalId!==principalId||record.device.tenantId!==tenantId))denied();if(record?.pending?.phase==="SENDING")fail("DEVICE_RECEIPT_REQUIRED");let deviceId=record?.device?.deviceId;if(!deviceId&&enrollment!==void 0){const command=LocalManagementCommandSchema.parse(enrollment);if(command.kind!=="ENROLL"||command.input.tenantId!==tenantId)denied();const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const c=await renderConnection(env,void 0,false,projectId);try{if(c.scope.profile!==caller.profile||c.scope.resource!==caller.resource)denied();const receipt=await c.studio.call("device.management-receipt",{command});if(!receipt.result)fail("DEVICE_RECEIPT_REQUIRED");const device=LocalDeviceViewSchema.parse(receipt.result);if(device.enrolledByPrincipalId!==principalId||device.tenantId!==tenantId)denied();deviceId=device.deviceId}finally{await c.close().catch(()=>{})}}if(!deviceId)fail("DEVICE_SETUP_REQUIRED");if(raw.deviceId!==void 0&&raw.deviceId!==deviceId)denied();await caller.assertCurrent();return{tenantId,projectId,deviceId,ownerKey,assertCurrent:caller.assertCurrent}}async function runLocalLibrary(argv,stdin){const[action,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--home","--input","--file","--enrollment"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}if(!action||!["import","list","get","read","access","sync","resume-access","import-receipt","usage"].includes(action)||!flags.has("--input")||flags.get("--input")==="-"&&flags.get("--enrollment")==="-"||action!=="import"&&(flags.has("--file")||flags.has("--enrollment")))throw Error();const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(flags.get("--input"),stdin);if(action!=="import")return{exitCode:0,output:await runDesktopLibraryRequest(home,{operation:"library",call:{...raw,action}})};const file=flags.get("--file");if(!file)throw Error();const enrollment=flags.has("--enrollment")?await readInput(flags.get("--enrollment"),stdin):void 0;const{assertCurrent,...defaults}=await libraryImportContext(home,raw,enrollment);const seed=DesktopLibraryImportSeedSchema.parse({...defaults,title:basename(file),contentType:"application/octet-stream",...raw});const request=await prepareDesktopLibraryImport({operation:"library-import-prepare",file:resolve(file),seed});await assertCurrent?.();return{exitCode:0,output:await runDesktopLibraryImport(home,request)}}export{runLocalLibrary};
@@ -1 +1 @@
1
- import{loginCommand,runLoginService}from"./chunk-D74NHT4I.js";import{prepareInstalledCpuSpeech}from"./chunk-FVY3PLG7.js";import{connectDevice,generateDeviceKey}from"./chunk-HBDPYWMI.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-ELUJ44BO.js";import{LocalAgentGrantSchema,NativeStudioLocalDeviceClient,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-6EZX2TRX.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,LocalManagementCommandSchema,NativeStudioAgentClient,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";function preparationGuidance(code){const steps={DEPENDENCY_CHANNEL_REQUIRED:["Read workspace_caller.hostReleases (CLI: call workspace.caller); use its exact configured URL, not an inferred path.","Configure the advertised catalogueUrl/publicKey through local configure; never accept an unsigned catalogue or invent a trust key."],MANAGED_TOOLS_UNAVAILABLE:["This exact signed release has no qualified managed media executables. Install the required tools using the host's authorized package manager or official vendor.","Use local tools-prepare --version <resolved-runtime-version> --input <private-json> with mode INSTALLED and absolute ffmpeg/ffprobe paths. Missing fonts/browser remain separate capabilities."],RELEASE_NOT_PUBLISHED:["Ask the release operator to publish matching exact-version dependencies. Preserve this CLI/Runtime identity; do not substitute another version's bytes."],RELEASE_METADATA_INVALID:["Reject malformed release metadata; ask the operator to check the exact signed catalogue URL. Do not treat a discovery page as a catalogue."],RELEASE_ACCESS_DENIED:["The public download edge denied access. Inspect its safe status; for Cloudflare 1010, identify your actual application with a descriptive User-Agent. Do not disable TLS or copy a browser session."],RELEASE_TIMEOUT:["The read deadline ended. An unknown installation apply must be reconciled from its original plan, never replayed blindly."],RELEASE_SIGNATURE_INVALID:["Reject these bytes. Verify the configured operator URL/public key; do not rotate trust to make verification pass."],RELEASE_EXPIRED:["Ask the operator to renew the approved inventory; never ignore expiry or alter the host clock."],BUNDLED_COMPONENT_RELEASE_MISMATCH:["The catalogue does not match the code/resources inside this CLI. Keep the original installation plan; ask the operator for its matching release."],LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED:["Activate a Runtime with login startup support through the existing exact-version installation plan."],LOGIN_SERVICE_REPLACE_REQUIRED:["Read local service-status and disable the existing registration using its original fingerprint. Then approve the current service plan."],LOGIN_SERVICE_OS_UNCONFIRMED:["Read local service-status and check the current user's native service manager. Keep the original approval fingerprint for reconciliation."],LOGIN_SERVICE_DISABLE_PENDING:["Read local service-status and complete service-disable using the original fingerprint."]};return steps[code]}import{homedir}from"node:os";import{join,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));const disclosures=["review metadata",...grant.imageDisclosureApproved?["original image pixels"]:[],...grant.mediaDisclosureApproved?["normalized image pixels or sampled video frames and technical audio statistics"]:[]];return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:`Approving this fingerprint permits remote OpenAI inference for these Projects until expiry and allows disclosure of ${disclosures.join(", ")}. Preview does not invoke a model.`}}}const evidence=flags.get("--evidence");if(evidence&&!["IMAGE_PIXELS","METADATA_ONLY","MEDIA"].includes(evidence))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);const studioFor=tenantId=>new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId,authorization:()=>readCredential(flags,process.env)});let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":{const context=await readInput(need("--input"),stdin);output=await client.prepareAgentReview(evidence==="MEDIA"?localAgentMediaSnapshot(context):localAgentSnapshotFromContext(context,evidence==="IMAGE_PIXELS"));break}case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=studioFor(snapshot.basis.scope.tenantId);const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-media-fetch":{const view=await client.inspectAgentReview(need("--id"));const{basis,evidence:expected,media}=view.plan.snapshot;if(!expected)throw Error();if(view.evidenceReceipt){output=view;break}if(view.phase!=="PREPARED")throw Error();const source=await studioFor(basis.scope.tenantId).immutableMedia({projectId:basis.scope.projectId,representationId:media.representationId,checksumSha256:media.checksumSha256,byteSize:expected.byteSize});output=await client.stageAgentImage(view.plan.id,source.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentMediaProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command==="library"){mutation=["import","access","resume-access"].includes(rest[0]??"");return await(await import("./library-main-ATRFEAVN.js")).runLocalLibrary(rest,stdin)}if(command==="device-preflight"){for(let i=0;i<rest.length;i+=2){const name=rest[i],value=rest[i+1];if(!name||!["--kind","--home","--project"].includes(name)||!value||value.startsWith("--")||options.has(name))throw Error();options.set(name,value)}return(await import("./device-preflight-C7FFUXI2.js")).devicePreflight(options.get("--kind"),{...process.env,...options.has("--home")&&{NATIVESTUDIO_CLIENT_HOME:resolve2(options.get("--home"))}},options.get("--project"))}if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|revoke-device|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact|latest> \u2014 uses this CLI's bundled code; update CLI first for newer code; latest resolves once into an exact saved plan","speech-prepare --input <json with optional voiceIds> \u2014 prepare pinned CPU speech resources and return the original tools update plan","tools-prepare --version <exact|latest> --input <private-json with mode MANAGED or INSTALLED, exact ffmpeg/ffprobe paths, optional compositionBrowser and captionAssetsDirectory>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","service-plan|service-status [--home <private-client-home>] \u2014 inspect optional user-login startup without changing it","service-enable|service-start|service-disable --approve <service-fingerprint> [--home <private-client-home>] \u2014 register, start or remove this installation's user-login service","device-preflight --kind preview|final|<processor-kind> [--project <uuid>] [--home <private-client-home>] \u2014 read current setup and action qualification","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-library]","library import|list|get|read|access|sync|resume-access|import-receipt|usage --input <json|-> [--file <exact-media>] [--home <client-home>] \u2014 private Owner library; import never uploads","agent-grant-plan|agent-probe|agent-grant|agent-revoke \u2014 installed Codex CLI with explicitly authorized remote OpenAI inference","review-prepare --input <private-context> [--evidence METADATA_ONLY|IMAGE_PIXELS|MEDIA]","review-media-fetch --id <draft> --origin <cloud-origin> --token-file <member-token> \u2014 read exact stored bytes for a MEDIA draft","review-image-fetch|review-inspect|review-proposal \u2014 use --id <draft>","review-start --id <draft> --revision <current> --approve <plan-fingerprint>"],note:"Release check and update planning only inspect metadata. speech-prepare explicitly fetches optional CPU resources. Apply uses the exact saved fingerprint. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const home=resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client"));if(loginCommand(command)){mutation=["service-enable","service-start","service-disable"].includes(command);if([...options.keys()].some(key=>key!=="--home"&&(!mutation||key!=="--approve")))throw Error();return{exitCode:0,output:await runLoginService(command,home,options.get("--approve"))}}const manager=await LocalInstallationManager.open(home);let output;mutation=["configure","speech-prepare","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepareBundled(required("--version"));break;case"speech-prepare":output=await prepareInstalledCpuSpeech(manager,await readInput(required("--input"),stdin));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepareBundled(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",...preparationGuidance(known)?{nextSteps:preparationGuidance(known)}:{},error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED","DEVICE_CONNECTION_REQUIRED","LOGIN_SERVICE_PLAN_CHANGED","LOGIN_SERVICE_REPLACE_REQUIRED","LOGIN_SERVICE_DISABLE_PENDING","LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED","LOGIN_SERVICE_PLATFORM_UNSUPPORTED","LOGIN_SERVICE_USER_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
1
+ import{loginCommand,runLoginService}from"./chunk-5Y7J2OYL.js";import{prepareInstalledCpuSpeech}from"./chunk-VXYZCCCQ.js";import{connectDevice,generateDeviceKey}from"./chunk-H4FH6STZ.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-FFXSXE3G.js";import{LocalAgentGrantSchema,NativeStudioLocalDeviceClient,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-LDBXGRCQ.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,LocalManagementCommandSchema,NativeStudioAgentClient,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-2S7FI3HF.js";import"./chunk-7I7ARCY7.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";function preparationGuidance(code){const steps={DEPENDENCY_CHANNEL_REQUIRED:["Read workspace_caller.hostReleases (CLI: call workspace.caller); use its exact configured URL, not an inferred path.","Configure the advertised catalogueUrl/publicKey through local configure; never accept an unsigned catalogue or invent a trust key."],MANAGED_TOOLS_UNAVAILABLE:["This exact signed release has no qualified managed media executables. Install the required tools using the host's authorized package manager or official vendor.","Use local tools-prepare --version <resolved-runtime-version> --input <private-json> with mode INSTALLED and absolute ffmpeg/ffprobe paths. Missing fonts/browser remain separate capabilities."],RELEASE_NOT_PUBLISHED:["Ask the release operator to publish matching exact-version dependencies. Preserve this CLI/Runtime identity; do not substitute another version's bytes."],RELEASE_METADATA_INVALID:["Reject malformed release metadata; ask the operator to check the exact signed catalogue URL. Do not treat a discovery page as a catalogue."],RELEASE_ACCESS_DENIED:["The public download edge denied access. Inspect its safe status; for Cloudflare 1010, identify your actual application with a descriptive User-Agent. Do not disable TLS or copy a browser session."],RELEASE_TIMEOUT:["The read deadline ended. An unknown installation apply must be reconciled from its original plan, never replayed blindly."],RELEASE_SIGNATURE_INVALID:["Reject these bytes. Verify the configured operator URL/public key; do not rotate trust to make verification pass."],RELEASE_EXPIRED:["Ask the operator to renew the approved inventory; never ignore expiry or alter the host clock."],BUNDLED_COMPONENT_RELEASE_MISMATCH:["The catalogue does not match the code/resources inside this CLI. Keep the original installation plan; ask the operator for its matching release."],LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED:["Activate a Runtime with login startup support through the existing exact-version installation plan."],LOGIN_SERVICE_REPLACE_REQUIRED:["Read local service-status and disable the existing registration using its original fingerprint. Then approve the current service plan."],LOGIN_SERVICE_OS_UNCONFIRMED:["Read local service-status and check the current user's native service manager. Keep the original approval fingerprint for reconciliation."],LOGIN_SERVICE_DISABLE_PENDING:["Read local service-status and complete service-disable using the original fingerprint."]};return steps[code]}import{homedir}from"node:os";import{join,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));const disclosures=["review metadata",...grant.imageDisclosureApproved?["original image pixels"]:[],...grant.mediaDisclosureApproved?["normalized image pixels or sampled video frames and technical audio statistics"]:[]];return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:`Approving this fingerprint permits remote OpenAI inference for these Projects until expiry and allows disclosure of ${disclosures.join(", ")}. Preview does not invoke a model.`}}}const evidence=flags.get("--evidence");if(evidence&&!["IMAGE_PIXELS","METADATA_ONLY","MEDIA"].includes(evidence))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);const studioFor=tenantId=>new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId,authorization:()=>readCredential(flags,process.env)});let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":{const context=await readInput(need("--input"),stdin);output=await client.prepareAgentReview(evidence==="MEDIA"?localAgentMediaSnapshot(context):localAgentSnapshotFromContext(context,evidence==="IMAGE_PIXELS"));break}case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=studioFor(snapshot.basis.scope.tenantId);const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-media-fetch":{const view=await client.inspectAgentReview(need("--id"));const{basis,evidence:expected,media}=view.plan.snapshot;if(!expected)throw Error();if(view.evidenceReceipt){output=view;break}if(view.phase!=="PREPARED")throw Error();const source=await studioFor(basis.scope.tenantId).immutableMedia({projectId:basis.scope.projectId,representationId:media.representationId,checksumSha256:media.checksumSha256,byteSize:expected.byteSize});output=await client.stageAgentImage(view.plan.id,source.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentMediaProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command==="library"){mutation=["import","access","resume-access"].includes(rest[0]??"");return await(await import("./library-main-3WWH7UYV.js")).runLocalLibrary(rest,stdin)}if(command==="device-preflight"){for(let i=0;i<rest.length;i+=2){const name=rest[i],value=rest[i+1];if(!name||!["--kind","--home","--project"].includes(name)||!value||value.startsWith("--")||options.has(name))throw Error();options.set(name,value)}return(await import("./device-preflight-GTQ67H7C.js")).devicePreflight(options.get("--kind"),{...process.env,...options.has("--home")&&{NATIVESTUDIO_CLIENT_HOME:resolve2(options.get("--home"))}},options.get("--project"))}if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|revoke-device|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact|latest> \u2014 uses this CLI's bundled code; update CLI first for newer code; latest resolves once into an exact saved plan","speech-prepare --input <json with optional voiceIds> \u2014 prepare pinned CPU speech resources and return the original tools update plan","tools-prepare --version <exact|latest> --input <private-json with mode MANAGED or INSTALLED, exact ffmpeg/ffprobe paths, optional compositionBrowser and captionAssetsDirectory>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","service-plan|service-status [--home <private-client-home>] \u2014 inspect optional user-login startup without changing it","service-enable|service-start|service-disable --approve <service-fingerprint> [--home <private-client-home>] \u2014 register, start or remove this installation's user-login service","device-preflight --kind preview|final|<processor-kind> [--project <uuid>] [--home <private-client-home>] \u2014 read current setup and action qualification","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-library]","library import|list|get|read|access|sync|resume-access|import-receipt|usage --input <json|-> [--file <exact-media>] [--home <client-home>] \u2014 private Owner library; import never uploads","agent-grant-plan|agent-probe|agent-grant|agent-revoke \u2014 installed Codex CLI with explicitly authorized remote OpenAI inference","review-prepare --input <private-context> [--evidence METADATA_ONLY|IMAGE_PIXELS|MEDIA]","review-media-fetch --id <draft> --origin <cloud-origin> --token-file <member-token> \u2014 read exact stored bytes for a MEDIA draft","review-image-fetch|review-inspect|review-proposal \u2014 use --id <draft>","review-start --id <draft> --revision <current> --approve <plan-fingerprint>"],note:"Release check and update planning only inspect metadata. speech-prepare explicitly fetches optional CPU resources. Apply uses the exact saved fingerprint. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const home=resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client"));if(loginCommand(command)){mutation=["service-enable","service-start","service-disable"].includes(command);if([...options.keys()].some(key=>key!=="--home"&&(!mutation||key!=="--approve")))throw Error();return{exitCode:0,output:await runLoginService(command,home,options.get("--approve"))}}const manager=await LocalInstallationManager.open(home);let output;mutation=["configure","speech-prepare","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepareBundled(required("--version"));break;case"speech-prepare":output=await prepareInstalledCpuSpeech(manager,await readInput(required("--input"),stdin));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepareBundled(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",...preparationGuidance(known)?{nextSteps:preparationGuidance(known)}:{},error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED","DEVICE_CONNECTION_REQUIRED","LOGIN_SERVICE_PLAN_CHANGED","LOGIN_SERVICE_REPLACE_REQUIRED","LOGIN_SERVICE_DISABLE_PENDING","LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED","LOGIN_SERVICE_PLATFORM_UNSUPPORTED","LOGIN_SERVICE_USER_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};