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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/COMPATIBILITY.json +11 -11
  2. package/components/runtime.json +7 -7
  3. package/components/runtime.tgz +0 -0
  4. package/dist/_chunks/chunk-226SBV53.js +1 -0
  5. package/dist/_chunks/{chunk-TWC3NXFA.js → chunk-27KI24GK.js} +1 -1
  6. package/dist/_chunks/chunk-2GV47BUV.js +1 -0
  7. package/dist/_chunks/chunk-2MKMGMA4.js +1 -0
  8. package/dist/_chunks/{chunk-FX5UVDTH.js → chunk-3TOXIJ7K.js} +1 -1
  9. package/dist/_chunks/{chunk-65X56WAQ.js → chunk-4NCE337I.js} +1 -1
  10. package/dist/_chunks/{chunk-BR26X3ZF.js → chunk-5G3AJAKI.js} +1 -1
  11. package/dist/_chunks/chunk-5TKBEFRX.js +1 -0
  12. package/dist/_chunks/chunk-67QDMD7M.js +1 -0
  13. package/dist/_chunks/{chunk-SKAVQ4UW.js → chunk-7I7ARCY7.js} +1 -1
  14. package/dist/_chunks/{chunk-UMCOLDHH.js → chunk-7P2NA6TH.js} +1 -1
  15. package/dist/_chunks/{chunk-K25YVVTT.js → chunk-AIR7YOFU.js} +1 -1
  16. package/dist/_chunks/chunk-BZPQB66Z.js +1 -0
  17. package/dist/_chunks/chunk-CTCEGOC7.js +1 -0
  18. package/dist/_chunks/chunk-DLW42PJ6.js +1 -0
  19. package/dist/_chunks/{chunk-SDTAJ7FI.js → chunk-GQ32ZQTM.js} +1 -1
  20. package/dist/_chunks/{chunk-HI5SIUX7.js → chunk-H46NB5FL.js} +1 -1
  21. package/dist/_chunks/{chunk-ORFGJBJA.js → chunk-HIBT6NXN.js} +1 -1
  22. package/dist/_chunks/chunk-IF6AUKH3.js +1 -0
  23. package/dist/_chunks/{chunk-IHTF6VEC.js → chunk-J2IYRUVM.js} +1 -1
  24. package/dist/_chunks/{chunk-UGOXJEDU.js → chunk-JL4MUI7K.js} +1 -1
  25. package/dist/_chunks/chunk-LZPPTW2K.js +1 -0
  26. package/dist/_chunks/{chunk-53EULX5D.js → chunk-PAIJRAJB.js} +1 -1
  27. package/dist/_chunks/chunk-QGK6G6YS.js +1 -0
  28. package/dist/_chunks/{chunk-KYNC2BSW.js → chunk-TIHGZGU3.js} +1 -1
  29. package/dist/_chunks/chunk-TT7IA5HB.js +1 -0
  30. package/dist/_chunks/chunk-UITIQHVU.js +45 -0
  31. package/dist/_chunks/chunk-WTJVS2VS.js +1 -0
  32. package/dist/_chunks/chunk-WXEERCXN.js +1 -0
  33. package/dist/_chunks/component-contract-HETXQ2J4.js +1 -0
  34. package/dist/_chunks/connect-7TJDWXV4.js +1 -0
  35. package/dist/_chunks/device-management-NP7HAXRU.js +1 -0
  36. package/dist/_chunks/device-preflight-QAPMMHWK.js +1 -0
  37. package/dist/_chunks/devices-inventory-WZ3QAPTS.js +1 -0
  38. package/dist/_chunks/devices-main-XKRRLX5B.js +1 -0
  39. package/dist/_chunks/files-JJ6YOULB.js +1 -0
  40. package/dist/_chunks/host-component-H3Q7TU5Y.js +1 -0
  41. package/dist/_chunks/host-help-SBXGX457.js +1 -0
  42. package/dist/_chunks/host-main-VUEGUFTU.js +1 -0
  43. package/dist/_chunks/http-profile-3VVSWYA5.js +1 -0
  44. package/dist/_chunks/library-main-4BQ2J73H.js +1 -0
  45. package/dist/_chunks/local-main-GBC2HPD4.js +1 -0
  46. package/dist/_chunks/local-mcp-FXHB3CKF.js +1 -0
  47. package/dist/_chunks/main-R7DV24KT.js +2 -0
  48. package/dist/_chunks/mcp-6D4KHCCL.js +1 -0
  49. package/dist/_chunks/oauth-RPME2XYB.js +1 -0
  50. package/dist/_chunks/observe-entry-NKXTUZYF.js +1 -0
  51. package/dist/_chunks/remote-client-TIFVZEGG.js +1 -0
  52. package/dist/_chunks/render-main-KMP4SMK7.js +1 -0
  53. package/dist/_chunks/source-import-YYRII5FQ.js +1 -0
  54. package/dist/_chunks/src-IX5ZVGZS.js +1 -0
  55. package/dist/_chunks/stdio-main-HNLJCG45.js +1 -0
  56. package/dist/_chunks/workspace-main-LD56MMI6.js +1 -0
  57. package/dist/_types/cli/local/desktop-contract.d.ts +9 -3
  58. package/dist/_types/cli/local/desktop-device-contract.d.ts +18 -3
  59. package/dist/_types/cli/local/desktop-device-owner.d.ts +4 -1
  60. package/dist/_types/cli/local/desktop-device-state.d.ts +10 -4
  61. package/dist/_types/cli/local/desktop-owner.d.ts +13 -11
  62. package/dist/_types/cli/local/ledger.d.ts +2 -0
  63. package/dist/_types/cli/local/manager.d.ts +12 -6
  64. package/dist/_types/cli/local/mcp-tools.d.ts +21 -4
  65. package/dist/_types/contracts/component-status.d.ts +241 -0
  66. package/dist/_types/contracts/composition-source-review.d.ts +1 -1
  67. package/dist/_types/contracts/delivery-completion.d.ts +1 -1
  68. package/dist/_types/contracts/delivery-operations.d.ts +5 -5
  69. package/dist/_types/contracts/delivery-summary.d.ts +1 -1
  70. package/dist/_types/contracts/delivery-validation.d.ts +3 -3
  71. package/dist/_types/contracts/device-render.d.ts +2 -0
  72. package/dist/_types/contracts/final-render.d.ts +1 -1
  73. package/dist/_types/contracts/index.d.ts +1 -0
  74. package/dist/_types/contracts/interface/common.d.ts +18 -0
  75. package/dist/_types/contracts/interface/production-snapshot.d.ts +1 -1
  76. package/dist/_types/contracts/keyframe-review.d.ts +6 -6
  77. package/dist/_types/contracts/local-execution/agent-component-status.d.ts +109 -0
  78. package/dist/_types/contracts/local-execution/agent-context.d.ts +4 -4
  79. package/dist/_types/contracts/local-execution/agent-review.d.ts +7 -7
  80. package/dist/_types/contracts/local-execution/device.d.ts +2 -1
  81. package/dist/_types/contracts/local-execution/enrollment-credential.d.ts +141 -0
  82. package/dist/_types/contracts/local-execution/enrollment-handoff.d.ts +44 -0
  83. package/dist/_types/contracts/local-execution/index.d.ts +3 -0
  84. package/dist/_types/contracts/local-execution/ipc.d.ts +43 -9
  85. package/dist/_types/contracts/local-execution/library-result.d.ts +4 -0
  86. package/dist/_types/contracts/local-execution/local-navigation.d.ts +25 -8
  87. package/dist/_types/contracts/local-execution/management.d.ts +5 -2
  88. package/dist/_types/contracts/local-execution/media-validation.d.ts +2 -2
  89. package/dist/_types/contracts/local-execution/preview.d.ts +1 -0
  90. package/dist/_types/contracts/local-execution/processor-capability.d.ts +8 -0
  91. package/dist/_types/contracts/local-execution/processor-recipes.d.ts +29 -0
  92. package/dist/_types/contracts/local-execution/processor.d.ts +73 -3
  93. package/dist/_types/contracts/local-execution/workspace.d.ts +1 -1
  94. package/dist/_types/contracts/mcp-capabilities.d.ts +1 -0
  95. package/dist/_types/contracts/navigation-context.d.ts +1 -0
  96. package/dist/_types/contracts/navigation.d.ts +1 -0
  97. package/dist/_types/contracts/programmatic-exploration.d.ts +8 -8
  98. package/dist/_types/contracts/programmatic-video-review.d.ts +5 -5
  99. package/dist/_types/contracts/reference-preview.d.ts +1 -0
  100. package/dist/_types/contracts/repair-lifecycle.d.ts +12 -12
  101. package/dist/_types/contracts/repair-plan.d.ts +2 -2
  102. package/dist/_types/contracts/review-intelligence-final-output.d.ts +3 -3
  103. package/dist/_types/contracts/review-intelligence.d.ts +5 -5
  104. package/dist/_types/contracts/review1-repair-source.d.ts +6 -6
  105. package/dist/_types/contracts/review1-repair-strategy.d.ts +4 -4
  106. package/dist/_types/contracts/video-review.d.ts +6 -6
  107. package/dist/_types/sdk/errors.d.ts +3 -2
  108. package/dist/_types/sdk/local-runtime/device-client.d.ts +2 -2
  109. package/dist/_types/sdk/local-runtime-client.d.ts +29 -16
  110. package/dist/entry.js +1 -1
  111. package/dist/local-management.js +1 -1
  112. package/dist/local-navigation.js +1 -1
  113. package/package.json +1 -1
  114. package/dist/_chunks/chunk-3KBIDTXT.js +0 -1
  115. package/dist/_chunks/chunk-4IFMG2ZS.js +0 -1
  116. package/dist/_chunks/chunk-4NJIT52T.js +0 -1
  117. package/dist/_chunks/chunk-744IEPTK.js +0 -1
  118. package/dist/_chunks/chunk-C7CSZFV6.js +0 -1
  119. package/dist/_chunks/chunk-CW67UB2I.js +0 -1
  120. package/dist/_chunks/chunk-GKDGSAI5.js +0 -1
  121. package/dist/_chunks/chunk-HAOCQVMU.js +0 -1
  122. package/dist/_chunks/chunk-HTUTYIRU.js +0 -1
  123. package/dist/_chunks/chunk-RUPH3HZ2.js +0 -1
  124. package/dist/_chunks/chunk-U5FT4VBR.js +0 -1
  125. package/dist/_chunks/connect-OY623MMA.js +0 -1
  126. package/dist/_chunks/device-management-CXSZFF53.js +0 -1
  127. package/dist/_chunks/device-preflight-6HKPPZ5L.js +0 -1
  128. package/dist/_chunks/devices-inventory-K553HAF3.js +0 -1
  129. package/dist/_chunks/devices-main-LBDRDV2M.js +0 -1
  130. package/dist/_chunks/files-72BEXD7E.js +0 -1
  131. package/dist/_chunks/host-main-ZMBFHY55.js +0 -1
  132. package/dist/_chunks/http-profile-D65WSTZU.js +0 -1
  133. package/dist/_chunks/library-main-RNDPNKYK.js +0 -1
  134. package/dist/_chunks/local-main-RC4RM3OB.js +0 -1
  135. package/dist/_chunks/local-mcp-LQCQ3WLF.js +0 -1
  136. package/dist/_chunks/main-CPIMF4PS.js +0 -2
  137. package/dist/_chunks/mcp-HQQJCKHS.js +0 -1
  138. package/dist/_chunks/oauth-QBJ62PIA.js +0 -1
  139. package/dist/_chunks/observe-entry-4GPGZ3NJ.js +0 -1
  140. package/dist/_chunks/remote-client-6XHMNMXK.js +0 -1
  141. package/dist/_chunks/render-main-ATCEBECW.js +0 -1
  142. package/dist/_chunks/source-import-HIL7NW3L.js +0 -1
  143. package/dist/_chunks/src-MRFJOTKK.js +0 -1
  144. package/dist/_chunks/stdio-main-T4ORVLSX.js +0 -1
  145. package/dist/_chunks/workspace-main-44ECTGHC.js +0 -1
@@ -1 +0,0 @@
1
- import{ContinuationSchema,DeliveryOutputProfileSchema,PrincipalIdSchema,ProductionIdSchema,ProductionSchema,ProjectIdSchema,QueryLimitSchema,QueryPageInfoSchema,TenantIdSchema}from"./chunk-HAOCQVMU.js";import{z as z2}from"zod";import{z}from"zod";var ProjectLifecycleSchema=z.enum(["ACTIVE","ARCHIVED"]);var CreateProjectInputSchema=z.object({tenantId:TenantIdSchema,principalId:PrincipalIdSchema,idempotencyKey:z.string().trim().min(1).max(200),name:z.string().trim().min(1).max(200)});var CreateProjectRequestSchema=CreateProjectInputSchema.omit({principalId:true}).strict();var ProjectSchema=z.object({id:ProjectIdSchema,tenantId:TenantIdSchema,name:z.string().min(1),lifecycle:ProjectLifecycleSchema,defaultActiveProductionId:ProductionIdSchema.nullable(),revision:z.int().positive(),createdByPrincipalId:PrincipalIdSchema,createdAt:z.iso.datetime({offset:true}),updatedAt:z.iso.datetime({offset:true})});var CreatedProjectResultSchema=z.object({project:ProjectSchema,production:ProductionSchema});var ProjectLibraryQuerySchema=z2.strictObject({tenantId:TenantIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProjectLibraryScopeSchema=z2.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var ProjectLibraryPageSchema=z2.strictObject({items:z2.array(ProjectSchema).max(100),page:QueryPageInfoSchema});var ProjectWorkspaceSchema=z2.strictObject({project:ProjectSchema,productions:z2.array(ProductionSchema).max(100),possiblyTruncated:z2.boolean()});var SourceLibraryQuerySchema=ProjectLibraryQuerySchema.extend({projectId:ProjectIdSchema.optional()});var SourceLibraryItemSchema=z2.strictObject({artifactId:z2.uuid(),representationId:z2.uuid(),projectId:ProjectIdSchema,kind:z2.enum(["REFERENCE_IMAGE","REFERENCE_VIDEO","PRODUCT_INFORMATION"]),originalName:z2.string().max(255),checksumSha256:z2.string().regex(/^[0-9a-f]{64}$/),contentType:z2.enum(["image/png","image/jpeg","image/webp","text/plain","application/json","video/mp4"]),byteSize:z2.int().positive().max(8388608),width:z2.int().positive().nullable(),height:z2.int().positive().nullable(),createdAt:z2.iso.datetime({offset:true})});var SourceLibraryPageSchema=z2.strictObject({items:z2.array(SourceLibraryItemSchema).max(100),page:QueryPageInfoSchema});var SourceLibraryMediaSchema=ProjectLibraryScopeSchema.extend({artifactId:z2.uuid()});var StudioInputContentSchema=z2.strictObject({schemaVersion:z2.literal(1),productionId:z2.uuid(),projectTitle:z2.string().trim().min(1).max(200),name:z2.string().trim().max(300),intent:z2.string().trim().min(1).max(2e3),aspectRatio:z2.enum(["16:9","9:16"]),targetDurationSeconds:z2.int().min(30).max(60),outputProfile:DeliveryOutputProfileSchema,sourceArtifactIds:z2.array(z2.uuid()).max(12)});import{z as z3}from"zod";var HumanEmailSchema=z3.string().trim().max(254).toLowerCase().pipe(z3.email()).refine(v=>/^[\x21-\x7e]+$/.test(v),"Use an ASCII email address");var HumanPasswordSchema=z3.string().max(512).superRefine((v,c)=>{const points=[...v];const control=points.some(c2=>c2.codePointAt(0)<32||c2.codePointAt(0)===127);if(points.length<15||points.length>128||control)c.addIssue({code:"custom",message:"Password must contain 15\u2013128 characters"})});var HumanCodePurposeSchema=z3.enum(["REGISTER","RESET_PASSWORD","LINK_EMAIL"]);var HumanCodeRequestSchema=z3.strictObject({email:HumanEmailSchema,purpose:HumanCodePurposeSchema});var HumanCodeRequestedSchema=z3.strictObject({accepted:z3.literal(true),challengeId:z3.uuid(),retryAfterSeconds:z3.literal(60),expiresInSeconds:z3.literal(600)});var proof={challengeId:z3.uuid(),email:HumanEmailSchema,code:z3.string().regex(/^\d{6}$/),password:HumanPasswordSchema};var HumanRegisterSchema=z3.strictObject({...proof,displayName:z3.string().trim().min(1).max(80)});var HumanResetSchema=z3.strictObject(proof);var HumanLoginSchema=z3.strictObject({email:HumanEmailSchema,password:z3.string().max(512),rememberMe:z3.boolean().optional()});var HumanTenantSchema=z3.strictObject({id:z3.uuid(),displayName:z3.string().max(200)});var HumanAccountSchema=z3.strictObject({principalId:z3.uuid(),displayName:z3.string().max(200),email:HumanEmailSchema.nullable(),tenants:z3.array(HumanTenantSchema).max(100)});var HumanDesktopSessionSchema=z3.strictObject({tenantId:z3.uuid(),scopeKey:z3.string().regex(/^[a-f0-9]{64}$/),expiresAt:z3.int().positive(),sessionExpiresAt:z3.int().positive().optional(),rememberMe:z3.boolean(),account:HumanAccountSchema.omit({tenants:true})}).refine(({rememberMe,expiresAt,sessionExpiresAt})=>sessionExpiresAt===void 0||rememberMe&&sessionExpiresAt>=expiresAt,"Desktop persistence requires consent and the session deadline");var ShortHumanSessionSchema=z3.strictObject({accessToken:z3.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/),expiresAt:z3.iso.datetime(),account:HumanAccountSchema});var HumanRefreshTokenSchema=z3.string().regex(/^nvshr_[A-Za-z0-9_-]{43}$/);var HumanRefreshSchema=z3.strictObject({refreshToken:HumanRefreshTokenSchema});var HumanSessionSchema=ShortHumanSessionSchema.extend({refreshToken:HumanRefreshTokenSchema.optional(),sessionId:z3.uuid().optional(),sessionExpiresAt:z3.iso.datetime().optional()}).refine(session=>{const{refreshToken,sessionId,sessionExpiresAt,expiresAt}=session;if(!refreshToken)return sessionId===void 0&&sessionExpiresAt===void 0;return!!sessionId&&!!sessionExpiresAt&&Date.parse(expiresAt)<=Date.parse(sessionExpiresAt)},"Persistent session requires its exact identity and absolute expiry");var HumanIdentityAvailabilitySchema=z3.strictObject({passwordLogin:z3.boolean(),emailVerification:z3.boolean()});var HumanIdentityFailureSchema=z3.strictObject({code:z3.enum(["INVALID_INPUT","INVALID_CREDENTIALS","INVALID_CODE","RATE_LIMITED","MAIL_UNAVAILABLE","UNAVAILABLE","UNAUTHENTICATED","CONFLICT"])});var CliAccountRedirectSchema=z3.string().max(256).refine(value=>{try{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&Number(url.port)>0&&!url.username&&!url.password&&!url.search&&!url.hash&&/^\/account-callback\/[a-f0-9-]{36}$/.test(url.pathname)&&url.href===value}catch{return false}},"Owned loopback account callback required");var proofKey=z3.string().regex(/^[A-Za-z0-9_-]{43}$/);var CliAccountRequestIdSchema=z3.uuid();var CliAccountStartSchema=z3.strictObject({redirectUri:CliAccountRedirectSchema,state:proofKey,codeChallenge:proofKey});var CliAccountStartedSchema=z3.strictObject({requestId:z3.uuid(),expiresAt:z3.iso.datetime()});var CliAccountPreviewSchema=CliAccountStartedSchema.extend({redirectUri:CliAccountRedirectSchema});var CliAccountDecisionSchema=z3.strictObject({requestId:z3.uuid(),approved:z3.boolean(),expectedPrincipalId:z3.uuid()});var CliAccountExchangeSchema=z3.strictObject({requestId:z3.uuid(),code:proofKey,codeVerifier:proofKey,redirectUri:CliAccountRedirectSchema});var CliAccountSessionSchema=ShortHumanSessionSchema.extend({credentialPurpose:z3.literal("CLI_ACCOUNT")});var CliAccountIdentitySchema=z3.strictObject({credentialPurpose:z3.literal("CLI_ACCOUNT"),account:HumanAccountSchema});export{CreateProjectRequestSchema,ProjectSchema,CreatedProjectResultSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema,SourceLibraryQuerySchema,SourceLibraryItemSchema,SourceLibraryPageSchema,SourceLibraryMediaSchema,StudioInputContentSchema,HumanTenantSchema,CliAccountStartSchema,CliAccountStartedSchema,CliAccountExchangeSchema,CliAccountSessionSchema,CliAccountIdentitySchema};
@@ -1 +0,0 @@
1
- import{LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-C7CSZFV6.js";import{directory,entries,fail,privateAccess,read,sha256,write}from"./chunk-RUPH3HZ2.js";import{z}from"zod";var DesktopDeviceScopeSchema=z.strictObject({origin:z.url().refine(value=>{const u=new URL(value);return u.origin===value&&(u.protocol==="https:"||u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname))}),tenantId:z.uuid(),principalId:z.uuid()});var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("media-validation-capability")}),z.strictObject({action:z.literal("media-processing-capability")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120)}),z.strictObject({action:z.literal("revoke")}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),tenantMediaProcessing:z.literal(true).optional(),processorCapabilities:LocalDeviceTransportConfigurationSchema.shape.processorCapabilities,deviceRevision:z.int().positive(),tenantMediaValidation:z.literal(true).optional()}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"])}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120),revision:z.int().positive(),revokedAt:z.iso.datetime().nullable()}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","REVOKE_DEVICE","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional(),mediaValidationSupported:z.boolean().optional(),mediaProcessingSupported:z.boolean().optional(),localLibrarySupported:z.boolean().optional(),compositionProcessingSupported:z.boolean().optional()});import{join}from"node:path";var recordRoot=(home,scope)=>join(home,"devices",sha256(canonicalLocalJson(scope)));var DesktopDeviceRecords=class _DesktopDeviceRecords{constructor(root,scope){this.root=root;this.scope=scope}root;scope;static async open(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);return new _DesktopDeviceRecords(await directory(recordRoot(home,scope)),scope)}static async inspect(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);const root=recordRoot(home,scope);try{await privateAccess(join(home,"devices"),"directory");await privateAccess(root,"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _DesktopDeviceRecords(root,scope).current()}async current(){const names=(await entries(this.root)).filter(n=>/^\d{12}\.json$/.test(n)).sort();let state={revision:0,scope:this.scope,enrollment:null,device:null,previews:[],connectorId:null,connection:null,pending:null};for(const[index,name]of names.entries()){const next=DesktopDeviceStateSchema.parse(JSON.parse((await read(join(this.root,name),262144,true)).toString()));if(next.revision!==index+1||canonicalLocalJson(next.scope)!==canonicalLocalJson(this.scope))fail("DEVICE_HISTORY_INVALID");state=next}return state}async save(before,fields){if((await this.current()).revision!==before.revision)fail("REVISION_CONFLICT");const next=DesktopDeviceStateSchema.parse({...before,...fields,revision:before.revision+1});try{await write(join(this.root,String(next.revision).padStart(12,"0")+".json"),canonicalLocalJson(next),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}keyPath(){return join(this.root,"device-key.json")}connectorPath(id){return join(this.root,id+".connector.json")}};async function desktopDeviceConnector(home,scope){const records=await DesktopDeviceRecords.open(home,scope),state=await records.current();if(!state.connectorId)fail("LOCAL_AUTHORIZATION_REQUIRED");return records.connectorPath(state.connectorId)}export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceReplySchema,DesktopDeviceRecords,desktopDeviceConnector};
@@ -1 +0,0 @@
1
- import{z}from"zod";var TenantIdSchema=z.uuid().brand();var PrincipalIdSchema=z.uuid().brand();var ProjectIdSchema=z.uuid().brand();var ProductionIdSchema=z.uuid().brand();var ArtifactIdSchema=z.uuid().brand();var ArtifactRepresentationIdSchema=z.uuid().brand();var ArtifactRelationIdSchema=z.uuid().brand();var BriefIdSchema=z.uuid().brand();var BriefVersionIdSchema=z.uuid().brand();var StoryIdSchema=z.uuid().brand();var StoryVersionIdSchema=z.uuid().brand();var SceneShotPlanIdSchema=z.uuid().brand();var SceneShotPlanVersionIdSchema=z.uuid().brand();var SceneIdSchema=z.uuid().brand();var ShotIdSchema=z.uuid().brand();var ContinuityEdgeIdSchema=z.uuid().brand();var RuntimeJobIdSchema=z.uuid().brand();var OperationIdSchema=z.string().regex(/^op_[A-Za-z0-9_-]+$/).max(2048).brand();var RuntimeJobAttemptIdSchema=z.uuid().brand();var OutboxEventIdSchema=z.uuid().brand();import{z as z2}from"zod";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var page=new RegExp(`^/(?:projects(?:/${uuid})?|artifacts|productions/${uuid}(?:/(?:artifacts|delivery|history))?|settings/voices(?:/${uuid}(?:/versions/[1-9][0-9]*)?)?)$`);var HumanLinkScopeSchema=z2.strictObject({tenantId:z2.uuid(),projectId:z2.uuid().optional(),productionId:z2.uuid().optional(),artifactId:z2.uuid().optional(),representationId:z2.uuid().optional(),delivery:z2.boolean().optional(),voices:z2.boolean().optional(),voiceProfileId:z2.uuid().optional(),voiceProfileVersion:z2.int().positive().optional()}).refine(s=>!!s.artifactId===!!s.representationId&&(!s.delivery||!!s.productionId)&&(s.voiceProfileVersion===void 0||!!s.voiceProfileId));var HumanLinkSchema=z2.strictObject({rel:z2.enum(["workspace","project","production","artifact","delivery","voice_profile"]),href:z2.url().max(2048)}).refine(({rel,href})=>{try{const u=new URL(href),q=u.searchParams,parts=u.pathname.split("/"),pathId=parts[1]==="settings"?parts[3]:parts[2];return u.href===href&&!u.username&&!u.password&&!href.includes("#")&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))&&page.test(u.pathname)&&(!pathId||z2.uuid().safeParse(pathId).success)&&(parts[4]!=="versions"||z2.int().positive().safeParse(Number(parts[5])).success)&&new Set(q.keys()).size===q.size&&[...q].every(([key,value])=>["workspace","artifact","representation"].includes(key)&&z2.uuid().safeParse(value).success)&&q.has("workspace")&&q.has("artifact")===q.has("representation")&&(rel==="artifact"?u.pathname.endsWith("/artifacts")&&q.has("artifact"):!q.has("artifact")&&(rel==="workspace"?u.pathname==="/projects":rel==="project"?new RegExp(`^/projects/${uuid}$`).test(u.pathname):rel==="voice_profile"?u.pathname.startsWith("/settings/voices"):rel==="production"?new RegExp(`^/productions/${uuid}$`).test(u.pathname):u.pathname.endsWith("/delivery")))}catch{return false}});var HumanLinksSchema=z2.discriminatedUnion("status",[z2.strictObject({status:z2.literal("AVAILABLE"),items:z2.array(HumanLinkSchema).min(1).max(4)}),z2.strictObject({status:z2.enum(["UNCONFIGURED","UNAVAILABLE"]),items:z2.array(HumanLinkSchema).max(0)})]);import{z as z3}from"zod";var DeliveryOutputProfileSchema=z3.enum(["MP4_H264_1080P","MP4_H264_720P","MP4_H264_480P"]);var finalProfileIds={MP4_H264_1080P:"FINAL_H264_1080P_V1",MP4_H264_720P:"FINAL_H264_720P_V1",MP4_H264_480P:"FINAL_H264_480P_V1"};import{z as z4}from"zod";var InterfaceSemanticStatusSchema=z4.enum(["SUCCESS","ACCEPTED","NO_CHANGE","INVALID_INPUT","NOT_FOUND","REVISION_CONFLICT","STALE_BASIS","BLOCKED","WAITING_PROVIDER","WAITING_INPUT","RETRYING","CAPABILITY_UNAVAILABLE","PROVIDER_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED","INTERNAL_OPERATIONAL_FAILURE"]);var ActionAvailabilitySchema=z4.enum(["AVAILABLE","UNAVAILABLE"]);var NextActionSchema=z4.object({capability:z4.string().min(1).max(120),targetType:z4.string().min(1).max(80),targetId:z4.string().min(1).max(2048),availability:ActionAvailabilitySchema,reason:z4.string().min(1).max(1e3).nullable()});var ContinuationSchema=z4.string().min(1).max(8192);var QueryLimitSchema=z4.int().min(1).max(100).default(20);var QueryPageInfoSchema=z4.object({hasMore:z4.boolean(),next:ContinuationSchema.nullable()});var WorkSummarySchema=z4.object({total:z4.int().nonnegative(),pending:z4.int().nonnegative(),ready:z4.int().nonnegative(),running:z4.int().nonnegative(),waiting:z4.int().nonnegative(),succeeded:z4.int().nonnegative(),failed:z4.int().nonnegative(),cancelled:z4.int().nonnegative(),superseded:z4.int().nonnegative(),attempts:z4.int().nonnegative()});import{z as z5}from"zod";var ProductionLifecycleSchema=z5.enum(["ACTIVE","COMPLETED","FAILED","CANCELLED"]);var ProductionPhaseSchema=z5.enum(["INTAKE","PLANNING","PREPARING_GENERATION","GENERATING","SHOT_REVIEW","ASSEMBLING","ROUGH_CUT_REVIEW","FINAL_READY","FINAL_RENDERING","DELIVERY_VALIDATION"]);var ProductionConditionSchema=z5.enum(["RUNNABLE","RUNNING","WAITING_PROVIDER","WAITING_HUMAN","BLOCKED","RETRYING"]);var CreateProductionInputSchema=z5.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,principalId:PrincipalIdSchema});var ProductionStateSchema=z5.object({lifecycle:ProductionLifecycleSchema,phase:ProductionPhaseSchema,condition:ProductionConditionSchema,revision:z5.int().positive(),blockingReason:z5.string().min(1).nullable(),waitingReason:z5.string().min(1).nullable()});var ProductionSchema=z5.object({humanLinks:HumanLinksSchema.optional(),id:ProductionIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema,activeBriefVersion:z5.int().positive().nullable().default(null),activeStoryVersion:z5.int().positive().nullable().default(null),activeSceneShotPlanVersion:z5.int().positive().nullable().default(null),createdByPrincipalId:PrincipalIdSchema,createdAt:z5.iso.datetime({offset:true}),updatedAt:z5.iso.datetime({offset:true})});export{TenantIdSchema,PrincipalIdSchema,ProjectIdSchema,ProductionIdSchema,ArtifactIdSchema,ArtifactRepresentationIdSchema,ArtifactRelationIdSchema,BriefIdSchema,BriefVersionIdSchema,StoryIdSchema,StoryVersionIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,SceneIdSchema,ShotIdSchema,ContinuityEdgeIdSchema,OperationIdSchema,HumanLinksSchema,DeliveryOutputProfileSchema,finalProfileIds,InterfaceSemanticStatusSchema,NextActionSchema,ContinuationSchema,QueryLimitSchema,QueryPageInfoSchema,WorkSummarySchema,ProductionStateSchema,ProductionSchema};
@@ -1 +0,0 @@
1
- var NativeStudioSdkError=class extends Error{constructor(code,semanticStatus,outcome,status=null,issues=[]){super(`NativeStudio ${code}`);this.code=code;this.semanticStatus=semanticStatus;this.outcome=outcome;this.status=status;this.issues=issues;this.name="NativeStudioSdkError"}code;semanticStatus;outcome;status;issues};function sdkInputError(issues=[]){throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE",null,issues)}export{NativeStudioSdkError,sdkInputError};
@@ -1 +0,0 @@
1
- import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,isAbsolute}from"node:path";var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory2=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/cli/package.json")));const read2=async(name,maximum)=>{const path=join(directory2,name),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size<1||stat.size>maximum)throw Error("WINDOWS_HELPER_INVALID");const bytes2=await readFile(path);if(bytes2.length!==stat.size)throw Error("WINDOWS_HELPER_INVALID");return bytes2};const m=JSON.parse((await read2("helper.json",4096)).toString());const bytes=await read2("helper.exe",2*1024*1024);if(m.protocol!=="NVS_WINDOWS_HELPER_V1"||m.format!=="PE_AMD64_NETFRAMEWORK48"||m.byteSize!==bytes.length||!/^[a-f0-9]{64}$/.test(m.sha256)||createHash("sha256").update(bytes).digest("hex")!==m.sha256)throw Error("WINDOWS_HELPER_INVALID");return realpath(join(directory2,"helper.exe"))}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(["EXISTS","RESOURCE_BUDGET_EXCEEDED"].includes(value.error??"")?value.error:"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}async function syncDirectory(path){if(process.platform==="win32")return;const d=await open(path,"r");try{await d.sync()}finally{await d.close()}}async function atomicMove(source,target,exclusive=false){if(dirname(source)!==dirname(target))throw Error("LOCAL_ATOMIC_MOVE_INVALID");if(process.platform==="win32"){try{await windowsRequest({operation:"move",source,target,exclusive})}catch(error){if(error.message==="EXISTS")throw Object.assign(Error("EXISTS"),{code:"EEXIST"});throw error}}else{if(exclusive){await link(source,target);await unlink(source)}else await rename(source,target);await syncDirectory(dirname(target))}}async function assertExecutable(path){const s=await lstat2(path);if(!isAbsolute2(path)||!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw Error("LOCAL_EXECUTABLE_INVALID");if(process.platform==="win32"){if(!path.toLowerCase().endsWith(".exe"))throw Error("LOCAL_EXECUTABLE_INVALID");await windowsRequest({operation:"executable",path})}else if(!(s.mode&73)||s.mode&18)throw Error("LOCAL_EXECUTABLE_INVALID")}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{constants}from"node:fs";import{open as open2,realpath as realpath2,rename as rename2,unlink as unlink2,link as link2,readdir}from"node:fs/promises";import{isAbsolute as isAbsolute3,join as join3,dirname as dirname2}from"node:path";import{randomUUID as randomUUID2,createHash as createHash3}from"node:crypto";var sha256=v=>createHash3("sha256").update(v).digest("hex");var sha512=v=>createHash3("sha512").update(v).digest("hex");var LocalClientError=class extends Error{constructor(code){super("NativeStudio local "+code);this.code=code}code};function fail(code){throw new LocalClientError(code)}async function directory(path){if(!isAbsolute3(path))fail("LOCATION_UNSUPPORTED");try{await privateDirectory(path,true)}catch{fail("PRIVATE_LOCATION_REQUIRED")}const root=await realpath2(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))fail("PRIVATE_LOCATION_REQUIRED");return root}async function read(path,maximum=65536,ledger=false){try{await privateAccess(path,"file")}catch(e){if(e.code==="ENOENT")throw e;fail("PRIVATE_FILE_REQUIRED")}const f=await open2(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const s=await f.stat();if(!s.isFile()||process.platform!=="win32"&&(s.uid!==process.getuid?.()||s.mode&63)||s.size>maximum||(ledger?s.nlink>2:s.nlink!==1))fail("PRIVATE_FILE_REQUIRED");const bytes=Buffer.alloc(Math.min(maximum+1,s.size+1));let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>s.size)fail("FILE_CHANGED");if(used>maximum)fail("FILE_LIMIT");return bytes.subarray(0,used)}finally{await f.close()}}async function write(path,value,exclusive=false){const temporary=join3(dirname2(path),".tmp-"+randomUUID2());const f=await open2(temporary,"wx",384);try{await f.writeFile(value);await f.sync()}finally{await f.close()}try{if(process.platform==="win32")await atomicMove(temporary,path,exclusive);else if(exclusive)await link2(temporary,path);else{try{await read(path,64*1024*1024)}catch(e){if(e.code!=="ENOENT")throw e}await rename2(temporary,path)}}finally{await unlink2(temporary).catch(e=>{if(e.code!=="ENOENT")throw e})}await syncDirectory(dirname2(path))}async function entries(path){const values=await readdir(path);if(values.length>1e4)fail("HISTORY_LIMIT");return values}async function optional(path){try{return JSON.parse((await read(path)).toString())}catch(e){if(e.code==="ENOENT")return null;throw e}}async function verifyBackup(path,stateDirectory){const base=await realpath2(join3(stateDirectory,"backups")),actual=await realpath2(path);if(dirname2(actual)!==base||!/[0-9a-f-]{36}\.sqlite$/.test(actual))fail("JOURNAL_BACKUP_REQUIRED");try{await privateAccess(actual,"file")}catch{fail("JOURNAL_BACKUP_REQUIRED")}const f=await open2(actual,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await f.stat(),header=Buffer.alloc(16);if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size<100)fail("JOURNAL_BACKUP_REQUIRED");const n=await f.read(header,0,16,0);if(n.bytesRead!==16||header.toString()!=="SQLite format 3\0")fail("JOURNAL_BACKUP_REQUIRED")}finally{await f.close()}}export{localSocketPath,privateAccess,privateDirectory,atomicMove,assertExecutable,sha256,sha512,LocalClientError,fail,directory,read,write,entries,optional,verifyBackup};
@@ -1 +0,0 @@
1
- import{privateAccess}from"./chunk-RUPH3HZ2.js";import{open,constants}from"node:fs/promises";import{resolve}from"node:path";var limit=18*1024*1024;async function readInput(path,stdin,privateInput=false,signal){let bytes;if(path==="-"){const chunks=[];let size=0;const iterator=stdin[Symbol.asyncIterator]();try{while(true){signal?.throwIfAborted();let stopped;const pending=iterator.next();if(signal?.aborted){void pending.catch(()=>{});signal.throwIfAborted()}const next=signal?await Promise.race([pending,new Promise((_,reject)=>{stopped=()=>reject(signal.reason);signal.addEventListener("abort",stopped,{once:true})})]).finally(()=>{if(stopped)signal.removeEventListener("abort",stopped)}):await pending;if(next.done)break;size+=next.value.byteLength;if(size>limit)throw Error();chunks.push(Buffer.from(next.value))}}finally{void iterator.return?.().catch(()=>{})}bytes=Buffer.concat(chunks)}else{if(privateInput&&process.platform==="win32")await privateAccess(resolve(path),"file");const handle=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>limit||privateInput&&process.platform!=="win32"&&((stat.mode&63)!==0||process.getuid&&stat.uid!==process.getuid()))throw Error();bytes=Buffer.alloc(limit+1);let used=0;while(used<bytes.byteLength){const read=await handle.read(bytes,used,bytes.byteLength-used,null);if(!read.bytesRead)break;used+=read.bytesRead}if(used>limit)throw Error();bytes=bytes.subarray(0,used)}finally{await handle.close()}}const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!value||typeof value!=="object"||Array.isArray(value))throw Error();return value}async function readCredential(options,environment){if(options.has("--token-file")===options.has("--token-env"))throw Error();let token;const key=options.get("--token-env");if(key){if(!/^[A-Z][A-Z0-9_]{0,127}$/.test(key))throw Error();token=environment[key]??""}else{if(process.platform==="win32")await privateAccess(resolve(options.get("--token-file")),"file");const handle=await open(options.get("--token-file"),constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||process.platform!=="win32"&&(stat.mode&63)!==0||stat.size>8192)throw Error();const bytes=Buffer.alloc(8193);const{bytesRead}=await handle.read(bytes,0,bytes.length,0);if(bytesRead>8192)throw Error();token=bytes.subarray(0,bytesRead).toString("utf8").trim()}finally{await handle.close()}}if(!/^[A-Za-z0-9._~-]{1,8192}$/.test(token))throw Error();return"Bearer "+token}export{readInput,readCredential};
@@ -1 +0,0 @@
1
- import{loginLink,openLoginBrowser}from"./chunk-OW6R4MAQ.js";import{profileAuthorization,runOAuthCommand}from"./chunk-FX5UVDTH.js";import"./chunk-U5FT4VBR.js";import{clientHome,connectionError,loadConnection,readAccount,saveConnection,tenantConnection}from"./chunk-TWC3NXFA.js";import{FileOAuthProvider}from"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runConnect(argv,environment,hooks={}){if(argv[0]!=="connect")throw Error();const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--mcp-url","--scope","--timeout-ms","--browser"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const root=await clientHome(environment,true),account=await readAccount(root);const explicit=options.get("--mcp-url");if(!explicit&&!account?.workspaceId)connectionError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");const resource=tenantConnection(explicit??new URL("/mcp/external/v1/tenants/"+account.workspaceId,account.serverOrigin).href);const scope=options.get("--scope")??"nvs:read nvs:write";if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();const browser=options.get("--browser")??"auto";if(!["auto","manual"].includes(browser))throw Error();const timeout=options.get("--timeout-ms")??"180000";if(!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)throw Error();const signal=AbortSignal.timeout(Number(timeout));const profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;if(account&&(account.state!=="ACTIVE"||account.workspaceId!==resource.tenantId))connectionError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");if(!explicit){let saved=null;try{saved=await loadConnection(environment)}catch(error){if(!(error instanceof NativeStudioSdkError)||error.code!=="CONNECTION_ACCOUNT_MISMATCH")throw error}if(saved?.resource===resource.resource&&saved.scope===scope&&!saved.exchangeUnresolved){await profileAuthorization(saved.profile,signal);return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,resource:saved.resource,tenantId:saved.tenantId,scope,reused:true}}}}let provider,receiving=false,redeeming=false;let finish;const callback=new Promise(resolve=>{finish=resolve});const server=createServer({maxHeaderSize:8192,requestTimeout:5e3,headersTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address();const host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||req.url.length>4096||!req.url.startsWith(callbackPath+"?")||!provider||receiving){res.writeHead(400).end("Invalid authorization callback.");return}const url=new URL(req.url,`http://${host}`),state=url.searchParams.get("state");const expected=provider.data.state;const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(!state||Buffer.byteLength(state)!==Buffer.byteLength(expected)||!timingSafeEqual(Buffer.from(state),Buffer.from(expected))||url.searchParams.getAll("state").length!==1||url.pathname!==callbackPath||url.searchParams.getAll("iss").length!==1||url.searchParams.get("iss")!==issuer||(url.searchParams.has("error")?url.searchParams.has("code"):url.searchParams.getAll("code").length!==1||!url.searchParams.get("code"))){res.writeHead(400).end("Invalid authorization callback.");return}receiving=true;res.end("Authorization received. Return to NativeStudio CLI for the result.");finish(url.searchParams.has("error")?null:url.href)});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirect=`http://127.0.0.1:${address.port}${callbackPath}`;await runOAuthCommand(["auth-start","--profile",path,"--mcp-url",resource.resource,"--callback",redirect,"--scope",scope],empty(),signal);provider=await FileOAuthProvider.load(path);if(!provider.data.authorizationUrl)throw Error();signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(provider.data.authorizationUrl,signal);else if(browser==="manual")loginLink(provider.data.authorizationUrl);else await openLoginBrowser(provider.data.authorizationUrl,signal);const received=await callback;if(!received)connectionError(signal.aborted?"LOGIN_TIMED_OUT":"LOGIN_DENIED");async function*input(){yield Buffer.from(JSON.stringify({callbackUrl:received}))}redeeming=true;await runOAuthCommand(["auth-complete","--profile",path,"--input","-"],input(),signal);const credentials=await saveConnection(root,profile,account?.epoch).catch(()=>{throw new NativeStudioSdkError("AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"TENANT_MCP",...resource,scope:credentials.scope,requestedScope:scope,nextSteps:["nvs status","nvs find --query <intent>","nvs mcp"]}}}catch(error){if(!redeeming&&signal.aborted)connectionError("LOGIN_TIMED_OUT");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()))}}async function*empty(){}export{runConnect};
@@ -1 +0,0 @@
1
- import{profileAuthorization}from"./chunk-FX5UVDTH.js";import{readCredential,readInput}from"./chunk-U5FT4VBR.js";import{connectRemoteMcp}from"./chunk-65X56WAQ.js";import"./chunk-2UYKJ6YN.js";import"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import{defaultConnection,tenantConnection}from"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";var operations={enroll:"device.enroll",revoke:"device.revoke",receipt:"device.management-receipt"};async function deviceManagementCommand(action,args,env,stdin){if(!action||!Object.hasOwn(operations,action))throw Error();const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--input","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}if(!flags.has("--input"))throw Error();await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(k=>flags.has(k)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=tenantConnection(resource);const raw=await readInput(flags.get("--input"),stdin);const nested=action==="receipt"?raw.input:raw;if(nested?.tenantId!==void 0&&String(nested.tenantId).toLowerCase()!==scope.tenantId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const key=operations[action];const input=action==="receipt"?{command:raw}:{...raw,tenantId:scope.tenantId};const output=await connection.studio.call(key,input);return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceManagementCommand};
@@ -1 +0,0 @@
1
- import{callerOriginMatches,workspaceCaller}from"./chunk-53EULX5D.js";import{renderConnection}from"./chunk-HI5SIUX7.js";import"./chunk-KYNC2BSW.js";import{LocalInstallationManager,ownerClient,probeLocalLibrary,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-744IEPTK.js";import{DesktopDeviceRecords}from"./chunk-GKDGSAI5.js";import{LocalToolSelectionSchema}from"./chunk-3KBIDTXT.js";import"./chunk-FX5UVDTH.js";import"./chunk-U5FT4VBR.js";import"./chunk-65X56WAQ.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-4NJIT52T.js";import{LocalDeviceTransportConfigurationSchema}from"./chunk-C7CSZFV6.js";import"./chunk-UMCOLDHH.js";import"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import{LocalClientError,read}from"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.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"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"&&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 +0,0 @@
1
- import{profileAuthorization}from"./chunk-FX5UVDTH.js";import{readCredential}from"./chunk-U5FT4VBR.js";import{connectRemoteMcp}from"./chunk-65X56WAQ.js";import"./chunk-2UYKJ6YN.js";import{WorkspaceDeviceListInputSchema}from"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import{defaultConnection,tenantConnection}from"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.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 +0,0 @@
1
- import{callerRenderConnection}from"./chunk-HI5SIUX7.js";import"./chunk-KYNC2BSW.js";import"./chunk-FX5UVDTH.js";import"./chunk-U5FT4VBR.js";import"./chunk-65X56WAQ.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.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-K553HAF3.js")).deviceInventoryCommand(args,env);if(action!=="list")return(await import("./device-management-CXSZFF53.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 +0,0 @@
1
- import{LocalClientError,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-RUPH3HZ2.js";export{LocalClientError,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write};
@@ -1 +0,0 @@
1
- import{runDesktopDeviceRequest}from"./chunk-4IFMG2ZS.js";import"./chunk-IHTF6VEC.js";import"./chunk-SDTAJ7FI.js";import"./chunk-744IEPTK.js";import{DesktopDeviceRequestSchema}from"./chunk-GKDGSAI5.js";import"./chunk-3KBIDTXT.js";import{readInput}from"./chunk-U5FT4VBR.js";import"./chunk-C7CSZFV6.js";import{LocalClientError}from"./chunk-RUPH3HZ2.js";import"./chunk-HAOCQVMU.js";import"./chunk-HTUTYIRU.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"]);async function runHostCli(argv,stdin=process.stdin){let entered=false;let mutation=false;try{if(!argv.length||argv.length===1&&argv[0]==="help")return{exitCode:0,output:{protocol:"NVS_EXTERNAL_HOST_V1",agentRuntime:"EXTERNAL",commands:["host device --input <json|-> [--home <private-client-home>]"],actions:[...actions],guidance:"Use your existing tenant MCP: studio_capability_invoke targets device_enroll, and studio_capability_query targets device_management_receipt; pass each original input under arguments. Keep the device key local. Read workspace_caller.skill (or nvs skill with an existing CLI connection) for the configured download URL; CLI and SDK install through latest."}};const[command,...rest]=argv,options=new Map;if(command!=="device")throw Error();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 request=DesktopDeviceRequestSchema.parse(await readInput(file,stdin));if(!actions.has(request.call.action))throw Error();mutation=!["inspect","media-validation-capability","media-processing-capability"].includes(request.call.action);const home=resolve(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));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 uncertain=entered&&mutation&&code!=="DEVICE_COMMAND_UNSUPPORTED"||/(?:UNKNOWN|RECOVERY_REQUIRED|PROOF_UNAVAILABLE)/.test(code)||code==="INTERNAL_OPERATIONAL_FAILURE";return{exitCode:2,output:{semanticStatus:code==="INVALID_INPUT"?"INVALID_INPUT":"BLOCKED",error:{code,outcome:uncertain?"UNKNOWN":"NO_WRITE"}}}}}export{runHostCli};
@@ -1 +0,0 @@
1
- import{profileHttpOrigin}from"./chunk-UMCOLDHH.js";import"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.js";export{profileHttpOrigin};
@@ -1 +0,0 @@
1
- import{localCaller}from"./chunk-53EULX5D.js";import{renderConnection}from"./chunk-HI5SIUX7.js";import"./chunk-KYNC2BSW.js";import{DesktopLibraryImportSeedSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryRequest}from"./chunk-ORFGJBJA.js";import"./chunk-IHTF6VEC.js";import"./chunk-744IEPTK.js";import{DesktopDeviceRecords}from"./chunk-GKDGSAI5.js";import"./chunk-3KBIDTXT.js";import"./chunk-FX5UVDTH.js";import{readInput}from"./chunk-U5FT4VBR.js";import"./chunk-65X56WAQ.js";import"./chunk-2UYKJ6YN.js";import"./chunk-4NJIT52T.js";import{LocalDeviceViewSchema,LocalManagementCommandSchema}from"./chunk-C7CSZFV6.js";import"./chunk-UMCOLDHH.js";import"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import{fail,sha256}from"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.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 +0,0 @@
1
- import{prepareInstalledCpuSpeech}from"./chunk-K25YVVTT.js";import{connectDevice,generateDeviceKey}from"./chunk-SDTAJ7FI.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-744IEPTK.js";import{LocalAgentGrantSchema,NativeStudioLocalDeviceClient,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-3KBIDTXT.js";import{readCredential,readInput}from"./chunk-U5FT4VBR.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioAgentClient}from"./chunk-4NJIT52T.js";import{EnrollLocalDeviceSchema,LocalManagementCommandSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-C7CSZFV6.js";import{LocalClientError}from"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.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."]};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-RNDPNKYK.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-6HKPPZ5L.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","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 manager=await LocalInstallationManager.open(resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client")));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"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
@@ -1 +0,0 @@
1
- import{StdioLines}from"./chunk-JFC6ZIGA.js";import{workspaceCaller}from"./chunk-53EULX5D.js";import"./chunk-HI5SIUX7.js";import"./chunk-KYNC2BSW.js";import{LocalMcpTools,localTools}from"./chunk-UGOXJEDU.js";import{desktopDeviceConnector}from"./chunk-GKDGSAI5.js";import{LocalMcpFailureSchema}from"./chunk-3KBIDTXT.js";import"./chunk-FX5UVDTH.js";import"./chunk-U5FT4VBR.js";import"./chunk-65X56WAQ.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import"./chunk-UMCOLDHH.js";import"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{z}from"zod";import{homedir}from"node:os";import{join,resolve}from"node:path";import{deserializeMessage,SUPPORTED_PROTOCOL_VERSIONS,LATEST_PROTOCOL_VERSION,serializeMessage,isJSONRPCRequest,isJSONRPCNotification}from"@modelcontextprotocol/client";async function selectedConnector(home,env){const caller=await workspaceCaller(env);if(!caller)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");return desktopDeviceConnector(home,{origin:caller.serverOrigin,tenantId:caller.tenantId,principalId:caller.principalId})}async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const visible=[...tools.names??Object.keys(localTools).filter(name=>!name.startsWith("local_library_"))].sort(),pending=new Map;let initialized=false,closed=false;const frames=new StdioLines(65536);let finish;const ended=new Promise(resolve2=>{finish=resolve2});const send=message=>{if(closed)return;if(output.writableLength>512*1024){close(1);return}output.write(serializeMessage(message))};const error=(id,code,message)=>send({jsonrpc:"2.0",id,error:{code,message}});async function dispatch(r){if(pending.has(r.id)||pending.size>=8){error(r.id,-32e3,"Local request capacity unavailable");return}const abort=new AbortController;const timer=setTimeout(()=>abort.abort(),3e4);pending.set(r.id,abort);try{let result;if(r.method==="initialize"){if(initialized)throw Error();const v=r.params?.protocolVersion;if(typeof v!=="string")throw Error();const protocol=SUPPORTED_PROTOCOL_VERSIONS.includes(v)?v:LATEST_PROTOCOL_VERSION;initialized=true;result={protocolVersion:protocol,serverInfo:{name:"native-studio-local",version:identity.version},capabilities:{tools:{}},instructions:"Use local_navigate and local_capability_describe for scoped guidance. The standard tool list stays stable. Local tools inspect scoped mechanics. Use nvs mcp for workspace, Project and render business actions. Cloud owns native admission. Updates require a human CLI approval; MCP cannot stop or replace Runtime."}}else if(!initialized)throw Error();else if(r.method==="ping")result={};else if(r.method==="tools/list"){if(r.params?.cursor!==void 0)throw Error();result={tools:visible.map(name=>tools.schema(name))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!visible.includes(name))throw Error();let data;try{data=await tools.call(name,r.params?.arguments??{},abort.signal)}catch(cause){const code=cause instanceof z.ZodError?"INVALID_INPUT":cause instanceof NativeStudioSdkError&&["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE"].includes(cause.code)?cause.code:"LOCAL_CAPABILITY_UNAVAILABLE";const failure=LocalMcpFailureSchema.parse({semanticStatus:code==="INVALID_INPUT"?"INVALID_INPUT":"BLOCKED",error:{code,outcome:"NO_WRITE"},nextActions:[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:code==="FORBIDDEN"||code==="AUTHORIZATION_REQUIRED"?"AUTHORIZATION_REQUIRED":"UNAVAILABLE"}]});send({jsonrpc:"2.0",id:r.id,result:{isError:true,content:[{type:"text",text:JSON.stringify(failure)}],structuredContent:failure}});return}result={content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}else{error(r.id,-32601,"Local method unavailable");return}send({jsonrpc:"2.0",id:r.id,result})}catch{error(r.id,-32602,"Local capability unavailable or authorization required")}finally{clearTimeout(timer);pending.delete(r.id)}}function onData(b){try{frames.push(b,line=>{const message=deserializeMessage(line.toString());if(isJSONRPCRequest(message))void dispatch(message);else if(isJSONRPCNotification(message)){if(message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")pending.get(id)?.abort()}}else throw Error();return!closed})}catch{close(1)}}function close(code=0){if(closed)return;closed=true;for(const abort of pending.values())abort.abort();input.off("data",onData);finish(code)}input.on("data",onData);input.once("end",()=>close(frames.incomplete?1:0));input.once("error",()=>close(1));output.once("error",()=>close(1));return{closed:ended,close:async()=>close()}}async function runLocalMcp(argv){try{const flags=new Map;const library=argv.includes("--with-library");if(argv.filter(k=>k==="--with-library").length>1)throw Error();argv=argv.filter(k=>k!=="--with-library");for(let i=0;i<argv.length;i+=2){const k=argv[i],v=argv[i+1];if(!k||!["--connector","--home"].includes(k)||!v||flags.has(k))throw Error();flags.set(k,v)}const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client"));const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const connector=flags.get("--connector")??await selectedConnector(home,env);const tools=await LocalMcpTools.open(resolve(connector),home,library);const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("Local MCP needs a current device connector. Use nvs mcp for workspace, Project and render business tools.\n");return 2}}export{runLocalMcp,serveLocalMcp};
@@ -1,2 +0,0 @@
1
- import{loginLink,openLoginBrowser}from"./chunk-OW6R4MAQ.js";import{readInput}from"./chunk-U5FT4VBR.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import{write}from"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get",skill:"workspace.caller"};var auth=new Set(["--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"]);var fields={find:{"--query":"search","--project":"projectId","--limit":"limit","--next":"next","--attention":"attention"},overview:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},next:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},resume:{"--production":"productionId","--operation":"operationId"},search:{"--query":"query","--project":"projectId","--group":"group","--family":"family","--limit":"limit","--next":"next"},describe:{"--tool":"tool","--project":"projectId","--reference":"schemaCursor"},groups:{"--project":"projectId"},skill:{}};var NavigationCliCommands=new Set([...Object.keys(aliases),"capabilities"]);async function runNavigationCli(argv,stdin,call){const kind=argv[0]==="capabilities"?argv[1]?.startsWith("--")||!argv[1]?"groups":argv[1]:argv[0];const operation=argv[0]==="capabilities"?{groups:"studio.capability.groups",search:"studio.capability.search",describe:"studio.capability.describe"}[kind]:aliases[kind];const offset=argv[0]==="capabilities"&&argv[1]===kind?2:1;if(!operation||!fields[kind])throw Error("INVALID_INPUT");const forwarded=["call",operation],body={},seen=new Set;let input;for(let i=offset;i<argv.length;i+=2){const flag=argv[i],value=argv[i+1];if(!value||value.startsWith("--")||seen.has(flag))throw Error("INVALID_INPUT");seen.add(flag);if(auth.has(flag))forwarded.push(flag,value);else if(flag==="--input"&&kind!=="skill")input=value;else{const key=fields[kind][flag];if(!key)throw Error("INVALID_INPUT");body[key]=flag==="--limit"?Number(value):value}}if(input&&Object.keys(body).length)throw Error("INVALID_INPUT");forwarded.push("--input",input??"-");const generated=async function*(){yield Buffer.from(JSON.stringify(body))};const result=await call(forwarded,input?stdin:generated());return kind==="skill"&&result.exitCode===0?{...result,output:result.output.skill}:result}import{randomBytes,randomUUID,createHash,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function accountSignals(timeout,run){const cancelled=new AbortController,signal=AbortSignal.any([AbortSignal.timeout(timeout),cancelled.signal]);const stop=()=>cancelled.abort();process.once("SIGINT",stop);process.once("SIGTERM",stop);try{return await run(signal)}finally{process.off("SIGINT",stop);process.off("SIGTERM",stop)}}async function runAccountLogin(argv,environment,hooks={}){const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--server","--browser","--timeout-ms"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_LOGIN_INPUT_INVALID");options.set(key,value)}const configured=options.get("--server")??environment.NATIVESTUDIO_STUDIO_ORIGIN;if(!configured)return{exitCode:2,output:{semanticStatus:"NEEDS_INPUT",error:{code:"ACCOUNT_SERVER_REQUIRED",outcome:"NO_WRITE"},nextSteps:["nvs login --server <Studio-origin> (no Project required)"]}};const origin=accountServerOrigin(configured),browser=options.get("--browser")??"auto",timeout=options.get("--timeout-ms")??"180000";if(!["auto","manual"].includes(browser)||!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)accountError("ACCOUNT_LOGIN_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(Number(timeout),async signal=>{if((await readAccount(root))?.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");const client=new NativeStudioAccountClient({serverOrigin:origin});await client.metadata(signal);const verifier=randomBytes(32).toString("base64url"),state=randomBytes(32).toString("base64url"),path="/account-callback/"+randomUUID();let finish,receiving=false,sent=false;const callback=new Promise(done=>{finish=done});const server=createServer({maxHeaderSize:8192,headersTimeout:5e3,requestTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address(),host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(receiving||req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||!req.url.startsWith(path+"?")||req.url.length>2048){res.writeHead(400).end("Invalid account callback.");return}const url=new URL(req.url,`http://${host}`),received=url.searchParams.get("state");const keys=[...url.searchParams.keys()];if(url.pathname!==path||new Set(keys).size!==keys.length||keys.some(k=>!["state","iss","code","error"].includes(k))||!received||Buffer.byteLength(received)!==Buffer.byteLength(state)||!timingSafeEqual(Buffer.from(received),Buffer.from(state))||url.searchParams.get("iss")!==origin||(url.searchParams.has("error")?url.searchParams.get("error")!=="access_denied"||url.searchParams.has("code"):!/^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("code")??""))){res.writeHead(400).end("Invalid account callback.");return}receiving=true;res.end("Account confirmation received. Return to NativeStudio CLI.");finish(url.searchParams.get("code"))});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});const attempt=join(root,"account-login-attempt.json");let attemptFile;try{await new Promise((done,fail)=>{server.once("error",fail);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirectUri=`http://127.0.0.1:${address.port}${path}`;const started=await client.start({redirectUri,state,codeChallenge:createHash("sha256").update(verifier).digest("base64url")},signal);const url=`${origin}/cli-authorize?requestId=${started.requestId}`;signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(url,signal);else{process.stderr.write(`CLI account login request: ${started.requestId}
2
- `);if(browser==="manual")loginLink(url);else await openLoginBrowser(url,signal)}const code=await callback;if(!code)accountError(signal.aborted?signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED":"ACCOUNT_LOGIN_DENIED");const marker={version:1,serverOrigin:origin,requestId:started.requestId,state:"EXCHANGE_UNRESOLVED"};attemptFile=join(root,`account-login-attempt-${started.requestId}.json`);await write(attemptFile,JSON.stringify(marker),true);await write(attempt,JSON.stringify(marker));signal.throwIfAborted();sent=true;const session=await client.exchange({requestId:started.requestId,redirectUri,code,codeVerifier:verifier},signal);if(Date.parse(session.expiresAt)<=Date.now()||Date.parse(session.expiresAt)>Date.now()+36e5+3e4)accountError("ACCOUNT_SESSION_INVALID","UNKNOWN");await saveAccount(root,{version:1,epoch:randomUUID(),state:"ACTIVE",serverOrigin:origin,accessToken:session.accessToken,expiresAt:session.expiresAt,principalId:session.account.principalId,workspaceId:null,projectId:null});await write(attempt,JSON.stringify({...marker,state:"COMPLETED"}));await write(attemptFile,JSON.stringify({...marker,state:"COMPLETED"}));return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",serverOrigin:origin,expiresAt:session.expiresAt,account:session.account,nextSteps:["nvs workspaces","nvs workspace --id <workspace-id>","nvs projects"]}}}catch(error){if(sent){if(error instanceof NativeStudioSdkError&&error.outcome!=="UNKNOWN"){await write(attempt,JSON.stringify({version:1,state:"REJECTED"}));if(attemptFile)await write(attemptFile,JSON.stringify({version:1,state:"REJECTED"}));throw error}accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN")}if(error instanceof NativeStudioSdkError&&error.outcome==="UNKNOWN")accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN");if(signal.aborted)accountError(signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(done=>server.close(()=>done()))}}))}import{randomUUID as randomUUID2}from"node:crypto";import{z}from"zod";var AccountCommands=new Set(["whoami","workspaces","workspace","projects","project","logout"]);async function runAccountCommand(argv,environment){const command=argv[0],options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--id","--limit","--next"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_COMMAND_INPUT_INVALID");options.set(key,value)}if(["workspace","project"].includes(command??"")?options.size!==1||!options.has("--id"):command==="projects"?options.has("--id"):options.size!==0)accountError("ACCOUNT_COMMAND_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(15e3,async signal=>{const stored=await readAccount(root);if(command==="logout"){if(!stored||stored.state==="SIGNED_OUT")return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:false}};const client2=new NativeStudioAccountClient({serverOrigin:stored.serverOrigin,accessToken:stored.accessToken});const pending={...stored,state:"REVOKE_PENDING",workspaceId:null,projectId:null};await saveAccount(root,pending);try{await client2.logout(signal);await saveAccount(root,{...pending,state:"SIGNED_OUT",accessToken:null})}catch{accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN")}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:true,nextSteps:["nvs login --server <Studio-origin>"]}}}const account=requireAccount(stored),client=new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken});if(command==="whoami"||command==="workspaces"||command==="workspace"){const value2=await client.me(signal);if(value2.account.principalId!==account.principalId)accountError("ACCOUNT_IDENTITY_MISMATCH");if(command==="workspace"){const id=z.uuid().parse(options.get("--id"));if(!value2.account.tenants.some(t=>t.id===id))accountError("WORKSPACE_NOT_AUTHORIZED");await saveAccount(root,{...account,workspaceId:id,projectId:account.workspaceId===id?account.projectId:null,epoch:account.workspaceId===id?account.epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:id,nextSteps:["nvs projects"]}}}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",verification:"LIVE_NATIVE_ACCOUNT",...command==="workspaces"?{workspaces:value2.account.tenants}:{account:value2.account,workspaceId:account.workspaceId,projectId:account.projectId,expiresAt:account.expiresAt},nextSteps:["nvs workspace --id <workspace-id>"]}}}if(!account.workspaceId)accountError("WORKSPACE_SELECTION_REQUIRED");if(command==="projects"){const limit=options.has("--limit")?z.coerce.number().int().min(1).max(100).parse(options.get("--limit")):void 0;const value2=await client.projects({tenantId:account.workspaceId,limit,next:options.get("--next")},signal);if(value2.items.some(p=>p.tenantId!==account.workspaceId))accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");return{exitCode:0,output:{semanticStatus:"SUCCESS",...value2,nextSteps:["nvs project --id <project-id>"]}}}if(command!=="project")accountError("ACCOUNT_COMMAND_INPUT_INVALID");const projectId=z.uuid().parse(options.get("--id")),value=await client.project({tenantId:account.workspaceId,projectId},signal);if(value.project.id!==projectId||value.project.tenantId!==account.workspaceId)accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");if(value.project.lifecycle!=="ACTIVE")accountError("PROJECT_ARCHIVED");await saveAccount(root,{...account,projectId});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Use the existing workspace connection; run nvs connect if this workspace is not connected.","nvs status"]}}}))}var exits={SUCCESS:0,ACCEPTED:0,INVALID_INPUT:2,NOT_FOUND:3,BLOCKED:4,CAPABILITY_UNAVAILABLE:4,REVISION_CONFLICT:5};async function runRemoteCli(argv,environment=process.env,stdin=process.stdin){try{if(argv[0]==="connect")return await(await import("./connect-OY623MMA.js")).runConnect(argv,environment);if(argv[0]==="login")return await runAccountLogin(argv,environment);if(argv[0]==="render")return await(await import("./render-main-ATCEBECW.js")).renderCommand(argv.slice(1),environment);if(argv[0]==="devices")return await(await import("./devices-main-LBDRDV2M.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-HIL7NW3L.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-44ECTGHC.js")).workspaceCommand(argv,environment);return business??await runAccountCommand(argv,environment)}if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-QBJ62PIA.js")).runOAuthCommand(argv,stdin);if(!argv.length||argv.length===1&&["help","--help"].includes(argv[0]))return{exitCode:0,output:{product:"NativeStudio CLI",start:["nvs login --server <Studio-origin> \u2014 sign in/register your account in the browser; no project required.","nvs workspaces; nvs workspace --id <id>; nvs projects; nvs project --id <id>","nvs connect (authorizes the selected workspace once; supports its Projects and devices)","nvs status","nvs skill \u2014 read the configured SKILL download URL through the existing connection","nvs find --query <intent>"],navigation:["nvs capabilities","nvs overview --production <uuid>","nvs next --production <uuid>","nvs resume --production <uuid> --operation <op_original>"],agentConnection:{command:"nvs",args:["mcp"],note:"Uses the private saved connection; no token in Agent configuration."},commands:["login --server <Studio-origin> | whoami | logout \u2014 independent account session","workspaces | workspace --id <id> | projects [--limit <n>] [--next <cursor>] | project --id <id>","connect [--mcp-url <workspace-connection-url>] \u2014 authorize the workspace once for its Projects and devices","status","observe --input <scope-json|-> [--max-polls <1..1000>] [--timeout-ms <1..1800000>] \u2014 bounded JSON Lines feedback/events; Ctrl-C ends observation only","skill \u2014 read the configured SKILL download URL/status; no automatic download","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","devices inventory [--device <uuid>] [--after <uuid>] [--limit <1..50>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read Workspace device registration and connection facts; no project required","devices list --kind preview|final|library|<processor-kind> [--project <uuid>] [--device <uuid>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read candidates for this Project task; connection alone does not imply eligibility","devices enroll|revoke|receipt --input <json|-> \u2014 uses the saved tenant OAuth and original native command","render preview|final --production <uuid> --request <stable-uuid> [--project <uuid>] [--device <uuid>] [--validation-mode TENANT_TRUSTED_VALIDATOR] \u2014 tenant device only; saves original receipt","render status|download --kind preview|final --production <uuid> --render <uuid> [--project <uuid>] [--output <file>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates","host help \u2014 enroll/prove/connect an execution device using the external Agent's existing MCP session; discover the separate SKILL URL with nvs skill or workspace_caller.skill"],advanced:["operations","mcp --profile <private-file> | --mcp-url <endpoint> --token-env <NAME>|--token-file <private-file>","call <operation> --input <file|-> --tenant <uuid> --token-env <NAME> --origin <https-origin>","call <operation> --input <file|-> --tenant <uuid> --token-file <private-file> --mcp-url <https-endpoint>","auth-start --profile <new-private-file> --mcp-url <resource> --callback <receiver-url>","auth-complete --profile <private-file> --input <callback-json-file|->","call <operation> --profile <private-file> --tenant <uuid> --input <file|->","import project|original --input <intent.json|-> --file <media> --tenant <uuid> --origin <https-origin> --token-file <private-file>"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{sdkOperations,sdkMcpTools,sdkCarrierDifferences,assertCarrierCoverage}=await import("./src-MRFJOTKK.js");if(argv.length===1&&argv[0]==="operations"){assertCarrierCoverage(sdkOperations,sdkCarrierDifferences);return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null,mcp:sdkMcpTools[name2],carrierDifference:Object.hasOwn(sdkCarrierDifferences,name2)?sdkCarrierDifferences[name2]:null}))}}}const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();if(name==="rough-cut.media-ticket"||name==="final-render.media-ticket")throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile","--transport"];for(let i=0;i<args.length;i+=2){const key2=args[i],value=args[i+1];if(!key2||!allowed.includes(key2)||!value||value.startsWith("--")||options.has(key2))throw Error();options.set(key2,value)}if(!options.has("--input"))throw Error();const key=name;const privateInput=["provider.configure","webhook.configure","webhook.secret.prepare"].includes(key);await defaultConnection(options,environment,true);const input=await readInput(options.get("--input"),stdin,privateInput);const output=await(await import("./remote-client-6XHMNMXK.js")).withRemoteClient(options,environment,sdkMcpTools[key]===null,studio=>studio.call(key,input));const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <workspace-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/workspace before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE",...e?.issues.length?{issues:e.issues}:{}},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["TENANT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <workspace-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
@@ -1 +0,0 @@
1
- import{connectRemoteMcp}from"./chunk-65X56WAQ.js";import"./chunk-2UYKJ6YN.js";import"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.js";export{connectRemoteMcp};
@@ -1 +0,0 @@
1
- import{profileAuthorization,runOAuthCommand}from"./chunk-FX5UVDTH.js";import"./chunk-U5FT4VBR.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.js";export{profileAuthorization,runOAuthCommand};
@@ -1 +0,0 @@
1
- import{withRemoteClient}from"./chunk-BR26X3ZF.js";import{readInput}from"./chunk-U5FT4VBR.js";import{observeProduction}from"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";async function runObservationCli(argv,emit,signal,environment=process.env,stdin=process.stdin){const lifetime=new AbortController;let timer;const observationSignal=AbortSignal.any([signal,lifetime.signal]);try{const options=new Map;const allowed=["--input","--tenant","--profile","--origin","--mcp-url","--token-env","--token-file","--transport","--max-polls","--timeout-ms","--max-events","--max-bytes"];for(let n=0;n<argv.length;n+=2){const key=argv[n],value=argv[n+1];if(!key||!allowed.includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}if(!options.has("--input"))throw Error();const number=key=>{const value=options.get(key);if(value!==void 0&&!/^[1-9][0-9]{0,8}$/.test(value))throw Error();return value===void 0?{}:{[key.slice(2).replace(/-([a-z])/g,(_,x)=>x.toUpperCase())]:Number(value)}};const limits=Object.assign({},...["--max-polls","--timeout-ms","--max-events","--max-bytes"].map(number));const timeout=Number(options.get("--timeout-ms")??3e5);if(!Number.isSafeInteger(timeout)||timeout<1||timeout>18e5)throw Error();timer=setTimeout(()=>lifetime.abort(),timeout);const input=await readInput(options.get("--input"),stdin,false,observationSignal);if(typeof input.productionId!=="string")throw Error();const productionId=input.productionId;await withRemoteClient(options,environment,false,async client=>{for await(const page of observeProduction(client,{...input,productionId},{...limits,signal:observationSignal})){observationSignal.throwIfAborted();await emit({kind:"production.events",data:page},observationSignal)}},{signal:observationSignal,maxJsonBytes:128*1024});await emit({kind:"observation.ended",reason:"POLL_LIMIT",nativeWorkCancelled:false},observationSignal);return 0}catch(error){if(signal.aborted)return 130;if(lifetime.signal.aborted)return 0;const e=error instanceof NativeStudioSdkError?error:null;await emit({kind:"observation.ended",reason:lifetime.signal.aborted?"OBSERVATION_LIMIT":e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE",nativeWorkCancelled:false},observationSignal).catch(()=>{});return lifetime.signal.aborted||e?.code==="OBSERVATION_LIMIT"?0:e?4:2}finally{if(timer)clearTimeout(timer);lifetime.abort()}}async function runObservationEntry(argv){const controller=new AbortController;const stop=()=>controller.abort();process.on("SIGINT",stop);process.on("SIGTERM",stop);try{return await runObservationCli(argv,(value,writeSignal)=>new Promise((resolve,reject)=>{if(writeSignal.aborted){reject(writeSignal.reason);return}const aborted=()=>{cleanup();reject(writeSignal.reason)};const failed=error=>{cleanup();controller.abort();reject(error)};const cleanup=()=>{writeSignal.removeEventListener("abort",aborted);process.stdout.off("error",failed)};writeSignal.addEventListener("abort",aborted,{once:true});process.stdout.once("error",failed);process.stdout.write(JSON.stringify(value)+"\n",error=>{cleanup();if(error)reject(error);else resolve()})}),controller.signal)}finally{controller.abort();process.stdin.pause();process.off("SIGINT",stop);process.off("SIGTERM",stop)}}export{runObservationEntry};
@@ -1 +0,0 @@
1
- import{withRemoteClient}from"./chunk-BR26X3ZF.js";import"./chunk-U5FT4VBR.js";import"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.js";export{withRemoteClient};
@@ -1 +0,0 @@
1
- import{callerRenderConnection}from"./chunk-HI5SIUX7.js";import"./chunk-KYNC2BSW.js";import"./chunk-FX5UVDTH.js";import"./chunk-U5FT4VBR.js";import"./chunk-65X56WAQ.js";import"./chunk-2UYKJ6YN.js";import{DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,PreparedDeviceRenderSchema}from"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import{clientHome}from"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import{directory,optional,sha256,write}from"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{z}from"zod";import{join,resolve}from"node:path";async function assertRenderProject(studio,scope,productionId,options){const snapshot=await studio.call("production.snapshot",{productionId},options);if(snapshot.tenantId!==scope.tenantId||snapshot.projectId!==scope.projectId||snapshot.productionId!==productionId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}var receipt=z.strictObject({scope:z.string(),intent:DeviceRenderIntentSchema,prepared:PreparedDeviceRenderSchema});async function renderCommand(argv,env){const[kind,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const k=args[i],v=args[i+1];if(!k||!v||v.startsWith("--")||flags.has(k)||!["--production","--project","--request","--device","--profile-id","--validation-mode","--kind","--render","--role","--output","--mcp-url","--token-file"].includes(k))throw Error();flags.set(k,v)}if(kind==="status"||kind==="download"){const allowed=new Set(["--kind","--project","--production","--render","--mcp-url","--token-file",...kind==="download"?["--role","--output"]:[]]);if(Array.from(flags.keys()).some(key=>!allowed.has(key)))throw Error();const input=DeviceRenderReadSchema.parse({kind:flags.get("--kind"),productionId:flags.get("--production"),renderId:flags.get("--render")});const conn2=await callerRenderConnection(env,flags,false);try{if(kind==="status"){const view=await conn2.studio.deviceRenders.get(input);if(view.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return{exitCode:0,output:view}}const filename=flags.get("--output");if(!filename)throw Error();const request=DeviceRenderDownloadSchema.parse({...input,role:flags.get("--role")??"VIDEO"});const output=await conn2.studio.deviceRenders.download(request,void 0,conn2.scope.projectId);if(output.object.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await write(resolve(filename),output.bytes,true);return{exitCode:0,output:{semanticStatus:"SUCCESS",renderId:output.renderId,representationId:output.representationId,byteSize:output.object.byteSize,checksumSha256:output.object.checksumSha256}}}finally{await conn2.close().catch(()=>{})}}if(["--kind","--render","--role","--output"].some(key=>flags.has(key)))throw Error();const intent=DeviceRenderIntentSchema.parse({kind,productionId:flags.get("--production"),idempotencyKey:z.uuid().parse(flags.get("--request")),...flags.has("--device")?{deviceId:flags.get("--device")}:{},...flags.has("--profile-id")?{profileId:flags.get("--profile-id")}:{},...flags.has("--validation-mode")?{validationMode:flags.get("--validation-mode")}:{}});const conn=await callerRenderConnection(env,flags);const binding=conn.scope.resource+"#"+sha256(conn.scope.profile)+"#"+conn.scope.projectId;try{await assertRenderProject(conn.studio,conn.scope,intent.productionId);const root=await directory(join(await clientHome(env,true),"renders"));const prefix=join(root,sha256(binding+"\n"+intent.idempotencyKey));const previous=await optional(prefix+".request.json");if(previous){const old=receipt.parse(previous);if(old.scope!==binding||JSON.stringify(old.intent)!==JSON.stringify(intent))throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");const result=await optional(prefix+".result.json");if(result)return{exitCode:0,output:result};const failure=await optional(prefix+".failure.json");if(failure)return{exitCode:1,output:{semanticStatus:"BLOCKED",error:failure}};try{const recovered=await conn.studio.deviceRenders.receipt(old.prepared);await write(prefix+".result.json",JSON.stringify(recovered),true);return{exitCode:0,output:recovered}}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="REVISION_CONFLICT")throw error}return{exitCode:1,output:{semanticStatus:"BLOCKED",error:{code:"OUTCOME_UNKNOWN",outcome:"UNKNOWN"},idempotencyKey:intent.idempotencyKey,productionId:intent.productionId,nextAction:"Repeat this command with the original request ID to observe its receipt."}}}const prepared=await conn.studio.deviceRenders.prepare(intent);await write(prefix+".request.json",JSON.stringify({scope:binding,intent,prepared}),true);let output;try{output=await conn.studio.deviceRenders.start(prepared)}catch(e){if(e instanceof NativeStudioSdkError&&e.outcome!=="UNKNOWN")await write(prefix+".failure.json",JSON.stringify({code:e.code,outcome:e.outcome,semanticStatus:e.semanticStatus}),true);throw e}try{await write(prefix+".result.json",JSON.stringify(output),true)}catch{throw new NativeStudioSdkError("OUTCOME_UNKNOWN","BLOCKED","UNKNOWN")}return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{renderCommand};
@@ -1 +0,0 @@
1
- import{profileAuthorization}from"./chunk-FX5UVDTH.js";import{readCredential,readInput}from"./chunk-U5FT4VBR.js";import{NativeStudioAgentClient}from"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import{profileHttpOrigin}from"./chunk-UMCOLDHH.js";import{defaultConnection,tenantConnection}from"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.js";import{constants,open}from"node:fs/promises";async function sourceBytes(path,maxBytes){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size<1||stat.size>maxBytes)throw Error();const bytes=Buffer.alloc(stat.size);let offset=0;while(offset<bytes.length){const{bytesRead}=await file.read(bytes,offset,bytes.length-offset,offset);if(!bytesRead)throw Error();offset+=bytesRead}if((await file.read(Buffer.alloc(1),0,1,offset)).bytesRead)throw Error();return bytes}finally{await file.close()}}async function importSourceCommand([kind,...args],env,stdin){if(kind!=="project"&&kind!=="original")throw Error();const flags=new Map;for(let index=0;index<args.length;index+=2){const name=args[index],value=args[index+1];if(!name||!value||value.startsWith("--")||flags.has(name)||!["--input","--file","--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"].includes(name))throw Error();flags.set(name,value)}await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile?["--origin","--mcp-url","--token-env","--token-file"].some(key=>flags.has(key)):flags.has("--origin")===flags.has("--mcp-url"))throw Error();const connected=profile?await profileAuthorization(profile):null;const resource=connected?.resource??flags.get("--mcp-url");const scope=resource?tenantConnection(resource):null;if(scope&&flags.has("--tenant")&&flags.get("--tenant")!==scope.tenantId)throw Error();const input=flags.get("--input"),file=flags.get("--file"),tenantId=scope?.tenantId??flags.get("--tenant"),baseUrl=flags.get("--origin")??(connected&&profile?await profileHttpOrigin(profile,connected.resource):resource?new URL(resource).origin:void 0);if(!input||!file||!tenantId||!baseUrl)throw Error();const authorization=connected?.authorization??await readCredential(flags,env);const studio=new NativeStudioAgentClient({tenantId,baseUrl,authorization:()=>authorization});const intent=await readInput(input,stdin);const bytes=await sourceBytes(file,(kind==="project"?8:128)*1024*1024);const receipt=kind==="project"?await studio.directSources.importProjectSource(intent,bytes):await studio.directSources.importOriginal(intent,bytes);if(receipt.state==="SUBMITTED")return{exitCode:0,output:receipt};const output="registration"in receipt?{artifactId:receipt.registration.artifact.id,representationId:receipt.registration.primaryRepresentation.id}:{artifactId:receipt.original.artifactId,representationId:receipt.original.representationId,sourceId:receipt.original.sourceId,version:receipt.original.version};return{exitCode:0,output:{state:receipt.state,...output}}}export{importSourceCommand};
@@ -1 +0,0 @@
1
- import{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,LocalLibraryCommandStatusSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,assertCarrierCoverage,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,sdkCarrierDifferences,sdkImageMediaTools,sdkMcpTools,sdkOperations,verifyWebhookNotification,waitForOperation}from"./chunk-4NJIT52T.js";import{FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,ProjectDeviceListSchema,RoughCutViewSchema}from"./chunk-C7CSZFV6.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-HTUTYIRU.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,assertCarrierCoverage,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,sdkCarrierDifferences,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,verifyWebhookNotification,waitForOperation};
@@ -1 +0,0 @@
1
- import{StdioLines}from"./chunk-JFC6ZIGA.js";import{readCredential}from"./chunk-U5FT4VBR.js";import{defaultConnection}from"./chunk-TWC3NXFA.js";import{FileOAuthProvider}from"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import{secureEndpoint}from"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.js";async function stdioRelayConfig(argv,environment){const options=new Map;for(let i=0;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--profile","--mcp-url","--token-env","--token-file","--timeout-ms","--discovery"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}await defaultConnection(options,environment,false);const discovery=options.get("--discovery");if(discovery!==void 0&&discovery!=="contextual-v1")throw Error();const timeout=options.get("--timeout-ms")??"30000";if(!/^\d+$/.test(timeout))throw Error();const timeoutMs=Number(timeout);if(!Number.isSafeInteger(timeoutMs)||timeoutMs<100||timeoutMs>3e5)throw Error();const profile=options.get("--profile");let endpoint,read;if(profile){if(options.has("--mcp-url")||options.has("--token-env")||options.has("--token-file"))throw Error();endpoint=secureEndpoint((await FileOAuthProvider.load(profile)).data.resource);read=async signal=>{const{profileAuthorization}=await import("./oauth-QBJ62PIA.js");const value=await profileAuthorization(profile,signal);if(secureEndpoint(value.resource).href!==endpoint.href)throw Error();return value.authorization}}else{if(!options.has("--mcp-url"))throw Error();endpoint=secureEndpoint(options.get("--mcp-url"));await readCredential(options,environment);read=()=>readCredential(options,environment)}let tail=Promise.resolve();return{endpoint,timeoutMs,...discovery?{discovery}:{},authorization(signal){const current=tail.then(()=>{signal.throwIfAborted();return read(signal)});tail=current.catch(()=>{});return current}}}import{isJSONRPCResultResponse}from"@modelcontextprotocol/client";var StdioContextualMenu=class{clear(){}request(request){return request}response(request,message){if(request.method!=="initialize"||!isJSONRPCResultResponse(message))return message;return{...message,result:{...message.result,instructions:["Navigation guidance: standard tools/list is stable. Begin with workspace_caller, then discover missing capabilities with studio_capability_groups/search/describe. Execute discovered reads through studio_capability_query and writes through studio_capability_invoke, passing the original complete input under arguments. Capability names such as studio_start and studio_navigate are targets, not additional menu tools. Describe never installs tools. Follow native evidence, inspect links and exact original request identities; reconcile uncertain writes without replay.",...typeof message.result.instructions==="string"?[message.result.instructions]:[]].join("\n")}}}};import{StreamableHTTPClientTransport,deserializeMessage,serializeMessage,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse as isJSONRPCResultResponse2,isJSONRPCErrorResponse}from"@modelcontextprotocol/client";var STDIO_RESPONSE_LIMIT=32*1024*1024;function stdioRelayFetch(config,shutdown){return async(input,init)=>{const target=new URL(input instanceof Request?input.url:String(input));if(target.href!==config.endpoint.href)throw Error();const signal=AbortSignal.any([shutdown,...init?.signal?[init.signal]:[],AbortSignal.timeout(config.timeoutMs)]);const authorization=await config.authorization(signal);signal.throwIfAborted();const headers=new Headers(init?.headers);headers.set("authorization",authorization);const response=await fetch(input,{...init,headers,signal,redirect:"error"});if(!response.body)return response;const declared=response.headers.get("content-length");if(declared&&(!/^\d+$/.test(declared)||Number(declared)>STDIO_RESPONSE_LIMIT)){await response.body.cancel();throw Error()}const reader=response.body.getReader();let size=0;const body=new ReadableStream({async pull(controller){try{const part=await reader.read();if(part.done){reader.releaseLock();controller.close();return}size+=part.value.byteLength;if(size>STDIO_RESPONSE_LIMIT){await reader.cancel();throw Error()}controller.enqueue(part.value)}catch(error){controller.error(error)}},async cancel(reason){await reader.cancel(reason);reader.releaseLock()}});return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}}var inputLimit=18*1024*1024;var concurrency=32;async function serveRemoteMcpStdio(config,input,output){const shutdown=new AbortController;const pending=new Map;const transport=new StreamableHTTPClientTransport(config.endpoint,{fetch:stdioRelayFetch(config,shutdown.signal),onInsufficientScope:"throw",reconnectionOptions:{maxRetries:0,maxReconnectionDelay:1,initialReconnectionDelay:1,reconnectionDelayGrowFactor:1}});const lines=new StdioLines(inputLimit);let queuedBytes=0,sends=0,stopped=false;let finish;const closed=new Promise(resolve=>{finish=resolve});const menu=config.discovery==="contextual-v1"?new StdioContextualMenu:void 0;function discard(id){const item=pending.get(id);if(item)clearTimeout(item.timer);pending.delete(id);return item}function write(message){if(stopped)return;const frame=serializeMessage(message);const bytes=Buffer.byteLength(frame);if(bytes>STDIO_RESPONSE_LIMIT||queuedBytes+bytes>STDIO_RESPONSE_LIMIT){void close(1);return}queuedBytes+=bytes;output.write(frame,error=>{queuedBytes-=bytes;if(error)void close(1)})}function fail(id,noWrite=false){const item=discard(id);item?.abort.abort();write({jsonrpc:"2.0",id,error:{code:-32603,message:"Remote MCP request unavailable",data:{semanticStatus:"INTERNAL_OPERATIONAL_FAILURE",outcome:noWrite?"NO_WRITE":"UNKNOWN"}}})}async function forward(message){if(isJSONRPCNotification(message)&&message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")discard(id)?.abort.abort();if((transport.protocolVersion??"")>="2026-07-28")return}const request=isJSONRPCRequest(message)?message:null;if(request&&(pending.has(request.id)||pending.size>=concurrency||sends>=concurrency)){if(pending.has(request.id)){void close(2);return}fail(request.id,true);return}if(!request&&sends>=concurrency){void close(2);return}if(request){const version=request.method==="initialize"?request.params?.protocolVersion:request.params?._meta?.["io.modelcontextprotocol/protocolVersion"];if(typeof version==="string")transport.setProtocolVersion(version);const abort=new AbortController;const timer=setTimeout(()=>{if(pending.has(request.id))fail(request.id)},config.timeoutMs);timer.unref();pending.set(request.id,{abort,timer,request})}sends++;try{await transport.send(request&&menu?menu.request(request):message,request?{requestSignal:pending.get(request.id).abort.signal,onRequestStreamEnd:()=>{if(pending.has(request.id))fail(request.id)}}:{requestSignal:shutdown.signal})}catch{if(request&&pending.has(request.id))fail(request.id)}finally{sends--}}transport.onmessage=message=>{if(isJSONRPCResultResponse2(message)||isJSONRPCErrorResponse(message)){if(message.id===void 0)return;const item=discard(message.id);if(!item)return;if(item.request.method==="initialize"&&isJSONRPCResultResponse2(message)&&typeof message.result.protocolVersion==="string")transport.setProtocolVersion(message.result.protocolVersion);if(menu)message=menu.response(item.request,message)}if(isJSONRPCNotification(message)&&message.method==="notifications/tools/list_changed")menu?.clear();write(message)};transport.onerror=()=>{};function data(chunk){if(stopped)return;const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);try{lines.push(bytes,line=>{void forward(deserializeMessage(new TextDecoder("utf-8",{fatal:true}).decode(line)));return!stopped})}catch{void close(2)}}function end(){void close(lines.incomplete?2:0)}function streamError(){void close(1)}async function close(code=0){if(stopped)return;stopped=true;shutdown.abort();for(const item of pending.values()){clearTimeout(item.timer);item.abort.abort()}pending.clear();menu?.clear();lines.clear();input.off("data",data).off("end",end).off("error",streamError);input.pause();output.off("error",streamError);try{await transport.close()}catch{code||=1}finish(code)}await transport.start();input.on("data",data).once("end",end).once("error",streamError);output.once("error",streamError);return{close,closed}}async function runMcpStdio(argv,environment){try{const config=await stdioRelayConfig(argv,environment);const handle=await serveRemoteMcpStdio(config,process.stdin,process.stdout);const stop=()=>{void handle.close()};process.once("SIGINT",stop);process.once("SIGTERM",stop);const code=await handle.closed;process.off("SIGINT",stop);process.off("SIGTERM",stop);if(code)process.stderr.write("NativeStudio MCP stdio connection failed.\n");return code}catch{process.stderr.write("NativeStudio MCP stdio configuration failed; run nvs status and nvs connect after account sign-in, or use explicit credentials.\n");return 2}}export{runMcpStdio};
@@ -1 +0,0 @@
1
- import{workspaceCommand,workspaceProject}from"./chunk-KYNC2BSW.js";import"./chunk-FX5UVDTH.js";import"./chunk-U5FT4VBR.js";import"./chunk-65X56WAQ.js";import"./chunk-2UYKJ6YN.js";import"./chunk-4NJIT52T.js";import"./chunk-C7CSZFV6.js";import"./chunk-TWC3NXFA.js";import"./chunk-SKAVQ4UW.js";import"./chunk-RUPH3HZ2.js";import"./chunk-CW67UB2I.js";import"./chunk-HAOCQVMU.js";import"./chunk-KOCUZ3AE.js";import"./chunk-HTUTYIRU.js";export{workspaceCommand,workspaceProject};